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; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 7 | use std::convert::TryFrom; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 8 | use std::error::Error as StdError; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 9 | use std::ffi::CStr; |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 10 | use std::fmt::{self, Display}; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 11 | use std::fs::{File, OpenOptions}; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 12 | use std::io::{self, stdin, Read}; |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 13 | use std::mem; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 14 | use std::net::Ipv4Addr; |
Daniel Verkamp | 6f9215c | 2019-08-20 09:41:22 -0700 | [diff] [blame] | 15 | #[cfg(feature = "gpu")] |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 16 | use std::num::NonZeroU8; |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 17 | use std::num::ParseIntError; |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 18 | use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 19 | use std::os::unix::net::UnixStream; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 20 | use std::path::{Path, PathBuf}; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 21 | use std::str; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 22 | use std::sync::{Arc, Barrier}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 23 | use std::thread; |
| 24 | use std::thread::JoinHandle; |
Daniel Prilik | 2200604 | 2019-01-14 14:19:04 -0800 | [diff] [blame] | 25 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 26 | |
David Tolnay | 41a6f84 | 2019-03-01 16:18:44 -0800 | [diff] [blame] | 27 | use libc::{self, c_int, gid_t, uid_t}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 28 | |
Dylan Reid | 3082e8e | 2019-01-07 10:33:48 -0800 | [diff] [blame] | 29 | use audio_streams::DummyStreamSource; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 30 | use devices::virtio::{self, VirtioDevice}; |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 31 | use devices::{ |
| 32 | self, HostBackendDeviceProvider, PciDevice, VfioDevice, VfioPciDevice, VirtioPciDevice, |
| 33 | XhciController, |
| 34 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 35 | use io_jail::{self, Minijail}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 36 | use kvm::*; |
paulhsia | f052cfe | 2019-01-22 15:22:25 +0800 | [diff] [blame] | 37 | use libcras::CrasClient; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 38 | use msg_socket::{MsgError, MsgReceiver, MsgSender, MsgSocket}; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 39 | use net_util::{Error as NetError, MacAddress, Tap}; |
Daniel Prilik | 2200604 | 2019-01-14 14:19:04 -0800 | [diff] [blame] | 40 | use rand_ish::SimpleRng; |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 41 | use remain::sorted; |
Xiong Zhang | 87a3b44 | 2019-10-29 17:32:44 +0800 | [diff] [blame] | 42 | use resources::{Alloc, MmioType, SystemAllocator}; |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 43 | use sync::{Condvar, Mutex}; |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 44 | use sys_util::net::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener}; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 45 | |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 46 | use sys_util::{ |
David Tolnay | 633426a | 2019-04-12 12:18:35 -0700 | [diff] [blame] | 47 | self, block_signal, clear_signal, drop_capabilities, error, flock, get_blocked_signals, |
Fletcher Woodruff | 82ff397 | 2019-10-02 13:11:34 -0600 | [diff] [blame] | 48 | get_group_id, get_user_id, getegid, geteuid, info, register_rt_signal_handler, |
| 49 | set_cpu_affinity, validate_raw_fd, warn, EventFd, FlockOperation, GuestAddress, GuestMemory, |
| 50 | Killable, MemoryMapping, PollContext, PollToken, Protection, SignalFd, Terminal, TimerFd, |
| 51 | WatchingEvents, SIGRTMIN, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 52 | }; |
Jason D. Clinton | 865323d | 2017-09-27 22:04:03 -0600 | [diff] [blame] | 53 | use vhost; |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 54 | use vm_control::{ |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 55 | BalloonControlCommand, BalloonControlRequestSocket, BalloonControlResponseSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 56 | DiskControlCommand, DiskControlRequestSocket, DiskControlResponseSocket, DiskControlResult, |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 57 | UsbControlSocket, VmControlResponseSocket, VmIrqRequest, VmIrqResponse, VmIrqResponseSocket, |
| 58 | VmMemoryControlRequestSocket, VmMemoryControlResponseSocket, VmMemoryRequest, VmMemoryResponse, |
| 59 | VmRunMode, |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 60 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 61 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 62 | use crate::{Config, DiskOption, Executable, SharedDir, SharedDirKind, TouchDeviceOption}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 63 | |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 64 | use arch::{self, LinuxArch, RunnableLinuxVm, VirtioDeviceStub, VmComponents, VmImage}; |
Sonny Rao | ed517d1 | 2018-02-13 22:09:43 -0800 | [diff] [blame] | 65 | |
Sonny Rao | 2ffa0cb | 2018-02-26 17:27:40 -0800 | [diff] [blame] | 66 | #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
| 67 | use aarch64::AArch64 as Arch; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 68 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 69 | use x86_64::X8664arch as Arch; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 70 | |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 71 | #[cfg(feature = "gpu-forward")] |
David Tolnay | aecf9a4 | 2019-04-11 14:30:00 -0700 | [diff] [blame] | 72 | use render_node_forward::*; |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 73 | #[cfg(not(feature = "gpu-forward"))] |
| 74 | type RenderNodeHost = (); |
| 75 | |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 76 | #[sorted] |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 77 | #[derive(Debug)] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 78 | pub enum Error { |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 79 | AddGpuDeviceMemory(sys_util::Error), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 80 | AddPmemDeviceMemory(sys_util::Error), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 81 | AllocateGpuDeviceAddress, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 82 | AllocatePmemDeviceAddress(resources::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 83 | BalloonDeviceNew(virtio::BalloonError), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 84 | BlockDeviceNew(sys_util::Error), |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 85 | BlockSignal(sys_util::signal::Error), |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 86 | BuildVm(<Arch as LinuxArch>::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 87 | ChownTpmStorage(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 88 | CloneEventFd(sys_util::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 89 | CreateCrasClient(libcras::Error), |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 90 | CreateDiskError(disk::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 91 | CreateEventFd(sys_util::Error), |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 92 | CreatePollContext(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 93 | CreateSignalFd(sys_util::SignalFdError), |
| 94 | CreateSocket(io::Error), |
Chirantan Ekbote | 49fa08f | 2018-11-16 13:26:53 -0800 | [diff] [blame] | 95 | CreateTapDevice(NetError), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 96 | CreateTimerFd(sys_util::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 97 | CreateTpmStorage(PathBuf, io::Error), |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 98 | CreateUsbProvider(devices::usb::host_backend::error::Error), |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 99 | CreateVfioDevice(devices::vfio::VfioError), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 100 | DeviceJail(io_jail::Error), |
| 101 | DevicePivotRoot(io_jail::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 102 | Disk(io::Error), |
Stephen Barber | c79de2d | 2018-02-21 14:17:27 -0800 | [diff] [blame] | 103 | DiskImageLock(sys_util::Error), |
Dmitry Torokhov | 7100607 | 2019-03-06 10:56:51 -0800 | [diff] [blame] | 104 | DropCapabilities(sys_util::Error), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 105 | FsDeviceNew(virtio::fs::Error), |
| 106 | GetMaxOpenFiles(io::Error), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 107 | InputDeviceNew(virtio::InputError), |
| 108 | InputEventsOpen(std::io::Error), |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 109 | InvalidFdPath, |
Zach Reizner | 579bd2c | 2018-09-14 15:43:33 -0700 | [diff] [blame] | 110 | InvalidWaylandPath, |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 111 | IoJail(io_jail::Error), |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 112 | LoadKernel(Box<dyn StdError>), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 113 | NetDeviceNew(virtio::NetError), |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 114 | OpenAndroidFstab(PathBuf, io::Error), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 115 | OpenBios(PathBuf, io::Error), |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 116 | OpenInitrd(PathBuf, io::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 117 | OpenKernel(PathBuf, io::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 118 | OpenVinput(PathBuf, io::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 119 | P9DeviceNew(virtio::P9Error), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 120 | ParseMaxOpenFiles(ParseIntError), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 121 | PivotRootDoesntExist(&'static str), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 122 | PmemDeviceImageTooBig, |
| 123 | PmemDeviceNew(sys_util::Error), |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 124 | PollContextAdd(sys_util::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 125 | PollContextDelete(sys_util::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 126 | ReadLowmemAvailable(io::Error), |
| 127 | ReadLowmemMargin(io::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 128 | RegisterBalloon(arch::DeviceRegistrationError), |
| 129 | RegisterBlock(arch::DeviceRegistrationError), |
| 130 | RegisterGpu(arch::DeviceRegistrationError), |
| 131 | RegisterNet(arch::DeviceRegistrationError), |
| 132 | RegisterP9(arch::DeviceRegistrationError), |
| 133 | RegisterRng(arch::DeviceRegistrationError), |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 134 | RegisterSignalHandler(sys_util::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 135 | RegisterWayland(arch::DeviceRegistrationError), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 136 | ReserveGpuMemory(sys_util::MmapError), |
| 137 | ReserveMemory(sys_util::Error), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 138 | ReservePmemMemory(sys_util::MmapError), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 139 | ResetTimerFd(sys_util::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 140 | RngDeviceNew(virtio::RngError), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 141 | SettingGidMap(io_jail::Error), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 142 | SettingMaxOpenFiles(io_jail::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 143 | SettingUidMap(io_jail::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 144 | SignalFd(sys_util::SignalFdError), |
| 145 | SpawnVcpu(io::Error), |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 146 | TimerFd(sys_util::Error), |
Chirantan Ekbote | 2d29233 | 2018-11-16 11:35:24 -0800 | [diff] [blame] | 147 | ValidateRawFd(sys_util::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 148 | VhostNetDeviceNew(virtio::vhost::Error), |
| 149 | VhostVsockDeviceNew(virtio::vhost::Error), |
Daniel Verkamp | 56f283b | 2018-10-05 11:40:59 -0700 | [diff] [blame] | 150 | VirtioPciDev(sys_util::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 151 | WaylandDeviceNew(sys_util::Error), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 152 | } |
| 153 | |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 154 | impl Display for Error { |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 155 | #[remain::check] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 156 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 157 | use self::Error::*; |
| 158 | |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 159 | #[sorted] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 160 | match self { |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 161 | AddGpuDeviceMemory(e) => write!(f, "failed to add gpu device memory: {}", e), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 162 | AddPmemDeviceMemory(e) => write!(f, "failed to add pmem device memory: {}", e), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 163 | AllocateGpuDeviceAddress => write!(f, "failed to allocate gpu device guest address"), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 164 | AllocatePmemDeviceAddress(e) => { |
| 165 | write!(f, "failed to allocate memory for pmem device: {}", e) |
| 166 | } |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 167 | BalloonDeviceNew(e) => write!(f, "failed to create balloon: {}", e), |
| 168 | BlockDeviceNew(e) => write!(f, "failed to create block device: {}", e), |
| 169 | BlockSignal(e) => write!(f, "failed to block signal: {}", e), |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 170 | BuildVm(e) => write!(f, "The architecture failed to build the vm: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 171 | ChownTpmStorage(e) => write!(f, "failed to chown tpm storage: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 172 | CloneEventFd(e) => write!(f, "failed to clone eventfd: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 173 | CreateCrasClient(e) => write!(f, "failed to create cras client: {}", e), |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 174 | CreateDiskError(e) => write!(f, "failed to create virtual disk: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 175 | CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e), |
| 176 | CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), |
| 177 | CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e), |
| 178 | CreateSocket(e) => write!(f, "failed to create socket: {}", e), |
| 179 | CreateTapDevice(e) => write!(f, "failed to create tap device: {}", e), |
| 180 | CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 181 | CreateTpmStorage(p, e) => { |
| 182 | write!(f, "failed to create tpm storage dir {}: {}", p.display(), e) |
| 183 | } |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 184 | CreateUsbProvider(e) => write!(f, "failed to create usb provider: {}", e), |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 185 | CreateVfioDevice(e) => write!(f, "Failed to create vfio device {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 186 | DeviceJail(e) => write!(f, "failed to jail device: {}", e), |
| 187 | DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e), |
| 188 | Disk(e) => write!(f, "failed to load disk image: {}", e), |
| 189 | DiskImageLock(e) => write!(f, "failed to lock disk image: {}", e), |
Dmitry Torokhov | 7100607 | 2019-03-06 10:56:51 -0800 | [diff] [blame] | 190 | DropCapabilities(e) => write!(f, "failed to drop process capabilities: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 191 | FsDeviceNew(e) => write!(f, "failed to create fs device: {}", e), |
| 192 | GetMaxOpenFiles(e) => write!(f, "failed to get max number of open files: {}", e), |
David Tolnay | 64cd5ea | 2019-04-15 15:56:35 -0700 | [diff] [blame] | 193 | InputDeviceNew(e) => write!(f, "failed to set up input device: {}", e), |
| 194 | InputEventsOpen(e) => write!(f, "failed to open event device: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 195 | InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"), |
| 196 | InvalidWaylandPath => write!(f, "wayland socket path has no parent or file name"), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 197 | IoJail(e) => write!(f, "{}", e), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 198 | LoadKernel(e) => write!(f, "failed to load kernel: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 199 | NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 200 | OpenAndroidFstab(p, e) => write!( |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 201 | f, |
| 202 | "failed to open android fstab file {}: {}", |
| 203 | p.display(), |
| 204 | e |
| 205 | ), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 206 | OpenBios(p, e) => write!(f, "failed to open bios {}: {}", p.display(), e), |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 207 | OpenInitrd(p, e) => write!(f, "failed to open initrd {}: {}", p.display(), e), |
| 208 | OpenKernel(p, e) => write!(f, "failed to open kernel image {}: {}", p.display(), e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 209 | OpenVinput(p, e) => write!(f, "failed to open vinput device {}: {}", p.display(), e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 210 | P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 211 | ParseMaxOpenFiles(e) => write!(f, "failed to parse max number of open files: {}", e), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 212 | PivotRootDoesntExist(p) => write!(f, "{} doesn't exist, can't jail devices.", p), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 213 | PmemDeviceImageTooBig => { |
| 214 | write!(f, "failed to create pmem device: pmem device image too big") |
| 215 | } |
| 216 | PmemDeviceNew(e) => write!(f, "failed to create pmem device: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 217 | PollContextAdd(e) => write!(f, "failed to add fd to poll context: {}", e), |
| 218 | PollContextDelete(e) => write!(f, "failed to remove fd from poll context: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 219 | ReadLowmemAvailable(e) => write!( |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 220 | f, |
| 221 | "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}", |
| 222 | e |
| 223 | ), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 224 | ReadLowmemMargin(e) => write!( |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 225 | f, |
| 226 | "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", |
| 227 | e |
| 228 | ), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 229 | RegisterBalloon(e) => write!(f, "error registering balloon device: {}", e), |
| 230 | RegisterBlock(e) => write!(f, "error registering block device: {}", e), |
| 231 | RegisterGpu(e) => write!(f, "error registering gpu device: {}", e), |
| 232 | RegisterNet(e) => write!(f, "error registering net device: {}", e), |
| 233 | RegisterP9(e) => write!(f, "error registering 9p device: {}", e), |
| 234 | RegisterRng(e) => write!(f, "error registering rng device: {}", e), |
| 235 | RegisterSignalHandler(e) => write!(f, "error registering signal handler: {}", e), |
| 236 | RegisterWayland(e) => write!(f, "error registering wayland device: {}", e), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 237 | ReserveGpuMemory(e) => write!(f, "failed to reserve gpu memory: {}", e), |
| 238 | ReserveMemory(e) => write!(f, "failed to reserve memory: {}", e), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 239 | ReservePmemMemory(e) => write!(f, "failed to reserve pmem memory: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 240 | ResetTimerFd(e) => write!(f, "failed to reset timerfd: {}", e), |
| 241 | RngDeviceNew(e) => write!(f, "failed to set up rng: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 242 | SettingGidMap(e) => write!(f, "error setting GID map: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 243 | SettingMaxOpenFiles(e) => write!(f, "error setting max open files: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 244 | SettingUidMap(e) => write!(f, "error setting UID map: {}", e), |
| 245 | SignalFd(e) => write!(f, "failed to read signal fd: {}", e), |
| 246 | SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e), |
| 247 | TimerFd(e) => write!(f, "failed to read timer fd: {}", e), |
| 248 | ValidateRawFd(e) => write!(f, "failed to validate raw fd: {}", e), |
| 249 | VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {}", e), |
| 250 | VhostVsockDeviceNew(e) => write!(f, "failed to set up virtual socket device: {}", e), |
| 251 | VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e), |
| 252 | WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 257 | impl From<io_jail::Error> for Error { |
| 258 | fn from(err: io_jail::Error) -> Self { |
| 259 | Error::IoJail(err) |
| 260 | } |
| 261 | } |
| 262 | |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 263 | impl std::error::Error for Error {} |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 264 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 265 | type Result<T> = std::result::Result<T, Error>; |
| 266 | |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 267 | enum TaggedControlSocket { |
| 268 | Vm(VmControlResponseSocket), |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 269 | VmMemory(VmMemoryControlResponseSocket), |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 270 | VmIrq(VmIrqResponseSocket), |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 271 | } |
| 272 | |
| 273 | impl AsRef<UnixSeqpacket> for TaggedControlSocket { |
| 274 | fn as_ref(&self) -> &UnixSeqpacket { |
| 275 | use self::TaggedControlSocket::*; |
| 276 | match &self { |
| 277 | Vm(ref socket) => socket, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 278 | VmMemory(ref socket) => socket, |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 279 | VmIrq(ref socket) => socket, |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | impl AsRawFd for TaggedControlSocket { |
| 285 | fn as_raw_fd(&self) -> RawFd { |
| 286 | self.as_ref().as_raw_fd() |
| 287 | } |
| 288 | } |
| 289 | |
Chirantan Ekbote | 220605a | 2019-11-14 18:36:06 +0900 | [diff] [blame] | 290 | fn get_max_open_files() -> Result<libc::rlim64_t> { |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 291 | let mut buf = String::with_capacity(32); |
| 292 | File::open("/proc/sys/fs/file-max") |
| 293 | .and_then(|mut f| f.read_to_string(&mut buf)) |
| 294 | .map_err(Error::GetMaxOpenFiles)?; |
| 295 | |
| 296 | Ok(buf.trim().parse().map_err(Error::ParseMaxOpenFiles)?) |
| 297 | } |
| 298 | |
Zach Reizner | 4486379 | 2019-06-26 14:22:08 -0700 | [diff] [blame] | 299 | fn create_base_minijail( |
| 300 | root: &Path, |
| 301 | log_failures: bool, |
| 302 | seccomp_policy: &Path, |
| 303 | ) -> Result<Minijail> { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 304 | // All child jails run in a new user namespace without any users mapped, |
| 305 | // they run as nobody unless otherwise configured. |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 306 | let mut j = Minijail::new().map_err(Error::DeviceJail)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 307 | j.namespace_pids(); |
| 308 | j.namespace_user(); |
| 309 | j.namespace_user_disable_setgroups(); |
| 310 | // Don't need any capabilities. |
| 311 | j.use_caps(0); |
| 312 | // Create a new mount namespace with an empty root FS. |
| 313 | j.namespace_vfs(); |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 314 | j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 315 | // Run in an empty network namespace. |
| 316 | j.namespace_net(); |
Chirantan Ekbote | 1a5fe95 | 2019-11-27 17:38:54 +0900 | [diff] [blame^] | 317 | // Most devices don't need to open many fds. |
| 318 | j.set_rlimit(libc::RLIMIT_NOFILE, 1024, 1024) |
| 319 | .map_err(Error::SettingMaxOpenFiles)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 320 | // Apply the block device seccomp policy. |
| 321 | j.no_new_privs(); |
Stephen Barber | 3b1d8a5 | 2018-01-06 17:34:51 -0800 | [diff] [blame] | 322 | // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill |
| 323 | // the entire device process if a worker thread commits a seccomp violation. |
| 324 | j.set_seccomp_filter_tsync(); |
Zach Reizner | 4486379 | 2019-06-26 14:22:08 -0700 | [diff] [blame] | 325 | if log_failures { |
| 326 | j.log_seccomp_filter_failures(); |
| 327 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 328 | j.parse_seccomp_filters(seccomp_policy) |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 329 | .map_err(Error::DeviceJail)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 330 | j.use_seccomp_filter(); |
| 331 | // Don't do init setup. |
| 332 | j.run_as_init(); |
| 333 | Ok(j) |
| 334 | } |
| 335 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 336 | fn simple_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> { |
Lepton Wu | 9105e9f | 2019-03-14 11:38:31 -0700 | [diff] [blame] | 337 | if cfg.sandbox { |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 338 | let pivot_root: &str = option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty"); |
| 339 | // A directory for a jailed device's pivot root. |
| 340 | let root_path = Path::new(pivot_root); |
| 341 | if !root_path.exists() { |
| 342 | return Err(Error::PivotRootDoesntExist(pivot_root)); |
| 343 | } |
| 344 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join(policy); |
Zach Reizner | 4486379 | 2019-06-26 14:22:08 -0700 | [diff] [blame] | 345 | Ok(Some(create_base_minijail( |
| 346 | root_path, |
| 347 | cfg.seccomp_log_failures, |
| 348 | &policy_path, |
| 349 | )?)) |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 350 | } else { |
| 351 | Ok(None) |
| 352 | } |
| 353 | } |
| 354 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 355 | type DeviceResult<T = VirtioDeviceStub> = std::result::Result<T, Error>; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 356 | |
| 357 | fn create_block_device( |
| 358 | cfg: &Config, |
| 359 | disk: &DiskOption, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 360 | disk_device_socket: DiskControlResponseSocket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 361 | ) -> DeviceResult { |
| 362 | // Special case '/proc/self/fd/*' paths. The FD is already open, just use it. |
| 363 | let raw_image: File = if disk.path.parent() == Some(Path::new("/proc/self/fd")) { |
| 364 | // Safe because we will validate |raw_fd|. |
| 365 | unsafe { File::from_raw_fd(raw_fd_from_path(&disk.path)?) } |
| 366 | } else { |
| 367 | OpenOptions::new() |
| 368 | .read(true) |
| 369 | .write(!disk.read_only) |
| 370 | .open(&disk.path) |
| 371 | .map_err(Error::Disk)? |
| 372 | }; |
| 373 | // Lock the disk image to prevent other crosvm instances from using it. |
| 374 | let lock_op = if disk.read_only { |
| 375 | FlockOperation::LockShared |
| 376 | } else { |
| 377 | FlockOperation::LockExclusive |
| 378 | }; |
| 379 | flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?; |
| 380 | |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 381 | let disk_file = disk::create_disk_file(raw_image).map_err(Error::CreateDiskError)?; |
Daniel Verkamp | e73c80f | 2019-11-08 10:11:16 -0800 | [diff] [blame] | 382 | let dev = virtio::Block::new( |
| 383 | disk_file, |
| 384 | disk.read_only, |
| 385 | disk.sparse, |
| 386 | Some(disk_device_socket), |
| 387 | ) |
| 388 | .map_err(Error::BlockDeviceNew)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 389 | |
| 390 | Ok(VirtioDeviceStub { |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 391 | dev: Box::new(dev), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 392 | jail: simple_jail(&cfg, "block_device.policy")?, |
| 393 | }) |
| 394 | } |
| 395 | |
| 396 | fn create_rng_device(cfg: &Config) -> DeviceResult { |
| 397 | let dev = virtio::Rng::new().map_err(Error::RngDeviceNew)?; |
| 398 | |
| 399 | Ok(VirtioDeviceStub { |
| 400 | dev: Box::new(dev), |
| 401 | jail: simple_jail(&cfg, "rng_device.policy")?, |
| 402 | }) |
| 403 | } |
| 404 | |
| 405 | #[cfg(feature = "tpm")] |
| 406 | fn create_tpm_device(cfg: &Config) -> DeviceResult { |
| 407 | use std::ffi::CString; |
| 408 | use std::fs; |
| 409 | use std::process; |
| 410 | use sys_util::chown; |
| 411 | |
| 412 | let tpm_storage: PathBuf; |
| 413 | let mut tpm_jail = simple_jail(&cfg, "tpm_device.policy")?; |
| 414 | |
| 415 | match &mut tpm_jail { |
| 416 | Some(jail) => { |
| 417 | // Create a tmpfs in the device's root directory for tpm |
| 418 | // simulator storage. The size is 20*1024, or 20 KB. |
| 419 | jail.mount_with_data( |
| 420 | Path::new("none"), |
| 421 | Path::new("/"), |
| 422 | "tmpfs", |
| 423 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 424 | "size=20480", |
| 425 | )?; |
| 426 | |
| 427 | let crosvm_ids = add_crosvm_user_to_jail(jail, "tpm")?; |
| 428 | |
| 429 | let pid = process::id(); |
| 430 | let tpm_pid_dir = format!("/run/vm/tpm.{}", pid); |
| 431 | tpm_storage = Path::new(&tpm_pid_dir).to_owned(); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 432 | fs::create_dir_all(&tpm_storage) |
| 433 | .map_err(|e| Error::CreateTpmStorage(tpm_storage.to_owned(), e))?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 434 | let tpm_pid_dir_c = CString::new(tpm_pid_dir).expect("no nul bytes"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 435 | chown(&tpm_pid_dir_c, crosvm_ids.uid, crosvm_ids.gid) |
| 436 | .map_err(Error::ChownTpmStorage)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 437 | |
| 438 | jail.mount_bind(&tpm_storage, &tpm_storage, true)?; |
| 439 | } |
| 440 | None => { |
| 441 | // Path used inside cros_sdk which does not have /run/vm. |
| 442 | tpm_storage = Path::new("/tmp/tpm-simulator").to_owned(); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | let dev = virtio::Tpm::new(tpm_storage); |
| 447 | |
| 448 | Ok(VirtioDeviceStub { |
| 449 | dev: Box::new(dev), |
| 450 | jail: tpm_jail, |
| 451 | }) |
| 452 | } |
| 453 | |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 454 | fn create_single_touch_device(cfg: &Config, single_touch_spec: &TouchDeviceOption) -> DeviceResult { |
| 455 | let socket = create_input_socket(&single_touch_spec.path).map_err(|e| { |
| 456 | error!("failed configuring virtio single touch: {:?}", e); |
| 457 | e |
| 458 | })?; |
| 459 | |
| 460 | let dev = virtio::new_single_touch(socket, single_touch_spec.width, single_touch_spec.height) |
| 461 | .map_err(Error::InputDeviceNew)?; |
| 462 | Ok(VirtioDeviceStub { |
| 463 | dev: Box::new(dev), |
| 464 | jail: simple_jail(&cfg, "input_device.policy")?, |
| 465 | }) |
| 466 | } |
| 467 | |
| 468 | fn create_trackpad_device(cfg: &Config, trackpad_spec: &TouchDeviceOption) -> DeviceResult { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 469 | let socket = create_input_socket(&trackpad_spec.path).map_err(|e| { |
| 470 | error!("failed configuring virtio trackpad: {}", e); |
| 471 | e |
| 472 | })?; |
| 473 | |
| 474 | let dev = virtio::new_trackpad(socket, trackpad_spec.width, trackpad_spec.height) |
| 475 | .map_err(Error::InputDeviceNew)?; |
| 476 | |
| 477 | Ok(VirtioDeviceStub { |
| 478 | dev: Box::new(dev), |
| 479 | jail: simple_jail(&cfg, "input_device.policy")?, |
| 480 | }) |
| 481 | } |
| 482 | |
| 483 | fn create_mouse_device(cfg: &Config, mouse_socket: &Path) -> DeviceResult { |
| 484 | let socket = create_input_socket(&mouse_socket).map_err(|e| { |
| 485 | error!("failed configuring virtio mouse: {}", e); |
| 486 | e |
| 487 | })?; |
| 488 | |
| 489 | let dev = virtio::new_mouse(socket).map_err(Error::InputDeviceNew)?; |
| 490 | |
| 491 | Ok(VirtioDeviceStub { |
| 492 | dev: Box::new(dev), |
| 493 | jail: simple_jail(&cfg, "input_device.policy")?, |
| 494 | }) |
| 495 | } |
| 496 | |
| 497 | fn create_keyboard_device(cfg: &Config, keyboard_socket: &Path) -> DeviceResult { |
| 498 | let socket = create_input_socket(&keyboard_socket).map_err(|e| { |
| 499 | error!("failed configuring virtio keyboard: {}", e); |
| 500 | e |
| 501 | })?; |
| 502 | |
| 503 | let dev = virtio::new_keyboard(socket).map_err(Error::InputDeviceNew)?; |
| 504 | |
| 505 | Ok(VirtioDeviceStub { |
| 506 | dev: Box::new(dev), |
| 507 | jail: simple_jail(&cfg, "input_device.policy")?, |
| 508 | }) |
| 509 | } |
| 510 | |
| 511 | fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult { |
| 512 | let dev_file = OpenOptions::new() |
| 513 | .read(true) |
| 514 | .write(true) |
| 515 | .open(dev_path) |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 516 | .map_err(|e| Error::OpenVinput(dev_path.to_owned(), e))?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 517 | |
| 518 | let dev = virtio::new_evdev(dev_file).map_err(Error::InputDeviceNew)?; |
| 519 | |
| 520 | Ok(VirtioDeviceStub { |
| 521 | dev: Box::new(dev), |
| 522 | jail: simple_jail(&cfg, "input_device.policy")?, |
| 523 | }) |
| 524 | } |
| 525 | |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 526 | fn create_balloon_device(cfg: &Config, socket: BalloonControlResponseSocket) -> DeviceResult { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 527 | let dev = virtio::Balloon::new(socket).map_err(Error::BalloonDeviceNew)?; |
| 528 | |
| 529 | Ok(VirtioDeviceStub { |
| 530 | dev: Box::new(dev), |
| 531 | jail: simple_jail(&cfg, "balloon_device.policy")?, |
| 532 | }) |
| 533 | } |
| 534 | |
| 535 | fn create_tap_net_device(cfg: &Config, tap_fd: RawFd) -> DeviceResult { |
| 536 | // Safe because we ensure that we get a unique handle to the fd. |
| 537 | let tap = unsafe { |
| 538 | Tap::from_raw_fd(validate_raw_fd(tap_fd).map_err(Error::ValidateRawFd)?) |
| 539 | .map_err(Error::CreateTapDevice)? |
| 540 | }; |
| 541 | |
| 542 | let dev = virtio::Net::from(tap).map_err(Error::NetDeviceNew)?; |
| 543 | |
| 544 | Ok(VirtioDeviceStub { |
| 545 | dev: Box::new(dev), |
| 546 | jail: simple_jail(&cfg, "net_device.policy")?, |
| 547 | }) |
| 548 | } |
| 549 | |
| 550 | fn create_net_device( |
| 551 | cfg: &Config, |
| 552 | host_ip: Ipv4Addr, |
| 553 | netmask: Ipv4Addr, |
| 554 | mac_address: MacAddress, |
| 555 | mem: &GuestMemory, |
| 556 | ) -> DeviceResult { |
| 557 | let dev = if cfg.vhost_net { |
| 558 | let dev = |
| 559 | virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, netmask, mac_address, mem) |
| 560 | .map_err(Error::VhostNetDeviceNew)?; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 561 | Box::new(dev) as Box<dyn VirtioDevice> |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 562 | } else { |
| 563 | let dev = |
| 564 | virtio::Net::<Tap>::new(host_ip, netmask, mac_address).map_err(Error::NetDeviceNew)?; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 565 | Box::new(dev) as Box<dyn VirtioDevice> |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 566 | }; |
| 567 | |
| 568 | let policy = if cfg.vhost_net { |
| 569 | "vhost_net_device.policy" |
| 570 | } else { |
| 571 | "net_device.policy" |
| 572 | }; |
| 573 | |
| 574 | Ok(VirtioDeviceStub { |
| 575 | dev, |
| 576 | jail: simple_jail(&cfg, policy)?, |
| 577 | }) |
| 578 | } |
| 579 | |
| 580 | #[cfg(feature = "gpu")] |
| 581 | fn create_gpu_device( |
| 582 | cfg: &Config, |
| 583 | exit_evt: &EventFd, |
Gurchetan Singh | 7ec58fa | 2019-05-15 15:30:38 -0700 | [diff] [blame] | 584 | gpu_device_socket: VmMemoryControlRequestSocket, |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 585 | gpu_sockets: Vec<virtio::resource_bridge::ResourceResponseSocket>, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 586 | wayland_socket_path: Option<PathBuf>, |
| 587 | x_display: Option<String>, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 588 | ) -> DeviceResult { |
| 589 | let jailed_wayland_path = Path::new("/wayland-0"); |
| 590 | |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 591 | let mut display_backends = vec![ |
| 592 | virtio::DisplayBackend::X(x_display), |
| 593 | virtio::DisplayBackend::Null, |
| 594 | ]; |
| 595 | |
| 596 | if let Some(socket_path) = wayland_socket_path.as_ref() { |
| 597 | display_backends.insert( |
| 598 | 0, |
| 599 | virtio::DisplayBackend::Wayland(if cfg.sandbox { |
| 600 | Some(jailed_wayland_path.to_owned()) |
| 601 | } else { |
| 602 | Some(socket_path.to_owned()) |
| 603 | }), |
| 604 | ); |
| 605 | } |
| 606 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 607 | let dev = virtio::Gpu::new( |
| 608 | exit_evt.try_clone().map_err(Error::CloneEventFd)?, |
Gurchetan Singh | 7ec58fa | 2019-05-15 15:30:38 -0700 | [diff] [blame] | 609 | Some(gpu_device_socket), |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 610 | NonZeroU8::new(1).unwrap(), // number of scanouts |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 611 | gpu_sockets, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 612 | display_backends, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 613 | ); |
| 614 | |
| 615 | let jail = match simple_jail(&cfg, "gpu_device.policy")? { |
| 616 | Some(mut jail) => { |
| 617 | // Create a tmpfs in the device's root directory so that we can bind mount the |
| 618 | // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
| 619 | jail.mount_with_data( |
| 620 | Path::new("none"), |
| 621 | Path::new("/"), |
| 622 | "tmpfs", |
| 623 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 624 | "size=67108864", |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 625 | )?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 626 | |
| 627 | // Device nodes required for DRM. |
| 628 | let sys_dev_char_path = Path::new("/sys/dev/char"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 629 | jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 630 | let sys_devices_path = Path::new("/sys/devices"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 631 | jail.mount_bind(sys_devices_path, sys_devices_path, false)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 632 | let drm_dri_path = Path::new("/dev/dri"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 633 | jail.mount_bind(drm_dri_path, drm_dri_path, false)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 634 | |
David Riley | 06787c5 | 2019-07-24 12:09:07 -0700 | [diff] [blame] | 635 | // If the ARM specific devices exist on the host, bind mount them in. |
| 636 | let mali0_path = Path::new("/dev/mali0"); |
| 637 | if mali0_path.exists() { |
| 638 | jail.mount_bind(mali0_path, mali0_path, true)?; |
| 639 | } |
| 640 | |
| 641 | let pvr_sync_path = Path::new("/dev/pvr_sync"); |
| 642 | if pvr_sync_path.exists() { |
| 643 | jail.mount_bind(pvr_sync_path, pvr_sync_path, true)?; |
| 644 | } |
| 645 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 646 | // Libraries that are required when mesa drivers are dynamically loaded. |
David Riley | 06787c5 | 2019-07-24 12:09:07 -0700 | [diff] [blame] | 647 | let lib_dirs = &["/usr/lib", "/usr/lib64", "/lib", "/lib64"]; |
| 648 | for dir in lib_dirs { |
| 649 | let dir_path = Path::new(dir); |
| 650 | if dir_path.exists() { |
| 651 | jail.mount_bind(dir_path, dir_path, false)?; |
| 652 | } |
| 653 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 654 | |
| 655 | // Bind mount the wayland socket into jail's root. This is necessary since each |
| 656 | // new wayland context must open() the socket. |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 657 | if let Some(path) = wayland_socket_path { |
| 658 | jail.mount_bind(path.as_ref(), jailed_wayland_path, true)?; |
| 659 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 660 | |
| 661 | add_crosvm_user_to_jail(&mut jail, "gpu")?; |
| 662 | |
David Riley | 54e660b | 2019-07-24 17:22:50 -0700 | [diff] [blame] | 663 | // pvr driver requires read access to /proc/self/task/*/comm. |
| 664 | let proc_path = Path::new("/proc"); |
| 665 | jail.mount( |
| 666 | proc_path, |
| 667 | proc_path, |
| 668 | "proc", |
| 669 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RDONLY) as usize, |
| 670 | )?; |
| 671 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 672 | Some(jail) |
| 673 | } |
| 674 | None => None, |
| 675 | }; |
| 676 | |
| 677 | Ok(VirtioDeviceStub { |
| 678 | dev: Box::new(dev), |
| 679 | jail, |
| 680 | }) |
| 681 | } |
| 682 | |
| 683 | fn create_wayland_device( |
| 684 | cfg: &Config, |
| 685 | socket_path: &Path, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 686 | socket: VmMemoryControlRequestSocket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 687 | resource_bridge: Option<virtio::resource_bridge::ResourceRequestSocket>, |
| 688 | ) -> DeviceResult { |
| 689 | let wayland_socket_dir = socket_path.parent().ok_or(Error::InvalidWaylandPath)?; |
| 690 | let wayland_socket_name = socket_path.file_name().ok_or(Error::InvalidWaylandPath)?; |
| 691 | let jailed_wayland_dir = Path::new("/wayland"); |
| 692 | let jailed_wayland_path = jailed_wayland_dir.join(wayland_socket_name); |
| 693 | |
| 694 | let dev = virtio::Wl::new( |
Lepton Wu | 9105e9f | 2019-03-14 11:38:31 -0700 | [diff] [blame] | 695 | if cfg.sandbox { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 696 | &jailed_wayland_path |
| 697 | } else { |
| 698 | socket_path |
| 699 | }, |
| 700 | socket, |
| 701 | resource_bridge, |
| 702 | ) |
| 703 | .map_err(Error::WaylandDeviceNew)?; |
| 704 | |
| 705 | let jail = match simple_jail(&cfg, "wl_device.policy")? { |
| 706 | Some(mut jail) => { |
| 707 | // Create a tmpfs in the device's root directory so that we can bind mount the wayland |
| 708 | // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
| 709 | jail.mount_with_data( |
| 710 | Path::new("none"), |
| 711 | Path::new("/"), |
| 712 | "tmpfs", |
| 713 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 714 | "size=67108864", |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 715 | )?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 716 | |
| 717 | // Bind mount the wayland socket's directory into jail's root. This is necessary since |
| 718 | // each new wayland context must open() the socket. If the wayland socket is ever |
| 719 | // destroyed and remade in the same host directory, new connections will be possible |
| 720 | // without restarting the wayland device. |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 721 | jail.mount_bind(wayland_socket_dir, jailed_wayland_dir, true)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 722 | |
| 723 | add_crosvm_user_to_jail(&mut jail, "Wayland")?; |
| 724 | |
| 725 | Some(jail) |
| 726 | } |
| 727 | None => None, |
| 728 | }; |
| 729 | |
| 730 | Ok(VirtioDeviceStub { |
| 731 | dev: Box::new(dev), |
| 732 | jail, |
| 733 | }) |
| 734 | } |
| 735 | |
| 736 | fn create_vhost_vsock_device(cfg: &Config, cid: u64, mem: &GuestMemory) -> DeviceResult { |
| 737 | let dev = virtio::vhost::Vsock::new(cid, mem).map_err(Error::VhostVsockDeviceNew)?; |
| 738 | |
| 739 | Ok(VirtioDeviceStub { |
| 740 | dev: Box::new(dev), |
| 741 | jail: simple_jail(&cfg, "vhost_vsock_device.policy")?, |
| 742 | }) |
| 743 | } |
| 744 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 745 | fn create_fs_device( |
| 746 | cfg: &Config, |
| 747 | uid_map: &str, |
| 748 | gid_map: &str, |
| 749 | src: &Path, |
| 750 | tag: &str, |
| 751 | fs_cfg: virtio::fs::passthrough::Config, |
| 752 | ) -> DeviceResult { |
| 753 | let mut j = Minijail::new().map_err(Error::DeviceJail)?; |
| 754 | |
| 755 | if cfg.sandbox { |
| 756 | j.namespace_pids(); |
| 757 | j.namespace_user(); |
| 758 | j.namespace_user_disable_setgroups(); |
| 759 | j.uidmap(uid_map).map_err(Error::SettingUidMap)?; |
| 760 | j.gidmap(gid_map).map_err(Error::SettingGidMap)?; |
| 761 | |
| 762 | // Run in an empty network namespace. |
| 763 | j.namespace_net(); |
| 764 | |
| 765 | j.no_new_privs(); |
| 766 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 767 | // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill |
| 768 | // the entire device process if a worker thread commits a seccomp violation. |
Chirantan Ekbote | b0ac007 | 2019-11-14 18:45:56 +0900 | [diff] [blame] | 769 | let seccomp_policy = cfg.seccomp_policy_dir.join("fs_device.policy"); |
| 770 | j.set_seccomp_filter_tsync(); |
| 771 | if cfg.seccomp_log_failures { |
| 772 | j.log_seccomp_filter_failures(); |
| 773 | } |
| 774 | j.parse_seccomp_filters(&seccomp_policy) |
| 775 | .map_err(Error::DeviceJail)?; |
| 776 | j.use_seccomp_filter(); |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 777 | |
| 778 | // Don't do init setup. |
| 779 | j.run_as_init(); |
| 780 | } |
| 781 | |
| 782 | // Create a new mount namespace with the source directory as the root. We need this even when |
| 783 | // sandboxing is disabled as the server relies on the host kernel to prevent path traversals |
| 784 | // from leaking out of the shared directory. |
| 785 | j.namespace_vfs(); |
| 786 | j.enter_pivot_root(src).map_err(Error::DevicePivotRoot)?; |
| 787 | |
| 788 | // The file server opens a lot of fds and needs a really high open file limit. |
| 789 | let max_open_files = get_max_open_files()?; |
| 790 | j.set_rlimit(libc::RLIMIT_NOFILE, max_open_files, max_open_files) |
| 791 | .map_err(Error::SettingMaxOpenFiles)?; |
| 792 | |
| 793 | // TODO(chirantan): Use more than one worker once the kernel driver has been fixed to not panic |
| 794 | // when num_queues > 1. |
| 795 | let dev = virtio::fs::Fs::new(tag, 1, fs_cfg).map_err(Error::FsDeviceNew)?; |
| 796 | |
| 797 | Ok(VirtioDeviceStub { |
| 798 | dev: Box::new(dev), |
| 799 | jail: Some(j), |
| 800 | }) |
| 801 | } |
| 802 | |
Chirantan Ekbote | 1a2683b | 2019-11-26 16:28:23 +0900 | [diff] [blame] | 803 | fn create_9p_device(cfg: &Config, src: &Path, tag: &str) -> DeviceResult { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 804 | let (jail, root) = match simple_jail(&cfg, "9p_device.policy")? { |
| 805 | Some(mut jail) => { |
| 806 | // The shared directory becomes the root of the device's file system. |
| 807 | let root = Path::new("/"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 808 | jail.mount_bind(src, root, true)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 809 | |
Chirantan Ekbote | 1a2683b | 2019-11-26 16:28:23 +0900 | [diff] [blame] | 810 | add_crosvm_user_to_jail(&mut jail, "p9")?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 811 | (Some(jail), root) |
| 812 | } |
| 813 | None => { |
| 814 | // There's no bind mount so we tell the server to treat the source directory as the |
David Tolnay | 9deb7d7 | 2019-03-05 18:25:44 -0800 | [diff] [blame] | 815 | // root. |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 816 | (None, src) |
| 817 | } |
| 818 | }; |
| 819 | |
| 820 | let dev = virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?; |
| 821 | |
| 822 | Ok(VirtioDeviceStub { |
| 823 | dev: Box::new(dev), |
| 824 | jail, |
| 825 | }) |
| 826 | } |
| 827 | |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 828 | fn create_pmem_device( |
| 829 | cfg: &Config, |
| 830 | vm: &mut Vm, |
| 831 | resources: &mut SystemAllocator, |
| 832 | disk: &DiskOption, |
| 833 | index: usize, |
| 834 | ) -> DeviceResult { |
| 835 | let fd = OpenOptions::new() |
| 836 | .read(true) |
| 837 | .write(!disk.read_only) |
| 838 | .open(&disk.path) |
| 839 | .map_err(Error::Disk)?; |
| 840 | |
| 841 | let image_size = { |
| 842 | let metadata = std::fs::metadata(&disk.path).map_err(Error::Disk)?; |
| 843 | metadata.len() |
| 844 | }; |
| 845 | |
| 846 | let protection = { |
| 847 | if disk.read_only { |
| 848 | Protection::read() |
| 849 | } else { |
| 850 | Protection::read_write() |
| 851 | } |
| 852 | }; |
| 853 | |
| 854 | let memory_mapping = { |
| 855 | // Conversion from u64 to usize may fail on 32bit system. |
| 856 | let image_size = usize::try_from(image_size).map_err(|_| Error::PmemDeviceImageTooBig)?; |
| 857 | |
| 858 | MemoryMapping::from_fd_offset_protection(&fd, image_size, 0, protection) |
| 859 | .map_err(Error::ReservePmemMemory)? |
| 860 | }; |
| 861 | |
| 862 | let mapping_address = resources |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 863 | .mmio_allocator(MmioType::High) |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 864 | .allocate_with_align( |
| 865 | image_size, |
| 866 | Alloc::PmemDevice(index), |
| 867 | format!("pmem_disk_image_{}", index), |
| 868 | // Linux kernel requires pmem namespaces to be 128 MiB aligned. |
| 869 | 128 * 1024 * 1024, /* 128 MiB */ |
| 870 | ) |
| 871 | .map_err(Error::AllocatePmemDeviceAddress)?; |
| 872 | |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 873 | vm.add_mmio_memory( |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 874 | GuestAddress(mapping_address), |
| 875 | memory_mapping, |
| 876 | /* read_only = */ disk.read_only, |
| 877 | /* log_dirty_pages = */ false, |
| 878 | ) |
| 879 | .map_err(Error::AddPmemDeviceMemory)?; |
| 880 | |
| 881 | let dev = virtio::Pmem::new(fd, GuestAddress(mapping_address), image_size) |
| 882 | .map_err(Error::PmemDeviceNew)?; |
| 883 | |
| 884 | Ok(VirtioDeviceStub { |
| 885 | dev: Box::new(dev) as Box<dyn VirtioDevice>, |
Jakub Staron | cc91fc8 | 2019-06-10 14:00:07 -0700 | [diff] [blame] | 886 | jail: simple_jail(&cfg, "pmem_device.policy")?, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 887 | }) |
| 888 | } |
| 889 | |
Dmitry Torokhov | ee42b8c | 2019-05-27 11:14:20 -0700 | [diff] [blame] | 890 | // gpu_device_socket is not used when GPU support is disabled. |
| 891 | #[cfg_attr(not(feature = "gpu"), allow(unused_variables))] |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 892 | fn create_virtio_devices( |
| 893 | cfg: &Config, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 894 | mem: &GuestMemory, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 895 | vm: &mut Vm, |
| 896 | resources: &mut SystemAllocator, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 897 | _exit_evt: &EventFd, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 898 | wayland_device_socket: VmMemoryControlRequestSocket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 899 | gpu_device_socket: VmMemoryControlRequestSocket, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 900 | balloon_device_socket: BalloonControlResponseSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 901 | disk_device_sockets: &mut Vec<DiskControlResponseSocket>, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 902 | ) -> DeviceResult<Vec<VirtioDeviceStub>> { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 903 | let mut devs = Vec::new(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 904 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 905 | for disk in &cfg.disks { |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 906 | let disk_device_socket = disk_device_sockets.remove(0); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 907 | devs.push(create_block_device(cfg, disk, disk_device_socket)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 908 | } |
| 909 | |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 910 | for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() { |
| 911 | devs.push(create_pmem_device(cfg, vm, resources, pmem_disk, index)?); |
| 912 | } |
| 913 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 914 | devs.push(create_rng_device(cfg)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 915 | |
David Tolnay | de6b29a | 2018-12-20 11:49:46 -0800 | [diff] [blame] | 916 | #[cfg(feature = "tpm")] |
| 917 | { |
David Tolnay | 43f8e21 | 2019-02-13 17:28:16 -0800 | [diff] [blame] | 918 | if cfg.software_tpm { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 919 | devs.push(create_tpm_device(cfg)?); |
David Tolnay | 43f8e21 | 2019-02-13 17:28:16 -0800 | [diff] [blame] | 920 | } |
David Tolnay | de6b29a | 2018-12-20 11:49:46 -0800 | [diff] [blame] | 921 | } |
| 922 | |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 923 | if let Some(single_touch_spec) = &cfg.virtio_single_touch { |
| 924 | devs.push(create_single_touch_device(cfg, single_touch_spec)?); |
| 925 | } |
| 926 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 927 | if let Some(trackpad_spec) = &cfg.virtio_trackpad { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 928 | devs.push(create_trackpad_device(cfg, trackpad_spec)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 929 | } |
| 930 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 931 | if let Some(mouse_socket) = &cfg.virtio_mouse { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 932 | devs.push(create_mouse_device(cfg, mouse_socket)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 933 | } |
| 934 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 935 | if let Some(keyboard_socket) = &cfg.virtio_keyboard { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 936 | devs.push(create_keyboard_device(cfg, keyboard_socket)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 937 | } |
| 938 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 939 | for dev_path in &cfg.virtio_input_evdevs { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 940 | devs.push(create_vinput_device(cfg, dev_path)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 941 | } |
| 942 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 943 | devs.push(create_balloon_device(cfg, balloon_device_socket)?); |
Dylan Reid | 295ccac | 2017-11-06 14:06:24 -0800 | [diff] [blame] | 944 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 945 | // We checked above that if the IP is defined, then the netmask is, too. |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 946 | for tap_fd in &cfg.tap_fd { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 947 | devs.push(create_tap_net_device(cfg, *tap_fd)?); |
Jorge E. Moreira | b795280 | 2019-02-12 16:43:05 -0800 | [diff] [blame] | 948 | } |
| 949 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 950 | if let (Some(host_ip), Some(netmask), Some(mac_address)) = |
| 951 | (cfg.host_ip, cfg.netmask, cfg.mac_address) |
| 952 | { |
| 953 | devs.push(create_net_device(cfg, host_ip, netmask, mac_address, mem)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 954 | } |
| 955 | |
David Tolnay | fa70171 | 2019-02-13 16:42:54 -0800 | [diff] [blame] | 956 | #[cfg_attr(not(feature = "gpu"), allow(unused_mut))] |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 957 | let mut resource_bridges = Vec::<virtio::resource_bridge::ResourceResponseSocket>::new(); |
| 958 | |
| 959 | if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() { |
| 960 | #[cfg_attr(not(feature = "gpu"), allow(unused_mut))] |
| 961 | let mut wl_resource_bridge = None::<virtio::resource_bridge::ResourceRequestSocket>; |
| 962 | |
| 963 | #[cfg(feature = "gpu")] |
| 964 | { |
| 965 | if cfg.gpu { |
| 966 | let (wl_socket, gpu_socket) = |
| 967 | virtio::resource_bridge::pair().map_err(Error::CreateSocket)?; |
| 968 | resource_bridges.push(gpu_socket); |
| 969 | wl_resource_bridge = Some(wl_socket); |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | devs.push(create_wayland_device( |
| 974 | cfg, |
| 975 | wayland_socket_path, |
| 976 | wayland_device_socket, |
| 977 | wl_resource_bridge, |
| 978 | )?); |
| 979 | } |
David Tolnay | fa70171 | 2019-02-13 16:42:54 -0800 | [diff] [blame] | 980 | |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 981 | #[cfg(feature = "gpu")] |
| 982 | { |
| 983 | if cfg.gpu { |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 984 | devs.push(create_gpu_device( |
| 985 | cfg, |
| 986 | _exit_evt, |
| 987 | gpu_device_socket, |
| 988 | resource_bridges, |
| 989 | cfg.wayland_socket_path.clone(), |
| 990 | cfg.x_display.clone(), |
| 991 | )?); |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 992 | } |
| 993 | } |
| 994 | |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 995 | if let Some(cid) = cfg.cid { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 996 | devs.push(create_vhost_vsock_device(cfg, cid, mem)?); |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 997 | } |
| 998 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 999 | for shared_dir in &cfg.shared_dirs { |
| 1000 | let SharedDir { |
| 1001 | src, |
| 1002 | tag, |
| 1003 | kind, |
| 1004 | uid_map, |
| 1005 | gid_map, |
| 1006 | cfg: fs_cfg, |
| 1007 | } = shared_dir; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1008 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 1009 | let dev = match kind { |
| 1010 | SharedDirKind::FS => create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone())?, |
Chirantan Ekbote | 1a2683b | 2019-11-26 16:28:23 +0900 | [diff] [blame] | 1011 | SharedDirKind::P9 => create_9p_device(cfg, src, tag)?, |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 1012 | }; |
| 1013 | devs.push(dev); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1014 | } |
| 1015 | |
| 1016 | Ok(devs) |
| 1017 | } |
| 1018 | |
| 1019 | fn create_devices( |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1020 | cfg: &Config, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1021 | mem: &GuestMemory, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1022 | vm: &mut Vm, |
| 1023 | resources: &mut SystemAllocator, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1024 | exit_evt: &EventFd, |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 1025 | control_sockets: &mut Vec<TaggedControlSocket>, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1026 | wayland_device_socket: VmMemoryControlRequestSocket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1027 | gpu_device_socket: VmMemoryControlRequestSocket, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1028 | balloon_device_socket: BalloonControlResponseSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1029 | disk_device_sockets: &mut Vec<DiskControlResponseSocket>, |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1030 | usb_provider: HostBackendDeviceProvider, |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 1031 | ) -> DeviceResult<Vec<(Box<dyn PciDevice>, Option<Minijail>)>> { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1032 | let stubs = create_virtio_devices( |
| 1033 | &cfg, |
| 1034 | mem, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1035 | vm, |
| 1036 | resources, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1037 | exit_evt, |
| 1038 | wayland_device_socket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1039 | gpu_device_socket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1040 | balloon_device_socket, |
| 1041 | disk_device_sockets, |
| 1042 | )?; |
| 1043 | |
| 1044 | let mut pci_devices = Vec::new(); |
| 1045 | |
| 1046 | for stub in stubs { |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 1047 | let dev = if stub.dev.msix_vectors() > 0 { |
| 1048 | let (msi_host_socket, msi_device_socket) = |
| 1049 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
| 1050 | control_sockets.push(TaggedControlSocket::VmIrq(msi_host_socket)); |
| 1051 | |
| 1052 | VirtioPciDevice::new(mem.clone(), stub.dev, Some(msi_device_socket)) |
| 1053 | .map_err(Error::VirtioPciDev)? |
| 1054 | } else { |
| 1055 | VirtioPciDevice::new(mem.clone(), stub.dev, None).map_err(Error::VirtioPciDev)? |
| 1056 | }; |
| 1057 | |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 1058 | let dev = Box::new(dev) as Box<dyn PciDevice>; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1059 | pci_devices.push((dev, stub.jail)); |
| 1060 | } |
| 1061 | |
| 1062 | if cfg.cras_audio { |
paulhsia | 580d418 | 2019-05-24 16:53:55 +0800 | [diff] [blame] | 1063 | let mut server = Box::new(CrasClient::new().map_err(Error::CreateCrasClient)?); |
| 1064 | if cfg.cras_capture { |
| 1065 | server.enable_cras_capture(); |
| 1066 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1067 | let cras_audio = devices::Ac97Dev::new(mem.clone(), server); |
| 1068 | |
| 1069 | pci_devices.push(( |
| 1070 | Box::new(cras_audio), |
| 1071 | simple_jail(&cfg, "cras_audio_device.policy")?, |
| 1072 | )); |
| 1073 | } |
| 1074 | |
| 1075 | if cfg.null_audio { |
| 1076 | let server = Box::new(DummyStreamSource::new()); |
| 1077 | let null_audio = devices::Ac97Dev::new(mem.clone(), server); |
| 1078 | |
| 1079 | pci_devices.push(( |
| 1080 | Box::new(null_audio), |
| 1081 | simple_jail(&cfg, "null_audio_device.policy")?, |
| 1082 | )); |
| 1083 | } |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1084 | // Create xhci controller. |
| 1085 | let usb_controller = Box::new(XhciController::new(mem.clone(), usb_provider)); |
| 1086 | pci_devices.push((usb_controller, simple_jail(&cfg, "xhci.policy")?)); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1087 | |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 1088 | if cfg.vfio.is_some() { |
Xiong Zhang | 4b5bb3a | 2019-04-23 17:15:21 +0800 | [diff] [blame] | 1089 | let (vfio_host_socket_irq, vfio_device_socket_irq) = |
| 1090 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
| 1091 | control_sockets.push(TaggedControlSocket::VmIrq(vfio_host_socket_irq)); |
| 1092 | |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 1093 | let vfio_path = cfg.vfio.as_ref().unwrap().as_path(); |
Xiong Zhang | c554fff | 2019-04-23 17:14:55 +0800 | [diff] [blame] | 1094 | let vfiodevice = |
Daniel Verkamp | 04a82c7 | 2019-09-24 11:06:58 -0700 | [diff] [blame] | 1095 | VfioDevice::new(vfio_path, vm, mem.clone()).map_err(Error::CreateVfioDevice)?; |
Xiong Zhang | 4b5bb3a | 2019-04-23 17:15:21 +0800 | [diff] [blame] | 1096 | let vfiopcidevice = Box::new(VfioPciDevice::new(vfiodevice, vfio_device_socket_irq)); |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 1097 | pci_devices.push((vfiopcidevice, simple_jail(&cfg, "vfio_device.policy")?)); |
| 1098 | } |
| 1099 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1100 | Ok(pci_devices) |
| 1101 | } |
| 1102 | |
| 1103 | #[derive(Copy, Clone)] |
Chirantan Ekbote | 1a2683b | 2019-11-26 16:28:23 +0900 | [diff] [blame] | 1104 | #[cfg_attr(not(feature = "tpm"), allow(dead_code))] |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1105 | struct Ids { |
| 1106 | uid: uid_t, |
| 1107 | gid: gid_t, |
| 1108 | } |
| 1109 | |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1110 | // Set the uid/gid for the jailed process and give a basic id map. This is |
| 1111 | // required for bind mounts to work. |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1112 | fn add_crosvm_user_to_jail(jail: &mut Minijail, feature: &str) -> Result<Ids> { |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1113 | let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap(); |
| 1114 | |
| 1115 | let crosvm_uid = match get_user_id(&crosvm_user_group) { |
| 1116 | Ok(u) => u, |
| 1117 | Err(e) => { |
| 1118 | warn!("falling back to current user id for {}: {}", feature, e); |
| 1119 | geteuid() |
| 1120 | } |
| 1121 | }; |
| 1122 | |
| 1123 | let crosvm_gid = match get_group_id(&crosvm_user_group) { |
| 1124 | Ok(u) => u, |
| 1125 | Err(e) => { |
| 1126 | warn!("falling back to current group id for {}: {}", feature, e); |
| 1127 | getegid() |
| 1128 | } |
| 1129 | }; |
| 1130 | |
| 1131 | jail.change_uid(crosvm_uid); |
| 1132 | jail.change_gid(crosvm_gid); |
| 1133 | jail.uidmap(&format!("{0} {0} 1", crosvm_uid)) |
| 1134 | .map_err(Error::SettingUidMap)?; |
| 1135 | jail.gidmap(&format!("{0} {0} 1", crosvm_gid)) |
| 1136 | .map_err(Error::SettingGidMap)?; |
| 1137 | |
David Tolnay | 41a6f84 | 2019-03-01 16:18:44 -0800 | [diff] [blame] | 1138 | Ok(Ids { |
| 1139 | uid: crosvm_uid, |
| 1140 | gid: crosvm_gid, |
| 1141 | }) |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1142 | } |
| 1143 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1144 | fn raw_fd_from_path(path: &Path) -> Result<RawFd> { |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1145 | if !path.is_file() { |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1146 | return Err(Error::InvalidFdPath); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1147 | } |
| 1148 | let raw_fd = path |
| 1149 | .file_name() |
| 1150 | .and_then(|fd_osstr| fd_osstr.to_str()) |
| 1151 | .and_then(|fd_str| fd_str.parse::<c_int>().ok()) |
| 1152 | .ok_or(Error::InvalidFdPath)?; |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1153 | validate_raw_fd(raw_fd).map_err(Error::ValidateRawFd) |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1154 | } |
| 1155 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1156 | fn create_input_socket(path: &Path) -> Result<UnixStream> { |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1157 | if path.parent() == Some(Path::new("/proc/self/fd")) { |
| 1158 | // Safe because we will validate |raw_fd|. |
| 1159 | unsafe { Ok(UnixStream::from_raw_fd(raw_fd_from_path(path)?)) } |
| 1160 | } else { |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1161 | UnixStream::connect(path).map_err(Error::InputEventsOpen) |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1162 | } |
| 1163 | } |
| 1164 | |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1165 | fn setup_vcpu_signal_handler(use_kvm_signals: bool) -> Result<()> { |
| 1166 | if use_kvm_signals { |
| 1167 | unsafe { |
| 1168 | extern "C" fn handle_signal() {} |
| 1169 | // Our signal handler does nothing and is trivially async signal safe. |
| 1170 | register_rt_signal_handler(SIGRTMIN() + 0, handle_signal) |
| 1171 | .map_err(Error::RegisterSignalHandler)?; |
| 1172 | } |
| 1173 | block_signal(SIGRTMIN() + 0).map_err(Error::BlockSignal)?; |
| 1174 | } else { |
| 1175 | unsafe { |
| 1176 | extern "C" fn handle_signal() { |
| 1177 | Vcpu::set_local_immediate_exit(true); |
| 1178 | } |
| 1179 | register_rt_signal_handler(SIGRTMIN() + 0, handle_signal) |
| 1180 | .map_err(Error::RegisterSignalHandler)?; |
| 1181 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1182 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1183 | Ok(()) |
| 1184 | } |
| 1185 | |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1186 | #[derive(Default)] |
| 1187 | struct VcpuRunMode { |
| 1188 | mtx: Mutex<VmRunMode>, |
| 1189 | cvar: Condvar, |
| 1190 | } |
| 1191 | |
| 1192 | impl VcpuRunMode { |
| 1193 | fn set_and_notify(&self, new_mode: VmRunMode) { |
| 1194 | *self.mtx.lock() = new_mode; |
| 1195 | self.cvar.notify_all(); |
| 1196 | } |
| 1197 | } |
| 1198 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1199 | fn run_vcpu( |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1200 | mut vcpu: Vcpu, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1201 | cpu_id: u32, |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1202 | vcpu_affinity: Vec<usize>, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1203 | start_barrier: Arc<Barrier>, |
| 1204 | io_bus: devices::Bus, |
| 1205 | mmio_bus: devices::Bus, |
| 1206 | exit_evt: EventFd, |
Zach Reizner | 795355a | 2019-01-16 17:37:57 -0800 | [diff] [blame] | 1207 | requires_kvmclock_ctrl: bool, |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1208 | run_mode_arc: Arc<VcpuRunMode>, |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1209 | use_kvm_signals: bool, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1210 | ) -> Result<JoinHandle<()>> { |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1211 | thread::Builder::new() |
| 1212 | .name(format!("crosvm_vcpu{}", cpu_id)) |
| 1213 | .spawn(move || { |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1214 | if vcpu_affinity.len() != 0 { |
| 1215 | if let Err(e) = set_cpu_affinity(vcpu_affinity) { |
| 1216 | error!("Failed to set CPU affinity: {}", e); |
| 1217 | } |
| 1218 | } |
| 1219 | |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1220 | let mut sig_ok = true; |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1221 | if use_kvm_signals { |
| 1222 | match get_blocked_signals() { |
| 1223 | Ok(mut v) => { |
| 1224 | v.retain(|&x| x != SIGRTMIN() + 0); |
| 1225 | if let Err(e) = vcpu.set_signal_mask(&v) { |
| 1226 | error!( |
| 1227 | "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {}", |
| 1228 | cpu_id, e |
| 1229 | ); |
| 1230 | sig_ok = false; |
| 1231 | } |
| 1232 | } |
| 1233 | Err(e) => { |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1234 | error!( |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1235 | "Failed to retrieve signal mask for vcpu {} : {}", |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1236 | cpu_id, e |
| 1237 | ); |
| 1238 | sig_ok = false; |
| 1239 | } |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1240 | }; |
| 1241 | } else { |
| 1242 | vcpu.set_thread_id(SIGRTMIN() + 0); |
| 1243 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1244 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1245 | start_barrier.wait(); |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1246 | |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1247 | if sig_ok { |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1248 | 'vcpu_loop: loop { |
| 1249 | let mut interrupted_by_signal = false; |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1250 | match vcpu.run() { |
| 1251 | Ok(VcpuExit::IoIn { port, mut size }) => { |
| 1252 | let mut data = [0; 8]; |
| 1253 | if size > data.len() { |
| 1254 | error!("unsupported IoIn size of {} bytes", size); |
| 1255 | size = data.len(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1256 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1257 | io_bus.read(port as u64, &mut data[..size]); |
| 1258 | if let Err(e) = vcpu.set_data(&data[..size]) { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1259 | error!("failed to set return data for IoIn: {}", e); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1260 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1261 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1262 | Ok(VcpuExit::IoOut { |
| 1263 | port, |
| 1264 | mut size, |
| 1265 | data, |
| 1266 | }) => { |
| 1267 | if size > data.len() { |
| 1268 | error!("unsupported IoOut size of {} bytes", size); |
| 1269 | size = data.len(); |
| 1270 | } |
| 1271 | io_bus.write(port as u64, &data[..size]); |
| 1272 | } |
| 1273 | Ok(VcpuExit::MmioRead { address, size }) => { |
| 1274 | let mut data = [0; 8]; |
| 1275 | mmio_bus.read(address, &mut data[..size]); |
| 1276 | // Setting data for mmio can not fail. |
| 1277 | let _ = vcpu.set_data(&data[..size]); |
| 1278 | } |
| 1279 | Ok(VcpuExit::MmioWrite { |
| 1280 | address, |
| 1281 | size, |
| 1282 | data, |
| 1283 | }) => { |
| 1284 | mmio_bus.write(address, &data[..size]); |
| 1285 | } |
| 1286 | Ok(VcpuExit::Hlt) => break, |
| 1287 | Ok(VcpuExit::Shutdown) => break, |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1288 | Ok(VcpuExit::SystemEvent(_, _)) => break, |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1289 | Ok(r) => warn!("unexpected vcpu exit: {:?}", r), |
| 1290 | Err(e) => match e.errno() { |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1291 | libc::EINTR => interrupted_by_signal = true, |
| 1292 | libc::EAGAIN => {} |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1293 | _ => { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1294 | error!("vcpu hit unknown error: {}", e); |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1295 | break; |
| 1296 | } |
| 1297 | }, |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1298 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1299 | |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1300 | if interrupted_by_signal { |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1301 | if use_kvm_signals { |
| 1302 | // Try to clear the signal that we use to kick VCPU if it is pending before |
| 1303 | // attempting to handle pause requests. |
| 1304 | if let Err(e) = clear_signal(SIGRTMIN() + 0) { |
| 1305 | error!("failed to clear pending signal: {}", e); |
| 1306 | break; |
| 1307 | } |
| 1308 | } else { |
| 1309 | vcpu.set_immediate_exit(false); |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1310 | } |
| 1311 | let mut run_mode_lock = run_mode_arc.mtx.lock(); |
| 1312 | loop { |
| 1313 | match *run_mode_lock { |
| 1314 | VmRunMode::Running => break, |
Zach Reizner | 795355a | 2019-01-16 17:37:57 -0800 | [diff] [blame] | 1315 | VmRunMode::Suspending => { |
| 1316 | // On KVM implementations that use a paravirtualized clock (e.g. |
| 1317 | // x86), a flag must be set to indicate to the guest kernel that |
| 1318 | // a VCPU was suspended. The guest kernel will use this flag to |
| 1319 | // prevent the soft lockup detection from triggering when this |
| 1320 | // VCPU resumes, which could happen days later in realtime. |
| 1321 | if requires_kvmclock_ctrl { |
| 1322 | if let Err(e) = vcpu.kvmclock_ctrl() { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1323 | error!("failed to signal to kvm that vcpu {} is being suspended: {}", cpu_id, e); |
Zach Reizner | 795355a | 2019-01-16 17:37:57 -0800 | [diff] [blame] | 1324 | } |
| 1325 | } |
| 1326 | } |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1327 | VmRunMode::Exiting => break 'vcpu_loop, |
| 1328 | } |
| 1329 | // Give ownership of our exclusive lock to the condition variable that |
| 1330 | // will block. When the condition variable is notified, `wait` will |
| 1331 | // unblock and return a new exclusive lock. |
| 1332 | run_mode_lock = run_mode_arc.cvar.wait(run_mode_lock); |
| 1333 | } |
| 1334 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1335 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1336 | } |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1337 | exit_evt |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1338 | .write(1) |
| 1339 | .expect("failed to signal vcpu exit eventfd"); |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 1340 | }) |
| 1341 | .map_err(Error::SpawnVcpu) |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1342 | } |
| 1343 | |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1344 | // Reads the contents of a file and converts the space-separated fields into a Vec of u64s. |
| 1345 | // Returns an error if any of the fields fail to parse. |
| 1346 | fn file_fields_to_u64<P: AsRef<Path>>(path: P) -> io::Result<Vec<u64>> { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1347 | let mut file = File::open(path)?; |
| 1348 | |
| 1349 | let mut buf = [0u8; 32]; |
| 1350 | let count = file.read(&mut buf)?; |
| 1351 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1352 | let content = |
| 1353 | str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; |
| 1354 | content |
| 1355 | .trim() |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1356 | .split_whitespace() |
| 1357 | .map(|x| { |
| 1358 | x.parse::<u64>() |
| 1359 | .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) |
| 1360 | }) |
| 1361 | .collect() |
| 1362 | } |
| 1363 | |
| 1364 | // Reads the contents of a file and converts them into a u64, and if there |
| 1365 | // are multiple fields it only returns the first one. |
| 1366 | fn file_to_u64<P: AsRef<Path>>(path: P) -> io::Result<u64> { |
| 1367 | file_fields_to_u64(path)? |
| 1368 | .into_iter() |
| 1369 | .next() |
| 1370 | .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty file")) |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1371 | } |
| 1372 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1373 | pub fn run_config(cfg: Config) -> Result<()> { |
Lepton Wu | 9105e9f | 2019-03-14 11:38:31 -0700 | [diff] [blame] | 1374 | if cfg.sandbox { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1375 | // Printing something to the syslog before entering minijail so that libc's syslogger has a |
| 1376 | // chance to open files necessary for its operation, like `/etc/localtime`. After jailing, |
| 1377 | // access to those files will not be possible. |
| 1378 | info!("crosvm entering multiprocess mode"); |
| 1379 | } |
| 1380 | |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1381 | let (usb_control_socket, usb_provider) = |
David Tolnay | 5fb3f51 | 2019-04-12 19:22:33 -0700 | [diff] [blame] | 1382 | HostBackendDeviceProvider::new().map_err(Error::CreateUsbProvider)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1383 | // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this |
| 1384 | // before any jailed devices have been spawned, so that we can catch any of them that fail very |
| 1385 | // quickly. |
| 1386 | let sigchld_fd = SignalFd::new(libc::SIGCHLD).map_err(Error::CreateSignalFd)?; |
| 1387 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1388 | let initrd_image = if let Some(initrd_path) = &cfg.initrd_path { |
| 1389 | Some(File::open(initrd_path).map_err(|e| Error::OpenInitrd(initrd_path.clone(), e))?) |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 1390 | } else { |
| 1391 | None |
| 1392 | }; |
| 1393 | |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 1394 | let vm_image = match cfg.executable_path { |
| 1395 | Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel( |
| 1396 | File::open(kernel_path).map_err(|e| Error::OpenKernel(kernel_path.to_path_buf(), e))?, |
| 1397 | ), |
| 1398 | Some(Executable::Bios(ref bios_path)) => VmImage::Bios( |
| 1399 | File::open(bios_path).map_err(|e| Error::OpenBios(bios_path.to_path_buf(), e))?, |
| 1400 | ), |
| 1401 | _ => panic!("Did not receive a bios or kernel, should be impossible."), |
| 1402 | }; |
| 1403 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1404 | let components = VmComponents { |
Jakub Staron | f55f75d | 2019-04-26 11:22:51 -0700 | [diff] [blame] | 1405 | memory_size: (cfg.memory.unwrap_or(256) << 20) as u64, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1406 | vcpu_count: cfg.vcpu_count.unwrap_or(1), |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1407 | vcpu_affinity: cfg.vcpu_affinity.clone(), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 1408 | vm_image, |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 1409 | android_fstab: cfg |
| 1410 | .android_fstab |
| 1411 | .as_ref() |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1412 | .map(|x| File::open(x).map_err(|e| Error::OpenAndroidFstab(x.to_path_buf(), e))) |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 1413 | .map_or(Ok(None), |v| v.map(Some))?, |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 1414 | initrd_image, |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 1415 | extra_kernel_params: cfg.params.clone(), |
| 1416 | wayland_dmabuf: cfg.wayland_dmabuf, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1417 | }; |
| 1418 | |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1419 | let control_server_socket = match &cfg.socket_path { |
| 1420 | Some(path) => Some(UnlinkUnixSeqpacketListener( |
| 1421 | UnixSeqpacketListener::bind(path).map_err(Error::CreateSocket)?, |
| 1422 | )), |
| 1423 | None => None, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1424 | }; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1425 | |
| 1426 | let mut control_sockets = Vec::new(); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1427 | let (wayland_host_socket, wayland_device_socket) = |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1428 | msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?; |
| 1429 | control_sockets.push(TaggedControlSocket::VmMemory(wayland_host_socket)); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1430 | // 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] | 1431 | let (balloon_host_socket, balloon_device_socket) = |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1432 | msg_socket::pair::<BalloonControlCommand, ()>().map_err(Error::CreateSocket)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1433 | |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1434 | // Create one control socket per disk. |
| 1435 | let mut disk_device_sockets = Vec::new(); |
| 1436 | let mut disk_host_sockets = Vec::new(); |
| 1437 | let disk_count = cfg.disks.len(); |
| 1438 | for _ in 0..disk_count { |
| 1439 | let (disk_host_socket, disk_device_socket) = |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1440 | msg_socket::pair::<DiskControlCommand, DiskControlResult>() |
| 1441 | .map_err(Error::CreateSocket)?; |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1442 | disk_host_sockets.push(disk_host_socket); |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 1443 | disk_device_sockets.push(disk_device_socket); |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1444 | } |
| 1445 | |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1446 | let (gpu_host_socket, gpu_device_socket) = |
| 1447 | msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?; |
| 1448 | control_sockets.push(TaggedControlSocket::VmMemory(gpu_host_socket)); |
| 1449 | |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 1450 | let sandbox = cfg.sandbox; |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1451 | let linux = Arch::build_vm( |
| 1452 | components, |
| 1453 | cfg.split_irqchip, |
| 1454 | &cfg.serial_parameters, |
Zach Reizner | a8adff0 | 2019-08-13 11:20:14 -0700 | [diff] [blame] | 1455 | simple_jail(&cfg, "serial.policy")?, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1456 | |mem, vm, sys_allocator, exit_evt| { |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1457 | create_devices( |
| 1458 | &cfg, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1459 | mem, |
| 1460 | vm, |
| 1461 | sys_allocator, |
| 1462 | exit_evt, |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 1463 | &mut control_sockets, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1464 | wayland_device_socket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1465 | gpu_device_socket, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1466 | balloon_device_socket, |
| 1467 | &mut disk_device_sockets, |
| 1468 | usb_provider, |
| 1469 | ) |
| 1470 | }, |
| 1471 | ) |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 1472 | .map_err(Error::BuildVm)?; |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1473 | |
| 1474 | let _render_node_host = (); |
| 1475 | #[cfg(feature = "gpu-forward")] |
| 1476 | let (_render_node_host, linux) = { |
| 1477 | // Rebinds linux as mutable. |
| 1478 | let mut linux = linux; |
| 1479 | |
| 1480 | // Reserve memory range for GPU buffer allocation in advance to bypass region count |
| 1481 | // limitation. We use mremap/MAP_FIXED later to make sure GPU buffers fall into this range. |
| 1482 | let gpu_mmap = |
| 1483 | MemoryMapping::new_protection(RENDER_NODE_HOST_SIZE as usize, Protection::none()) |
| 1484 | .map_err(Error::ReserveGpuMemory)?; |
| 1485 | |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 1486 | // Put the non-accessible memory map into high mmio so that no other devices use that |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1487 | // guest address space. |
| 1488 | let gpu_addr = linux |
| 1489 | .resources |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 1490 | .mmio_allocator(MmioType::High) |
Daniel Prilik | d92f81a | 2019-03-26 14:28:19 -0700 | [diff] [blame] | 1491 | .allocate( |
| 1492 | RENDER_NODE_HOST_SIZE, |
| 1493 | Alloc::GpuRenderNode, |
| 1494 | "gpu_render_node".to_string(), |
| 1495 | ) |
| 1496 | .map_err(|_| Error::AllocateGpuDeviceAddress)?; |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1497 | |
| 1498 | let host = RenderNodeHost::start(&gpu_mmap, gpu_addr, linux.vm.get_memory().clone()); |
| 1499 | |
| 1500 | // Makes the gpu memory accessible at allocated address. |
| 1501 | linux |
| 1502 | .vm |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 1503 | .add_mmio_memory( |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1504 | GuestAddress(gpu_addr), |
| 1505 | gpu_mmap, |
| 1506 | /* read_only = */ false, |
| 1507 | /* log_dirty_pages = */ false, |
| 1508 | ) |
| 1509 | .map_err(Error::AddGpuDeviceMemory)?; |
| 1510 | (host, linux) |
| 1511 | }; |
| 1512 | |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1513 | run_control( |
| 1514 | linux, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1515 | control_server_socket, |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1516 | control_sockets, |
| 1517 | balloon_host_socket, |
| 1518 | &disk_host_sockets, |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1519 | usb_control_socket, |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1520 | sigchld_fd, |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1521 | _render_node_host, |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 1522 | sandbox, |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1523 | ) |
Dylan Reid | 0ed91ab | 2018-05-31 15:42:18 -0700 | [diff] [blame] | 1524 | } |
| 1525 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1526 | fn run_control( |
| 1527 | mut linux: RunnableLinuxVm, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1528 | control_server_socket: Option<UnlinkUnixSeqpacketListener>, |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1529 | mut control_sockets: Vec<TaggedControlSocket>, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1530 | balloon_host_socket: BalloonControlRequestSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1531 | disk_host_sockets: &[DiskControlRequestSocket], |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1532 | usb_control_socket: UsbControlSocket, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1533 | sigchld_fd: SignalFd, |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 1534 | _render_node_host: RenderNodeHost, |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 1535 | sandbox: bool, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1536 | ) -> Result<()> { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1537 | // Paths to get the currently available memory and the low memory threshold. |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 1538 | const LOWMEM_MARGIN: &str = "/sys/kernel/mm/chromeos-low_mem/margin"; |
| 1539 | const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available"; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1540 | |
| 1541 | // The amount of additional memory to claim back from the VM whenever the system is |
| 1542 | // low on memory. |
| 1543 | const ONE_GB: u64 = (1 << 30); |
| 1544 | |
Dylan Reid | 0ed91ab | 2018-05-31 15:42:18 -0700 | [diff] [blame] | 1545 | let max_balloon_memory = match linux.vm.get_memory().memory_size() { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1546 | // If the VM has at least 1.5 GB, the balloon driver can consume all but the last 1 GB. |
| 1547 | n if n >= (ONE_GB / 2) * 3 => n - ONE_GB, |
| 1548 | // Otherwise, if the VM has at least 500MB the balloon driver will consume at most |
| 1549 | // half of it. |
| 1550 | n if n >= (ONE_GB / 2) => n / 2, |
| 1551 | // Otherwise, the VM is too small for us to take memory away from it. |
| 1552 | _ => 0, |
| 1553 | }; |
| 1554 | let mut current_balloon_memory: u64 = 0; |
| 1555 | let balloon_memory_increment: u64 = max_balloon_memory / 16; |
| 1556 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1557 | #[derive(PollToken)] |
| 1558 | enum Token { |
| 1559 | Exit, |
| 1560 | Stdin, |
| 1561 | ChildSignal, |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1562 | CheckAvailableMemory, |
| 1563 | LowMemory, |
| 1564 | LowmemTimer, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1565 | VmControlServer, |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1566 | VmControl { index: usize }, |
| 1567 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1568 | |
| 1569 | let stdin_handle = stdin(); |
| 1570 | let stdin_lock = stdin_handle.lock(); |
| 1571 | stdin_lock |
| 1572 | .set_raw_mode() |
| 1573 | .expect("failed to set terminal raw mode"); |
| 1574 | |
Zach Reizner | b2110be | 2019-07-23 15:55:03 -0700 | [diff] [blame] | 1575 | let poll_ctx = PollContext::build_with(&[ |
| 1576 | (&linux.exit_evt, Token::Exit), |
| 1577 | (&sigchld_fd, Token::ChildSignal), |
| 1578 | ]) |
| 1579 | .map_err(Error::PollContextAdd)?; |
| 1580 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1581 | if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1582 | warn!("failed to add stdin to poll context: {}", e); |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1583 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1584 | |
| 1585 | if let Some(socket_server) = &control_server_socket { |
| 1586 | poll_ctx |
| 1587 | .add(socket_server, Token::VmControlServer) |
| 1588 | .map_err(Error::PollContextAdd)?; |
| 1589 | } |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1590 | for (index, socket) in control_sockets.iter().enumerate() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1591 | poll_ctx |
| 1592 | .add(socket.as_ref(), Token::VmControl { index }) |
| 1593 | .map_err(Error::PollContextAdd)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1594 | } |
| 1595 | |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1596 | // Watch for low memory notifications and take memory back from the VM. |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1597 | let low_mem = File::open("/dev/chromeos-low-mem").ok(); |
David Tolnay | 64cd5ea | 2019-04-15 15:56:35 -0700 | [diff] [blame] | 1598 | if let Some(low_mem) = &low_mem { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1599 | poll_ctx |
| 1600 | .add(low_mem, Token::LowMemory) |
| 1601 | .map_err(Error::PollContextAdd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1602 | } else { |
| 1603 | warn!("Unable to open low mem indicator, maybe not a chrome os kernel"); |
| 1604 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1605 | |
| 1606 | // Used to rate limit balloon requests. |
| 1607 | let mut lowmem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1608 | poll_ctx |
| 1609 | .add(&lowmem_timer, Token::LowmemTimer) |
| 1610 | .map_err(Error::PollContextAdd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1611 | |
| 1612 | // Used to check whether it's ok to start giving memory back to the VM. |
| 1613 | let mut freemem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1614 | poll_ctx |
| 1615 | .add(&freemem_timer, Token::CheckAvailableMemory) |
| 1616 | .map_err(Error::PollContextAdd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1617 | |
| 1618 | // Used to add jitter to timer values so that we don't have a thundering herd problem when |
| 1619 | // multiple VMs are running. |
Daniel Prilik | 2200604 | 2019-01-14 14:19:04 -0800 | [diff] [blame] | 1620 | let mut simple_rng = SimpleRng::new( |
| 1621 | SystemTime::now() |
| 1622 | .duration_since(UNIX_EPOCH) |
| 1623 | .expect("time went backwards") |
| 1624 | .subsec_nanos() as u64, |
| 1625 | ); |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1626 | |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 1627 | if sandbox { |
| 1628 | // Before starting VCPUs, in case we started with some capabilities, drop them all. |
| 1629 | drop_capabilities().map_err(Error::DropCapabilities)?; |
| 1630 | } |
Dmitry Torokhov | 7100607 | 2019-03-06 10:56:51 -0800 | [diff] [blame] | 1631 | |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 1632 | let mut vcpu_handles = Vec::with_capacity(linux.vcpus.len()); |
| 1633 | let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpus.len() + 1)); |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1634 | let run_mode_arc = Arc::new(VcpuRunMode::default()); |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1635 | let use_kvm_signals = !linux.kvm.check_extension(Cap::ImmediateExit); |
| 1636 | setup_vcpu_signal_handler(use_kvm_signals)?; |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 1637 | let vcpus = linux.vcpus.split_off(0); |
| 1638 | for (cpu_id, vcpu) in vcpus.into_iter().enumerate() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1639 | let handle = run_vcpu( |
| 1640 | vcpu, |
| 1641 | cpu_id as u32, |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1642 | linux.vcpu_affinity.clone(), |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1643 | vcpu_thread_barrier.clone(), |
| 1644 | linux.io_bus.clone(), |
| 1645 | linux.mmio_bus.clone(), |
| 1646 | linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?, |
Zach Reizner | 795355a | 2019-01-16 17:37:57 -0800 | [diff] [blame] | 1647 | linux.vm.check_extension(Cap::KvmclockCtrl), |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1648 | run_mode_arc.clone(), |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1649 | use_kvm_signals, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1650 | )?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1651 | vcpu_handles.push(handle); |
| 1652 | } |
| 1653 | vcpu_thread_barrier.wait(); |
| 1654 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1655 | 'poll: loop { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1656 | let events = { |
| 1657 | match poll_ctx.wait() { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1658 | Ok(v) => v, |
| 1659 | Err(e) => { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1660 | error!("failed to poll: {}", e); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1661 | break; |
| 1662 | } |
| 1663 | } |
| 1664 | }; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1665 | |
| 1666 | let mut vm_control_indices_to_remove = Vec::new(); |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1667 | for event in events.iter_readable() { |
| 1668 | match event.token() { |
| 1669 | Token::Exit => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1670 | info!("vcpu requested shutdown"); |
| 1671 | break 'poll; |
| 1672 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1673 | Token::Stdin => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1674 | let mut out = [0u8; 64]; |
| 1675 | match stdin_lock.read_raw(&mut out[..]) { |
| 1676 | Ok(0) => { |
| 1677 | // Zero-length read indicates EOF. Remove from pollables. |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1678 | let _ = poll_ctx.delete(&stdin_handle); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1679 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1680 | Err(e) => { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1681 | warn!("error while reading stdin: {}", e); |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1682 | let _ = poll_ctx.delete(&stdin_handle); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1683 | } |
Jakub Staron | b6515a9 | 2019-06-05 15:18:25 -0700 | [diff] [blame] | 1684 | Ok(count) => { |
| 1685 | if let Some(ref stdio_serial) = linux.stdio_serial { |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1686 | stdio_serial |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1687 | .queue_input_bytes(&out[..count]) |
| 1688 | .expect("failed to queue bytes into serial port"); |
| 1689 | } |
Jakub Staron | b6515a9 | 2019-06-05 15:18:25 -0700 | [diff] [blame] | 1690 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1691 | } |
| 1692 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1693 | Token::ChildSignal => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1694 | // Print all available siginfo structs, then exit the loop. |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 1695 | while let Some(siginfo) = sigchld_fd.read().map_err(Error::SignalFd)? { |
Zach Reizner | 3ba0098 | 2019-01-23 19:04:43 -0800 | [diff] [blame] | 1696 | let pid = siginfo.ssi_pid; |
| 1697 | let pid_label = match linux.pid_debug_label_map.get(&pid) { |
| 1698 | Some(label) => format!("{} (pid {})", label, pid), |
| 1699 | None => format!("pid {}", pid), |
| 1700 | }; |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 1701 | error!( |
| 1702 | "child {} died: signo {}, status {}, code {}", |
Zach Reizner | 3ba0098 | 2019-01-23 19:04:43 -0800 | [diff] [blame] | 1703 | pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 1704 | ); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1705 | } |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 1706 | break 'poll; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1707 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1708 | Token::CheckAvailableMemory => { |
| 1709 | // Acknowledge the timer. |
| 1710 | freemem_timer.wait().map_err(Error::TimerFd)?; |
| 1711 | if current_balloon_memory == 0 { |
| 1712 | // Nothing to see here. |
| 1713 | if let Err(e) = freemem_timer.clear() { |
| 1714 | warn!("unable to clear available memory check timer: {}", e); |
| 1715 | } |
| 1716 | continue; |
| 1717 | } |
| 1718 | |
| 1719 | // Otherwise see if we can free up some memory. |
| 1720 | let margin = file_to_u64(LOWMEM_MARGIN).map_err(Error::ReadLowmemMargin)?; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1721 | let available = |
| 1722 | file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1723 | |
| 1724 | // `available` and `margin` are specified in MB while `balloon_memory_increment` is in |
| 1725 | // 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] | 1726 | if available >= margin + 2 * (balloon_memory_increment >> 20) { |
| 1727 | current_balloon_memory = |
| 1728 | if current_balloon_memory >= balloon_memory_increment { |
| 1729 | current_balloon_memory - balloon_memory_increment |
| 1730 | } else { |
| 1731 | 0 |
| 1732 | }; |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1733 | let command = BalloonControlCommand::Adjust { |
| 1734 | num_bytes: current_balloon_memory, |
| 1735 | }; |
| 1736 | if let Err(e) = balloon_host_socket.send(&command) { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1737 | warn!("failed to send memory value to balloon device: {}", e); |
| 1738 | } |
| 1739 | } |
| 1740 | } |
| 1741 | Token::LowMemory => { |
David Tolnay | 64cd5ea | 2019-04-15 15:56:35 -0700 | [diff] [blame] | 1742 | if let Some(low_mem) = &low_mem { |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1743 | let old_balloon_memory = current_balloon_memory; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1744 | current_balloon_memory = min( |
| 1745 | current_balloon_memory + balloon_memory_increment, |
| 1746 | max_balloon_memory, |
| 1747 | ); |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1748 | if current_balloon_memory != old_balloon_memory { |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1749 | let command = BalloonControlCommand::Adjust { |
| 1750 | num_bytes: current_balloon_memory, |
| 1751 | }; |
| 1752 | if let Err(e) = balloon_host_socket.send(&command) { |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1753 | warn!("failed to send memory value to balloon device: {}", e); |
| 1754 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1755 | } |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1756 | |
| 1757 | // Stop polling the lowmem device until the timer fires. |
| 1758 | poll_ctx.delete(low_mem).map_err(Error::PollContextDelete)?; |
| 1759 | |
| 1760 | // Add some jitter to the timer so that if there are multiple VMs running |
| 1761 | // they don't all start ballooning at exactly the same time. |
Daniel Prilik | 2200604 | 2019-01-14 14:19:04 -0800 | [diff] [blame] | 1762 | let lowmem_dur = Duration::from_millis(1000 + simple_rng.rng() % 200); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1763 | lowmem_timer |
| 1764 | .reset(lowmem_dur, None) |
| 1765 | .map_err(Error::ResetTimerFd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1766 | |
| 1767 | // Also start a timer to check when we can start giving memory back. Do the |
| 1768 | // first check after a minute (with jitter) and subsequent checks after |
| 1769 | // every 30 seconds (with jitter). |
Daniel Prilik | 2200604 | 2019-01-14 14:19:04 -0800 | [diff] [blame] | 1770 | let freemem_dur = Duration::from_secs(60 + simple_rng.rng() % 12); |
| 1771 | let freemem_int = Duration::from_secs(30 + simple_rng.rng() % 6); |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1772 | freemem_timer |
| 1773 | .reset(freemem_dur, Some(freemem_int)) |
| 1774 | .map_err(Error::ResetTimerFd)?; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1775 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1776 | } |
| 1777 | Token::LowmemTimer => { |
| 1778 | // Acknowledge the timer. |
| 1779 | lowmem_timer.wait().map_err(Error::TimerFd)?; |
| 1780 | |
David Tolnay | 64cd5ea | 2019-04-15 15:56:35 -0700 | [diff] [blame] | 1781 | if let Some(low_mem) = &low_mem { |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1782 | // Start polling the lowmem device again. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1783 | poll_ctx |
| 1784 | .add(low_mem, Token::LowMemory) |
| 1785 | .map_err(Error::PollContextAdd)?; |
Dylan Reid | f11e6ed | 2018-07-31 10:24:06 -0700 | [diff] [blame] | 1786 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1787 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1788 | Token::VmControlServer => { |
| 1789 | if let Some(socket_server) = &control_server_socket { |
| 1790 | match socket_server.accept() { |
| 1791 | Ok(socket) => { |
| 1792 | poll_ctx |
| 1793 | .add( |
| 1794 | &socket, |
| 1795 | Token::VmControl { |
| 1796 | index: control_sockets.len(), |
| 1797 | }, |
| 1798 | ) |
| 1799 | .map_err(Error::PollContextAdd)?; |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1800 | control_sockets |
| 1801 | .push(TaggedControlSocket::Vm(MsgSocket::new(socket))); |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1802 | } |
| 1803 | Err(e) => error!("failed to accept socket: {}", e), |
| 1804 | } |
| 1805 | } |
| 1806 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1807 | Token::VmControl { index } => { |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 1808 | if let Some(socket) = control_sockets.get(index) { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1809 | match socket { |
| 1810 | TaggedControlSocket::Vm(socket) => match socket.recv() { |
| 1811 | Ok(request) => { |
| 1812 | let mut run_mode_opt = None; |
| 1813 | let response = request.execute( |
| 1814 | &mut run_mode_opt, |
| 1815 | &balloon_host_socket, |
| 1816 | disk_host_sockets, |
| 1817 | &usb_control_socket, |
| 1818 | ); |
| 1819 | if let Err(e) = socket.send(&response) { |
| 1820 | error!("failed to send VmResponse: {}", e); |
| 1821 | } |
| 1822 | if let Some(run_mode) = run_mode_opt { |
| 1823 | info!("control socket changed run mode to {}", run_mode); |
| 1824 | match run_mode { |
| 1825 | VmRunMode::Exiting => { |
| 1826 | break 'poll; |
| 1827 | } |
| 1828 | other => { |
| 1829 | run_mode_arc.set_and_notify(other); |
| 1830 | for handle in &vcpu_handles { |
| 1831 | let _ = handle.kill(SIGRTMIN() + 0); |
| 1832 | } |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1833 | } |
| 1834 | } |
| 1835 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1836 | } |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1837 | Err(e) => { |
| 1838 | if let MsgError::BadRecvSize { actual: 0, .. } = e { |
| 1839 | vm_control_indices_to_remove.push(index); |
| 1840 | } else { |
| 1841 | error!("failed to recv VmRequest: {}", e); |
| 1842 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1843 | } |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1844 | }, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1845 | TaggedControlSocket::VmMemory(socket) => match socket.recv() { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1846 | Ok(request) => { |
| 1847 | let response = |
| 1848 | request.execute(&mut linux.vm, &mut linux.resources); |
| 1849 | if let Err(e) = socket.send(&response) { |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1850 | error!("failed to send VmMemoryControlResponse: {}", e); |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1851 | } |
| 1852 | } |
| 1853 | Err(e) => { |
| 1854 | if let MsgError::BadRecvSize { actual: 0, .. } = e { |
| 1855 | vm_control_indices_to_remove.push(index); |
| 1856 | } else { |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1857 | error!("failed to recv VmMemoryControlRequest: {}", e); |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1858 | } |
| 1859 | } |
| 1860 | }, |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 1861 | TaggedControlSocket::VmIrq(socket) => match socket.recv() { |
| 1862 | Ok(request) => { |
| 1863 | let response = |
| 1864 | request.execute(&mut linux.vm, &mut linux.resources); |
| 1865 | if let Err(e) = socket.send(&response) { |
| 1866 | error!("failed to send VmIrqResponse: {}", e); |
| 1867 | } |
| 1868 | } |
| 1869 | Err(e) => { |
| 1870 | if let MsgError::BadRecvSize { actual: 0, .. } = e { |
| 1871 | vm_control_indices_to_remove.push(index); |
| 1872 | } else { |
| 1873 | error!("failed to recv VmIrqRequest: {}", e); |
| 1874 | } |
| 1875 | } |
| 1876 | }, |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1877 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1878 | } |
| 1879 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1880 | } |
| 1881 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1882 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1883 | for event in events.iter_hungup() { |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1884 | match event.token() { |
| 1885 | Token::Exit => {} |
| 1886 | Token::Stdin => { |
| 1887 | let _ = poll_ctx.delete(&stdin_handle); |
| 1888 | } |
| 1889 | Token::ChildSignal => {} |
| 1890 | Token::CheckAvailableMemory => {} |
| 1891 | Token::LowMemory => {} |
| 1892 | Token::LowmemTimer => {} |
| 1893 | Token::VmControlServer => {} |
| 1894 | Token::VmControl { index } => { |
| 1895 | // It's possible more data is readable and buffered while the socket is hungup, |
| 1896 | // so don't delete the socket from the poll context until we're sure all the |
| 1897 | // data is read. |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 1898 | match control_sockets |
| 1899 | .get(index) |
| 1900 | .map(|s| s.as_ref().get_readable_bytes()) |
| 1901 | { |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1902 | Some(Ok(0)) | Some(Err(_)) => vm_control_indices_to_remove.push(index), |
| 1903 | Some(Ok(x)) => info!("control index {} has {} bytes readable", index, x), |
| 1904 | _ => {} |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1905 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 1906 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1907 | } |
| 1908 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1909 | |
| 1910 | // Sort in reverse so the highest indexes are removed first. This removal algorithm |
Zide Chen | 8958407 | 2019-11-14 10:33:51 -0800 | [diff] [blame] | 1911 | // preserves correct indexes as each element is removed. |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1912 | vm_control_indices_to_remove.sort_unstable_by(|a, b| b.cmp(a)); |
| 1913 | vm_control_indices_to_remove.dedup(); |
| 1914 | for index in vm_control_indices_to_remove { |
Zide Chen | 8958407 | 2019-11-14 10:33:51 -0800 | [diff] [blame] | 1915 | // Delete the socket from the `poll_ctx` synchronously. Otherwise, the kernel will do |
| 1916 | // this automatically when the FD inserted into the `poll_ctx` is closed after this |
| 1917 | // if-block, but this removal can be deferred unpredictably. In some instances where the |
| 1918 | // system is under heavy load, we can even get events returned by `poll_ctx` for an FD |
| 1919 | // that has already been closed. Because the token associated with that spurious event |
| 1920 | // now belongs to a different socket, the control loop will start to interact with |
| 1921 | // sockets that might not be ready to use. This can cause incorrect hangup detection or |
| 1922 | // blocking on a socket that will never be ready. See also: crbug.com/1019986 |
| 1923 | if let Some(socket) = control_sockets.get(index) { |
| 1924 | poll_ctx.delete(socket).map_err(Error::PollContextDelete)?; |
| 1925 | } |
| 1926 | |
| 1927 | // This line implicitly drops the socket at `index` when it gets returned by |
| 1928 | // `swap_remove`. After this line, the socket at `index` is not the one from |
| 1929 | // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to |
| 1930 | // use `poll_ctx.modify` to change the associated index in its `Token::VmControl`. |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1931 | control_sockets.swap_remove(index); |
| 1932 | if let Some(socket) = control_sockets.get(index) { |
| 1933 | poll_ctx |
Xiong Zhang | 44bb3dd | 2019-04-23 17:09:50 +0800 | [diff] [blame] | 1934 | .modify( |
| 1935 | socket, |
| 1936 | WatchingEvents::empty().set_read(), |
| 1937 | Token::VmControl { index }, |
| 1938 | ) |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1939 | .map_err(Error::PollContextAdd)?; |
| 1940 | } |
| 1941 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1942 | } |
| 1943 | |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1944 | // VCPU threads MUST see the VmRunMode flag, otherwise they may re-enter the VM. |
| 1945 | run_mode_arc.set_and_notify(VmRunMode::Exiting); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1946 | for handle in vcpu_handles { |
Dmitry Torokhov | cd40533 | 2018-02-16 16:25:54 -0800 | [diff] [blame] | 1947 | match handle.kill(SIGRTMIN() + 0) { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1948 | Ok(_) => { |
| 1949 | if let Err(e) = handle.join() { |
| 1950 | error!("failed to join vcpu thread: {:?}", e); |
| 1951 | } |
| 1952 | } |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 1953 | Err(e) => error!("failed to kill vcpu thread: {}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1954 | } |
| 1955 | } |
| 1956 | |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 1957 | // Explicitly drop the VM structure here to allow the devices to clean up before the |
| 1958 | // control sockets are closed when this function exits. |
| 1959 | mem::drop(linux); |
| 1960 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1961 | stdin_lock |
| 1962 | .set_canon_mode() |
| 1963 | .expect("failed to restore canonical mode for terminal"); |
| 1964 | |
| 1965 | Ok(()) |
| 1966 | } |