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