blob: a3df995b6432e266ee725b8d11814480132bf647 [file] [log] [blame]
Zach Reizner39aa26b2017-12-12 18:03:23 -08001// Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07006use std::cmp::min;
Jakub Starona3411ea2019-04-24 10:55:25 -07007use std::convert::TryFrom;
David Tolnayfdac5ed2019-03-08 16:56:14 -08008use std::error::Error as StdError;
Dylan Reid059a1882018-07-23 17:58:09 -07009use std::ffi::CStr;
David Tolnayc69f9752019-03-01 18:07:56 -080010use std::fmt::{self, Display};
Dylan Reid059a1882018-07-23 17:58:09 -070011use std::fs::{File, OpenOptions};
Zach Reizner55a9e502018-10-03 10:22:32 -070012use std::io::{self, stdin, Read};
Daniel Verkamp94c35272019-09-12 13:31:30 -070013use std::mem;
David Tolnay2b089fc2019-03-04 15:33:22 -080014use std::net::Ipv4Addr;
Daniel Verkamp6f9215c2019-08-20 09:41:22 -070015#[cfg(feature = "gpu")]
Zach Reizner0f2cfb02019-06-19 17:46:03 -070016use std::num::NonZeroU8;
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +090017use std::num::ParseIntError;
Jakub Starond99cd0a2019-04-11 14:09:39 -070018use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
Zach Reiznera60744b2019-02-13 17:33:32 -080019use std::os::unix::net::UnixStream;
Zach Reizner39aa26b2017-12-12 18:03:23 -080020use std::path::{Path, PathBuf};
Chirantan Ekbote448516e2018-07-24 16:07:42 -070021use std::str;
Dylan Reid059a1882018-07-23 17:58:09 -070022use std::sync::{Arc, Barrier};
Zach Reizner39aa26b2017-12-12 18:03:23 -080023use std::thread;
24use std::thread::JoinHandle;
Daniel Prilik22006042019-01-14 14:19:04 -080025use std::time::{Duration, SystemTime, UNIX_EPOCH};
Zach Reizner39aa26b2017-12-12 18:03:23 -080026
David Tolnay41a6f842019-03-01 16:18:44 -080027use libc::{self, c_int, gid_t, uid_t};
Zach Reizner39aa26b2017-12-12 18:03:23 -080028
Dylan Reid3082e8e2019-01-07 10:33:48 -080029use audio_streams::DummyStreamSource;
David Tolnay2b089fc2019-03-04 15:33:22 -080030use devices::virtio::{self, VirtioDevice};
Xiong Zhang17b0daf2019-04-23 17:14:50 +080031use devices::{
32 self, HostBackendDeviceProvider, PciDevice, VfioDevice, VfioPciDevice, VirtioPciDevice,
33 XhciController,
34};
Zach Reizner39aa26b2017-12-12 18:03:23 -080035use io_jail::{self, Minijail};
Zach Reizner39aa26b2017-12-12 18:03:23 -080036use kvm::*;
paulhsiaf052cfe2019-01-22 15:22:25 +080037use libcras::CrasClient;
Zach Reiznera60744b2019-02-13 17:33:32 -080038use msg_socket::{MsgError, MsgReceiver, MsgSender, MsgSocket};
David Tolnay2b089fc2019-03-04 15:33:22 -080039use net_util::{Error as NetError, MacAddress, Tap};
Daniel Prilik22006042019-01-14 14:19:04 -080040use rand_ish::SimpleRng;
David Tolnay3df35522019-03-11 12:36:30 -070041use remain::sorted;
Xiong Zhang87a3b442019-10-29 17:32:44 +080042use resources::{Alloc, MmioType, SystemAllocator};
Zach Reizner6a8fdd92019-01-16 14:38:41 -080043use sync::{Condvar, Mutex};
Jakub Starond99cd0a2019-04-11 14:09:39 -070044use sys_util::net::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener};
Jakub Starona3411ea2019-04-24 10:55:25 -070045
Zach Reiznera60744b2019-02-13 17:33:32 -080046use sys_util::{
David Tolnay633426a2019-04-12 12:18:35 -070047 self, block_signal, clear_signal, drop_capabilities, error, flock, get_blocked_signals,
Fletcher Woodruff82ff3972019-10-02 13:11:34 -060048 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 Reiznera60744b2019-02-13 17:33:32 -080052};
Jason D. Clinton865323d2017-09-27 22:04:03 -060053use vhost;
Jakub Starone7c59052019-04-09 12:31:14 -070054use vm_control::{
Jakub Staron1f828d72019-04-11 12:49:29 -070055 BalloonControlCommand, BalloonControlRequestSocket, BalloonControlResponseSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -070056 DiskControlCommand, DiskControlRequestSocket, DiskControlResponseSocket, DiskControlResult,
Xiong Zhanga5d248c2019-09-17 14:17:19 -070057 UsbControlSocket, VmControlResponseSocket, VmIrqRequest, VmIrqResponse, VmIrqResponseSocket,
58 VmMemoryControlRequestSocket, VmMemoryControlResponseSocket, VmMemoryRequest, VmMemoryResponse,
59 VmRunMode,
Jakub Starone7c59052019-04-09 12:31:14 -070060};
Zach Reizner39aa26b2017-12-12 18:03:23 -080061
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +090062use crate::{Config, DiskOption, Executable, SharedDir, SharedDirKind, TouchDeviceOption};
Zach Reizner39aa26b2017-12-12 18:03:23 -080063
Cody Schuffelen6d1ab502019-05-21 12:12:38 -070064use arch::{self, LinuxArch, RunnableLinuxVm, VirtioDeviceStub, VmComponents, VmImage};
Sonny Raoed517d12018-02-13 22:09:43 -080065
Sonny Rao2ffa0cb2018-02-26 17:27:40 -080066#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
67use aarch64::AArch64 as Arch;
Zach Reizner55a9e502018-10-03 10:22:32 -070068#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
69use x86_64::X8664arch as Arch;
Zach Reizner39aa26b2017-12-12 18:03:23 -080070
Lepton Wu60893882018-11-21 11:06:18 -080071#[cfg(feature = "gpu-forward")]
David Tolnayaecf9a42019-04-11 14:30:00 -070072use render_node_forward::*;
Lepton Wu60893882018-11-21 11:06:18 -080073#[cfg(not(feature = "gpu-forward"))]
74type RenderNodeHost = ();
75
David Tolnay3df35522019-03-11 12:36:30 -070076#[sorted]
Dylan Reid059a1882018-07-23 17:58:09 -070077#[derive(Debug)]
Zach Reizner39aa26b2017-12-12 18:03:23 -080078pub enum Error {
Lepton Wu60893882018-11-21 11:06:18 -080079 AddGpuDeviceMemory(sys_util::Error),
Jakub Starona3411ea2019-04-24 10:55:25 -070080 AddPmemDeviceMemory(sys_util::Error),
Lepton Wu60893882018-11-21 11:06:18 -080081 AllocateGpuDeviceAddress,
Jakub Starona3411ea2019-04-24 10:55:25 -070082 AllocatePmemDeviceAddress(resources::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -080083 BalloonDeviceNew(virtio::BalloonError),
Zach Reizner39aa26b2017-12-12 18:03:23 -080084 BlockDeviceNew(sys_util::Error),
Mark Ryan6ed5aea2018-04-20 13:52:35 +010085 BlockSignal(sys_util::signal::Error),
David Tolnaybe034262019-03-04 17:48:36 -080086 BuildVm(<Arch as LinuxArch>::Error),
David Tolnayfd0971d2019-03-04 17:15:57 -080087 ChownTpmStorage(sys_util::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -080088 CloneEventFd(sys_util::Error),
David Tolnayfd0971d2019-03-04 17:15:57 -080089 CreateCrasClient(libcras::Error),
Cody Schuffelen7d533e52019-07-02 16:54:05 -070090 CreateDiskError(disk::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -080091 CreateEventFd(sys_util::Error),
Zach Reizner5bed0d22018-03-28 02:31:11 -070092 CreatePollContext(sys_util::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -080093 CreateSignalFd(sys_util::SignalFdError),
94 CreateSocket(io::Error),
Chirantan Ekbote49fa08f2018-11-16 13:26:53 -080095 CreateTapDevice(NetError),
Chirantan Ekbote448516e2018-07-24 16:07:42 -070096 CreateTimerFd(sys_util::Error),
David Tolnayfd0971d2019-03-04 17:15:57 -080097 CreateTpmStorage(PathBuf, io::Error),
Jingkui Wang100e6e42019-03-08 20:41:57 -080098 CreateUsbProvider(devices::usb::host_backend::error::Error),
Xiong Zhang17b0daf2019-04-23 17:14:50 +080099 CreateVfioDevice(devices::vfio::VfioError),
Zach Reizner39aa26b2017-12-12 18:03:23 -0800100 DeviceJail(io_jail::Error),
101 DevicePivotRoot(io_jail::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800102 Disk(io::Error),
Stephen Barberc79de2d2018-02-21 14:17:27 -0800103 DiskImageLock(sys_util::Error),
Dmitry Torokhov71006072019-03-06 10:56:51 -0800104 DropCapabilities(sys_util::Error),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900105 FsDeviceNew(virtio::fs::Error),
106 GetMaxOpenFiles(io::Error),
Lepton Wu39133a02019-02-27 12:42:29 -0800107 InputDeviceNew(virtio::InputError),
108 InputEventsOpen(std::io::Error),
Dylan Reid20566442018-04-02 15:06:15 -0700109 InvalidFdPath,
Zach Reizner579bd2c2018-09-14 15:43:33 -0700110 InvalidWaylandPath,
David Tolnayfd0971d2019-03-04 17:15:57 -0800111 IoJail(io_jail::Error),
David Tolnayfdac5ed2019-03-08 16:56:14 -0800112 LoadKernel(Box<dyn StdError>),
David Tolnay2b089fc2019-03-04 15:33:22 -0800113 NetDeviceNew(virtio::NetError),
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800114 OpenAndroidFstab(PathBuf, io::Error),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700115 OpenBios(PathBuf, io::Error),
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800116 OpenInitrd(PathBuf, io::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800117 OpenKernel(PathBuf, io::Error),
David Tolnayfd0971d2019-03-04 17:15:57 -0800118 OpenVinput(PathBuf, io::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800119 P9DeviceNew(virtio::P9Error),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900120 ParseMaxOpenFiles(ParseIntError),
Lepton Wu39133a02019-02-27 12:42:29 -0800121 PivotRootDoesntExist(&'static str),
Jakub Starona3411ea2019-04-24 10:55:25 -0700122 PmemDeviceImageTooBig,
123 PmemDeviceNew(sys_util::Error),
Zach Reizner5bed0d22018-03-28 02:31:11 -0700124 PollContextAdd(sys_util::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700125 PollContextDelete(sys_util::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700126 ReadLowmemAvailable(io::Error),
127 ReadLowmemMargin(io::Error),
Dylan Reid0f579cb2018-07-09 15:39:34 -0700128 RegisterBalloon(arch::DeviceRegistrationError),
129 RegisterBlock(arch::DeviceRegistrationError),
130 RegisterGpu(arch::DeviceRegistrationError),
131 RegisterNet(arch::DeviceRegistrationError),
132 RegisterP9(arch::DeviceRegistrationError),
133 RegisterRng(arch::DeviceRegistrationError),
Mark Ryan6ed5aea2018-04-20 13:52:35 +0100134 RegisterSignalHandler(sys_util::Error),
Dylan Reid0f579cb2018-07-09 15:39:34 -0700135 RegisterWayland(arch::DeviceRegistrationError),
Lepton Wu60893882018-11-21 11:06:18 -0800136 ReserveGpuMemory(sys_util::MmapError),
137 ReserveMemory(sys_util::Error),
Jakub Starona3411ea2019-04-24 10:55:25 -0700138 ReservePmemMemory(sys_util::MmapError),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700139 ResetTimerFd(sys_util::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800140 RngDeviceNew(virtio::RngError),
Zach Reizner8fb52112017-12-13 16:04:39 -0800141 SettingGidMap(io_jail::Error),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900142 SettingMaxOpenFiles(io_jail::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800143 SettingUidMap(io_jail::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800144 SignalFd(sys_util::SignalFdError),
145 SpawnVcpu(io::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700146 TimerFd(sys_util::Error),
Chirantan Ekbote2d292332018-11-16 11:35:24 -0800147 ValidateRawFd(sys_util::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800148 VhostNetDeviceNew(virtio::vhost::Error),
149 VhostVsockDeviceNew(virtio::vhost::Error),
Daniel Verkamp56f283b2018-10-05 11:40:59 -0700150 VirtioPciDev(sys_util::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800151 WaylandDeviceNew(sys_util::Error),
Zach Reizner39aa26b2017-12-12 18:03:23 -0800152}
153
David Tolnayc69f9752019-03-01 18:07:56 -0800154impl Display for Error {
David Tolnay3df35522019-03-11 12:36:30 -0700155 #[remain::check]
Zach Reizner39aa26b2017-12-12 18:03:23 -0800156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnayc69f9752019-03-01 18:07:56 -0800157 use self::Error::*;
158
David Tolnay3df35522019-03-11 12:36:30 -0700159 #[sorted]
Zach Reizner39aa26b2017-12-12 18:03:23 -0800160 match self {
Lepton Wu60893882018-11-21 11:06:18 -0800161 AddGpuDeviceMemory(e) => write!(f, "failed to add gpu device memory: {}", e),
Jakub Starona3411ea2019-04-24 10:55:25 -0700162 AddPmemDeviceMemory(e) => write!(f, "failed to add pmem device memory: {}", e),
Lepton Wu60893882018-11-21 11:06:18 -0800163 AllocateGpuDeviceAddress => write!(f, "failed to allocate gpu device guest address"),
Jakub Starona3411ea2019-04-24 10:55:25 -0700164 AllocatePmemDeviceAddress(e) => {
165 write!(f, "failed to allocate memory for pmem device: {}", e)
166 }
David Tolnayc69f9752019-03-01 18:07:56 -0800167 BalloonDeviceNew(e) => write!(f, "failed to create balloon: {}", e),
168 BlockDeviceNew(e) => write!(f, "failed to create block device: {}", e),
169 BlockSignal(e) => write!(f, "failed to block signal: {}", e),
David Tolnaybe034262019-03-04 17:48:36 -0800170 BuildVm(e) => write!(f, "The architecture failed to build the vm: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800171 ChownTpmStorage(e) => write!(f, "failed to chown tpm storage: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800172 CloneEventFd(e) => write!(f, "failed to clone eventfd: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800173 CreateCrasClient(e) => write!(f, "failed to create cras client: {}", e),
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700174 CreateDiskError(e) => write!(f, "failed to create virtual disk: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800175 CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e),
176 CreatePollContext(e) => write!(f, "failed to create poll context: {}", e),
177 CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e),
178 CreateSocket(e) => write!(f, "failed to create socket: {}", e),
179 CreateTapDevice(e) => write!(f, "failed to create tap device: {}", e),
180 CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800181 CreateTpmStorage(p, e) => {
182 write!(f, "failed to create tpm storage dir {}: {}", p.display(), e)
183 }
Jingkui Wang100e6e42019-03-08 20:41:57 -0800184 CreateUsbProvider(e) => write!(f, "failed to create usb provider: {}", e),
Xiong Zhang17b0daf2019-04-23 17:14:50 +0800185 CreateVfioDevice(e) => write!(f, "Failed to create vfio device {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800186 DeviceJail(e) => write!(f, "failed to jail device: {}", e),
187 DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e),
188 Disk(e) => write!(f, "failed to load disk image: {}", e),
189 DiskImageLock(e) => write!(f, "failed to lock disk image: {}", e),
Dmitry Torokhov71006072019-03-06 10:56:51 -0800190 DropCapabilities(e) => write!(f, "failed to drop process capabilities: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900191 FsDeviceNew(e) => write!(f, "failed to create fs device: {}", e),
192 GetMaxOpenFiles(e) => write!(f, "failed to get max number of open files: {}", e),
David Tolnay64cd5ea2019-04-15 15:56:35 -0700193 InputDeviceNew(e) => write!(f, "failed to set up input device: {}", e),
194 InputEventsOpen(e) => write!(f, "failed to open event device: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800195 InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"),
196 InvalidWaylandPath => write!(f, "wayland socket path has no parent or file name"),
David Tolnayfd0971d2019-03-04 17:15:57 -0800197 IoJail(e) => write!(f, "{}", e),
Lepton Wu39133a02019-02-27 12:42:29 -0800198 LoadKernel(e) => write!(f, "failed to load kernel: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800199 NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800200 OpenAndroidFstab(p, e) => write!(
David Tolnayb4bd00f2019-02-12 17:51:26 -0800201 f,
202 "failed to open android fstab file {}: {}",
203 p.display(),
204 e
205 ),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700206 OpenBios(p, e) => write!(f, "failed to open bios {}: {}", p.display(), e),
David Tolnay3df35522019-03-11 12:36:30 -0700207 OpenInitrd(p, e) => write!(f, "failed to open initrd {}: {}", p.display(), e),
208 OpenKernel(p, e) => write!(f, "failed to open kernel image {}: {}", p.display(), e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800209 OpenVinput(p, e) => write!(f, "failed to open vinput device {}: {}", p.display(), e),
David Tolnayc69f9752019-03-01 18:07:56 -0800210 P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900211 ParseMaxOpenFiles(e) => write!(f, "failed to parse max number of open files: {}", e),
Lepton Wu39133a02019-02-27 12:42:29 -0800212 PivotRootDoesntExist(p) => write!(f, "{} doesn't exist, can't jail devices.", p),
Jakub Starona3411ea2019-04-24 10:55:25 -0700213 PmemDeviceImageTooBig => {
214 write!(f, "failed to create pmem device: pmem device image too big")
215 }
216 PmemDeviceNew(e) => write!(f, "failed to create pmem device: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800217 PollContextAdd(e) => write!(f, "failed to add fd to poll context: {}", e),
218 PollContextDelete(e) => write!(f, "failed to remove fd from poll context: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800219 ReadLowmemAvailable(e) => write!(
Zach Reizner55a9e502018-10-03 10:22:32 -0700220 f,
221 "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}",
222 e
223 ),
David Tolnayc69f9752019-03-01 18:07:56 -0800224 ReadLowmemMargin(e) => write!(
Zach Reizner55a9e502018-10-03 10:22:32 -0700225 f,
226 "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}",
227 e
228 ),
David Tolnayc69f9752019-03-01 18:07:56 -0800229 RegisterBalloon(e) => write!(f, "error registering balloon device: {}", e),
230 RegisterBlock(e) => write!(f, "error registering block device: {}", e),
231 RegisterGpu(e) => write!(f, "error registering gpu device: {}", e),
232 RegisterNet(e) => write!(f, "error registering net device: {}", e),
233 RegisterP9(e) => write!(f, "error registering 9p device: {}", e),
234 RegisterRng(e) => write!(f, "error registering rng device: {}", e),
235 RegisterSignalHandler(e) => write!(f, "error registering signal handler: {}", e),
236 RegisterWayland(e) => write!(f, "error registering wayland device: {}", e),
Lepton Wu60893882018-11-21 11:06:18 -0800237 ReserveGpuMemory(e) => write!(f, "failed to reserve gpu memory: {}", e),
238 ReserveMemory(e) => write!(f, "failed to reserve memory: {}", e),
Jakub Starona3411ea2019-04-24 10:55:25 -0700239 ReservePmemMemory(e) => write!(f, "failed to reserve pmem memory: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800240 ResetTimerFd(e) => write!(f, "failed to reset timerfd: {}", e),
241 RngDeviceNew(e) => write!(f, "failed to set up rng: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800242 SettingGidMap(e) => write!(f, "error setting GID map: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900243 SettingMaxOpenFiles(e) => write!(f, "error setting max open files: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800244 SettingUidMap(e) => write!(f, "error setting UID map: {}", e),
245 SignalFd(e) => write!(f, "failed to read signal fd: {}", e),
246 SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e),
247 TimerFd(e) => write!(f, "failed to read timer fd: {}", e),
248 ValidateRawFd(e) => write!(f, "failed to validate raw fd: {}", e),
249 VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {}", e),
250 VhostVsockDeviceNew(e) => write!(f, "failed to set up virtual socket device: {}", e),
251 VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e),
252 WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {}", e),
Zach Reizner39aa26b2017-12-12 18:03:23 -0800253 }
254 }
255}
256
David Tolnayfd0971d2019-03-04 17:15:57 -0800257impl From<io_jail::Error> for Error {
258 fn from(err: io_jail::Error) -> Self {
259 Error::IoJail(err)
260 }
261}
262
David Tolnayc69f9752019-03-01 18:07:56 -0800263impl std::error::Error for Error {}
Dylan Reid059a1882018-07-23 17:58:09 -0700264
Zach Reizner39aa26b2017-12-12 18:03:23 -0800265type Result<T> = std::result::Result<T, Error>;
266
Jakub Starond99cd0a2019-04-11 14:09:39 -0700267enum TaggedControlSocket {
268 Vm(VmControlResponseSocket),
Gurchetan Singh53edb812019-05-22 08:57:16 -0700269 VmMemory(VmMemoryControlResponseSocket),
Xiong Zhang2515b752019-09-19 10:29:02 +0800270 VmIrq(VmIrqResponseSocket),
Jakub Starond99cd0a2019-04-11 14:09:39 -0700271}
272
273impl AsRef<UnixSeqpacket> for TaggedControlSocket {
274 fn as_ref(&self) -> &UnixSeqpacket {
275 use self::TaggedControlSocket::*;
276 match &self {
277 Vm(ref socket) => socket,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700278 VmMemory(ref socket) => socket,
Xiong Zhang2515b752019-09-19 10:29:02 +0800279 VmIrq(ref socket) => socket,
Jakub Starond99cd0a2019-04-11 14:09:39 -0700280 }
281 }
282}
283
284impl AsRawFd for TaggedControlSocket {
285 fn as_raw_fd(&self) -> RawFd {
286 self.as_ref().as_raw_fd()
287 }
288}
289
Chirantan Ekbote220605a2019-11-14 18:36:06 +0900290fn get_max_open_files() -> Result<libc::rlim64_t> {
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900291 let mut buf = String::with_capacity(32);
292 File::open("/proc/sys/fs/file-max")
293 .and_then(|mut f| f.read_to_string(&mut buf))
294 .map_err(Error::GetMaxOpenFiles)?;
295
296 Ok(buf.trim().parse().map_err(Error::ParseMaxOpenFiles)?)
297}
298
Zach Reizner44863792019-06-26 14:22:08 -0700299fn create_base_minijail(
300 root: &Path,
301 log_failures: bool,
302 seccomp_policy: &Path,
303) -> Result<Minijail> {
Zach Reizner39aa26b2017-12-12 18:03:23 -0800304 // All child jails run in a new user namespace without any users mapped,
305 // they run as nobody unless otherwise configured.
David Tolnay5bbbf612018-12-01 17:49:30 -0800306 let mut j = Minijail::new().map_err(Error::DeviceJail)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800307 j.namespace_pids();
308 j.namespace_user();
309 j.namespace_user_disable_setgroups();
310 // Don't need any capabilities.
311 j.use_caps(0);
312 // Create a new mount namespace with an empty root FS.
313 j.namespace_vfs();
David Tolnay5bbbf612018-12-01 17:49:30 -0800314 j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800315 // Run in an empty network namespace.
316 j.namespace_net();
Chirantan Ekbote1a5fe952019-11-27 17:38:54 +0900317 // Most devices don't need to open many fds.
318 j.set_rlimit(libc::RLIMIT_NOFILE, 1024, 1024)
319 .map_err(Error::SettingMaxOpenFiles)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800320 // Apply the block device seccomp policy.
321 j.no_new_privs();
Stephen Barber3b1d8a52018-01-06 17:34:51 -0800322 // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill
323 // the entire device process if a worker thread commits a seccomp violation.
324 j.set_seccomp_filter_tsync();
Zach Reizner44863792019-06-26 14:22:08 -0700325 if log_failures {
326 j.log_seccomp_filter_failures();
327 }
Zach Reizner39aa26b2017-12-12 18:03:23 -0800328 j.parse_seccomp_filters(seccomp_policy)
David Tolnay5bbbf612018-12-01 17:49:30 -0800329 .map_err(Error::DeviceJail)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800330 j.use_seccomp_filter();
331 // Don't do init setup.
332 j.run_as_init();
333 Ok(j)
334}
335
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800336fn simple_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> {
Lepton Wu9105e9f2019-03-14 11:38:31 -0700337 if cfg.sandbox {
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800338 let pivot_root: &str = option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty");
339 // A directory for a jailed device's pivot root.
340 let root_path = Path::new(pivot_root);
341 if !root_path.exists() {
342 return Err(Error::PivotRootDoesntExist(pivot_root));
343 }
344 let policy_path: PathBuf = cfg.seccomp_policy_dir.join(policy);
Zach Reizner44863792019-06-26 14:22:08 -0700345 Ok(Some(create_base_minijail(
346 root_path,
347 cfg.seccomp_log_failures,
348 &policy_path,
349 )?))
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800350 } else {
351 Ok(None)
352 }
353}
354
David Tolnayfd0971d2019-03-04 17:15:57 -0800355type DeviceResult<T = VirtioDeviceStub> = std::result::Result<T, Error>;
David Tolnay2b089fc2019-03-04 15:33:22 -0800356
357fn create_block_device(
358 cfg: &Config,
359 disk: &DiskOption,
Jakub Staronecf81e02019-04-11 11:43:39 -0700360 disk_device_socket: DiskControlResponseSocket,
David Tolnay2b089fc2019-03-04 15:33:22 -0800361) -> DeviceResult {
362 // Special case '/proc/self/fd/*' paths. The FD is already open, just use it.
363 let raw_image: File = if disk.path.parent() == Some(Path::new("/proc/self/fd")) {
364 // Safe because we will validate |raw_fd|.
365 unsafe { File::from_raw_fd(raw_fd_from_path(&disk.path)?) }
366 } else {
367 OpenOptions::new()
368 .read(true)
369 .write(!disk.read_only)
370 .open(&disk.path)
371 .map_err(Error::Disk)?
372 };
373 // Lock the disk image to prevent other crosvm instances from using it.
374 let lock_op = if disk.read_only {
375 FlockOperation::LockShared
376 } else {
377 FlockOperation::LockExclusive
378 };
379 flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?;
380
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700381 let disk_file = disk::create_disk_file(raw_image).map_err(Error::CreateDiskError)?;
Daniel Verkampe73c80f2019-11-08 10:11:16 -0800382 let dev = virtio::Block::new(
383 disk_file,
384 disk.read_only,
385 disk.sparse,
386 Some(disk_device_socket),
387 )
388 .map_err(Error::BlockDeviceNew)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800389
390 Ok(VirtioDeviceStub {
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700391 dev: Box::new(dev),
David Tolnay2b089fc2019-03-04 15:33:22 -0800392 jail: simple_jail(&cfg, "block_device.policy")?,
393 })
394}
395
396fn create_rng_device(cfg: &Config) -> DeviceResult {
397 let dev = virtio::Rng::new().map_err(Error::RngDeviceNew)?;
398
399 Ok(VirtioDeviceStub {
400 dev: Box::new(dev),
401 jail: simple_jail(&cfg, "rng_device.policy")?,
402 })
403}
404
405#[cfg(feature = "tpm")]
406fn create_tpm_device(cfg: &Config) -> DeviceResult {
407 use std::ffi::CString;
408 use std::fs;
409 use std::process;
410 use sys_util::chown;
411
412 let tpm_storage: PathBuf;
413 let mut tpm_jail = simple_jail(&cfg, "tpm_device.policy")?;
414
415 match &mut tpm_jail {
416 Some(jail) => {
417 // Create a tmpfs in the device's root directory for tpm
418 // simulator storage. The size is 20*1024, or 20 KB.
419 jail.mount_with_data(
420 Path::new("none"),
421 Path::new("/"),
422 "tmpfs",
423 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
424 "size=20480",
425 )?;
426
427 let crosvm_ids = add_crosvm_user_to_jail(jail, "tpm")?;
428
429 let pid = process::id();
430 let tpm_pid_dir = format!("/run/vm/tpm.{}", pid);
431 tpm_storage = Path::new(&tpm_pid_dir).to_owned();
David Tolnayfd0971d2019-03-04 17:15:57 -0800432 fs::create_dir_all(&tpm_storage)
433 .map_err(|e| Error::CreateTpmStorage(tpm_storage.to_owned(), e))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800434 let tpm_pid_dir_c = CString::new(tpm_pid_dir).expect("no nul bytes");
David Tolnayfd0971d2019-03-04 17:15:57 -0800435 chown(&tpm_pid_dir_c, crosvm_ids.uid, crosvm_ids.gid)
436 .map_err(Error::ChownTpmStorage)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800437
438 jail.mount_bind(&tpm_storage, &tpm_storage, true)?;
439 }
440 None => {
441 // Path used inside cros_sdk which does not have /run/vm.
442 tpm_storage = Path::new("/tmp/tpm-simulator").to_owned();
443 }
444 }
445
446 let dev = virtio::Tpm::new(tpm_storage);
447
448 Ok(VirtioDeviceStub {
449 dev: Box::new(dev),
450 jail: tpm_jail,
451 })
452}
453
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800454fn create_single_touch_device(cfg: &Config, single_touch_spec: &TouchDeviceOption) -> DeviceResult {
455 let socket = create_input_socket(&single_touch_spec.path).map_err(|e| {
456 error!("failed configuring virtio single touch: {:?}", e);
457 e
458 })?;
459
460 let dev = virtio::new_single_touch(socket, single_touch_spec.width, single_touch_spec.height)
461 .map_err(Error::InputDeviceNew)?;
462 Ok(VirtioDeviceStub {
463 dev: Box::new(dev),
464 jail: simple_jail(&cfg, "input_device.policy")?,
465 })
466}
467
468fn create_trackpad_device(cfg: &Config, trackpad_spec: &TouchDeviceOption) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800469 let socket = create_input_socket(&trackpad_spec.path).map_err(|e| {
470 error!("failed configuring virtio trackpad: {}", e);
471 e
472 })?;
473
474 let dev = virtio::new_trackpad(socket, trackpad_spec.width, trackpad_spec.height)
475 .map_err(Error::InputDeviceNew)?;
476
477 Ok(VirtioDeviceStub {
478 dev: Box::new(dev),
479 jail: simple_jail(&cfg, "input_device.policy")?,
480 })
481}
482
483fn create_mouse_device(cfg: &Config, mouse_socket: &Path) -> DeviceResult {
484 let socket = create_input_socket(&mouse_socket).map_err(|e| {
485 error!("failed configuring virtio mouse: {}", e);
486 e
487 })?;
488
489 let dev = virtio::new_mouse(socket).map_err(Error::InputDeviceNew)?;
490
491 Ok(VirtioDeviceStub {
492 dev: Box::new(dev),
493 jail: simple_jail(&cfg, "input_device.policy")?,
494 })
495}
496
497fn create_keyboard_device(cfg: &Config, keyboard_socket: &Path) -> DeviceResult {
498 let socket = create_input_socket(&keyboard_socket).map_err(|e| {
499 error!("failed configuring virtio keyboard: {}", e);
500 e
501 })?;
502
503 let dev = virtio::new_keyboard(socket).map_err(Error::InputDeviceNew)?;
504
505 Ok(VirtioDeviceStub {
506 dev: Box::new(dev),
507 jail: simple_jail(&cfg, "input_device.policy")?,
508 })
509}
510
511fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult {
512 let dev_file = OpenOptions::new()
513 .read(true)
514 .write(true)
515 .open(dev_path)
David Tolnayfd0971d2019-03-04 17:15:57 -0800516 .map_err(|e| Error::OpenVinput(dev_path.to_owned(), e))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800517
518 let dev = virtio::new_evdev(dev_file).map_err(Error::InputDeviceNew)?;
519
520 Ok(VirtioDeviceStub {
521 dev: Box::new(dev),
522 jail: simple_jail(&cfg, "input_device.policy")?,
523 })
524}
525
Jakub Staron1f828d72019-04-11 12:49:29 -0700526fn create_balloon_device(cfg: &Config, socket: BalloonControlResponseSocket) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800527 let dev = virtio::Balloon::new(socket).map_err(Error::BalloonDeviceNew)?;
528
529 Ok(VirtioDeviceStub {
530 dev: Box::new(dev),
531 jail: simple_jail(&cfg, "balloon_device.policy")?,
532 })
533}
534
535fn create_tap_net_device(cfg: &Config, tap_fd: RawFd) -> DeviceResult {
536 // Safe because we ensure that we get a unique handle to the fd.
537 let tap = unsafe {
538 Tap::from_raw_fd(validate_raw_fd(tap_fd).map_err(Error::ValidateRawFd)?)
539 .map_err(Error::CreateTapDevice)?
540 };
541
542 let dev = virtio::Net::from(tap).map_err(Error::NetDeviceNew)?;
543
544 Ok(VirtioDeviceStub {
545 dev: Box::new(dev),
546 jail: simple_jail(&cfg, "net_device.policy")?,
547 })
548}
549
550fn create_net_device(
551 cfg: &Config,
552 host_ip: Ipv4Addr,
553 netmask: Ipv4Addr,
554 mac_address: MacAddress,
555 mem: &GuestMemory,
556) -> DeviceResult {
557 let dev = if cfg.vhost_net {
558 let dev =
559 virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, netmask, mac_address, mem)
560 .map_err(Error::VhostNetDeviceNew)?;
David Tolnayfdac5ed2019-03-08 16:56:14 -0800561 Box::new(dev) as Box<dyn VirtioDevice>
David Tolnay2b089fc2019-03-04 15:33:22 -0800562 } else {
563 let dev =
564 virtio::Net::<Tap>::new(host_ip, netmask, mac_address).map_err(Error::NetDeviceNew)?;
David Tolnayfdac5ed2019-03-08 16:56:14 -0800565 Box::new(dev) as Box<dyn VirtioDevice>
David Tolnay2b089fc2019-03-04 15:33:22 -0800566 };
567
568 let policy = if cfg.vhost_net {
569 "vhost_net_device.policy"
570 } else {
571 "net_device.policy"
572 };
573
574 Ok(VirtioDeviceStub {
575 dev,
576 jail: simple_jail(&cfg, policy)?,
577 })
578}
579
580#[cfg(feature = "gpu")]
581fn create_gpu_device(
582 cfg: &Config,
583 exit_evt: &EventFd,
Gurchetan Singh7ec58fa2019-05-15 15:30:38 -0700584 gpu_device_socket: VmMemoryControlRequestSocket,
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900585 gpu_sockets: Vec<virtio::resource_bridge::ResourceResponseSocket>,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700586 wayland_socket_path: Option<PathBuf>,
587 x_display: Option<String>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800588) -> DeviceResult {
589 let jailed_wayland_path = Path::new("/wayland-0");
590
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700591 let mut display_backends = vec![
592 virtio::DisplayBackend::X(x_display),
593 virtio::DisplayBackend::Null,
594 ];
595
596 if let Some(socket_path) = wayland_socket_path.as_ref() {
597 display_backends.insert(
598 0,
599 virtio::DisplayBackend::Wayland(if cfg.sandbox {
600 Some(jailed_wayland_path.to_owned())
601 } else {
602 Some(socket_path.to_owned())
603 }),
604 );
605 }
606
David Tolnay2b089fc2019-03-04 15:33:22 -0800607 let dev = virtio::Gpu::new(
608 exit_evt.try_clone().map_err(Error::CloneEventFd)?,
Gurchetan Singh7ec58fa2019-05-15 15:30:38 -0700609 Some(gpu_device_socket),
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700610 NonZeroU8::new(1).unwrap(), // number of scanouts
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900611 gpu_sockets,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700612 display_backends,
David Tolnay2b089fc2019-03-04 15:33:22 -0800613 );
614
615 let jail = match simple_jail(&cfg, "gpu_device.policy")? {
616 Some(mut jail) => {
617 // Create a tmpfs in the device's root directory so that we can bind mount the
618 // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
619 jail.mount_with_data(
620 Path::new("none"),
621 Path::new("/"),
622 "tmpfs",
623 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
624 "size=67108864",
David Tolnayfd0971d2019-03-04 17:15:57 -0800625 )?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800626
627 // Device nodes required for DRM.
628 let sys_dev_char_path = Path::new("/sys/dev/char");
David Tolnayfd0971d2019-03-04 17:15:57 -0800629 jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800630 let sys_devices_path = Path::new("/sys/devices");
David Tolnayfd0971d2019-03-04 17:15:57 -0800631 jail.mount_bind(sys_devices_path, sys_devices_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800632 let drm_dri_path = Path::new("/dev/dri");
David Tolnayfd0971d2019-03-04 17:15:57 -0800633 jail.mount_bind(drm_dri_path, drm_dri_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800634
David Riley06787c52019-07-24 12:09:07 -0700635 // If the ARM specific devices exist on the host, bind mount them in.
636 let mali0_path = Path::new("/dev/mali0");
637 if mali0_path.exists() {
638 jail.mount_bind(mali0_path, mali0_path, true)?;
639 }
640
641 let pvr_sync_path = Path::new("/dev/pvr_sync");
642 if pvr_sync_path.exists() {
643 jail.mount_bind(pvr_sync_path, pvr_sync_path, true)?;
644 }
645
David Tolnay2b089fc2019-03-04 15:33:22 -0800646 // Libraries that are required when mesa drivers are dynamically loaded.
David Riley06787c52019-07-24 12:09:07 -0700647 let lib_dirs = &["/usr/lib", "/usr/lib64", "/lib", "/lib64"];
648 for dir in lib_dirs {
649 let dir_path = Path::new(dir);
650 if dir_path.exists() {
651 jail.mount_bind(dir_path, dir_path, false)?;
652 }
653 }
David Tolnay2b089fc2019-03-04 15:33:22 -0800654
655 // Bind mount the wayland socket into jail's root. This is necessary since each
656 // new wayland context must open() the socket.
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700657 if let Some(path) = wayland_socket_path {
658 jail.mount_bind(path.as_ref(), jailed_wayland_path, true)?;
659 }
David Tolnay2b089fc2019-03-04 15:33:22 -0800660
661 add_crosvm_user_to_jail(&mut jail, "gpu")?;
662
David Riley54e660b2019-07-24 17:22:50 -0700663 // pvr driver requires read access to /proc/self/task/*/comm.
664 let proc_path = Path::new("/proc");
665 jail.mount(
666 proc_path,
667 proc_path,
668 "proc",
669 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RDONLY) as usize,
670 )?;
671
David Tolnay2b089fc2019-03-04 15:33:22 -0800672 Some(jail)
673 }
674 None => None,
675 };
676
677 Ok(VirtioDeviceStub {
678 dev: Box::new(dev),
679 jail,
680 })
681}
682
683fn create_wayland_device(
684 cfg: &Config,
685 socket_path: &Path,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700686 socket: VmMemoryControlRequestSocket,
David Tolnay2b089fc2019-03-04 15:33:22 -0800687 resource_bridge: Option<virtio::resource_bridge::ResourceRequestSocket>,
688) -> DeviceResult {
689 let wayland_socket_dir = socket_path.parent().ok_or(Error::InvalidWaylandPath)?;
690 let wayland_socket_name = socket_path.file_name().ok_or(Error::InvalidWaylandPath)?;
691 let jailed_wayland_dir = Path::new("/wayland");
692 let jailed_wayland_path = jailed_wayland_dir.join(wayland_socket_name);
693
694 let dev = virtio::Wl::new(
Lepton Wu9105e9f2019-03-14 11:38:31 -0700695 if cfg.sandbox {
David Tolnay2b089fc2019-03-04 15:33:22 -0800696 &jailed_wayland_path
697 } else {
698 socket_path
699 },
700 socket,
701 resource_bridge,
702 )
703 .map_err(Error::WaylandDeviceNew)?;
704
705 let jail = match simple_jail(&cfg, "wl_device.policy")? {
706 Some(mut jail) => {
707 // Create a tmpfs in the device's root directory so that we can bind mount the wayland
708 // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
709 jail.mount_with_data(
710 Path::new("none"),
711 Path::new("/"),
712 "tmpfs",
713 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
714 "size=67108864",
David Tolnayfd0971d2019-03-04 17:15:57 -0800715 )?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800716
717 // Bind mount the wayland socket's directory into jail's root. This is necessary since
718 // each new wayland context must open() the socket. If the wayland socket is ever
719 // destroyed and remade in the same host directory, new connections will be possible
720 // without restarting the wayland device.
David Tolnayfd0971d2019-03-04 17:15:57 -0800721 jail.mount_bind(wayland_socket_dir, jailed_wayland_dir, true)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800722
723 add_crosvm_user_to_jail(&mut jail, "Wayland")?;
724
725 Some(jail)
726 }
727 None => None,
728 };
729
730 Ok(VirtioDeviceStub {
731 dev: Box::new(dev),
732 jail,
733 })
734}
735
736fn create_vhost_vsock_device(cfg: &Config, cid: u64, mem: &GuestMemory) -> DeviceResult {
737 let dev = virtio::vhost::Vsock::new(cid, mem).map_err(Error::VhostVsockDeviceNew)?;
738
739 Ok(VirtioDeviceStub {
740 dev: Box::new(dev),
741 jail: simple_jail(&cfg, "vhost_vsock_device.policy")?,
742 })
743}
744
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900745fn create_fs_device(
746 cfg: &Config,
747 uid_map: &str,
748 gid_map: &str,
749 src: &Path,
750 tag: &str,
751 fs_cfg: virtio::fs::passthrough::Config,
752) -> DeviceResult {
753 let mut j = Minijail::new().map_err(Error::DeviceJail)?;
754
755 if cfg.sandbox {
756 j.namespace_pids();
757 j.namespace_user();
758 j.namespace_user_disable_setgroups();
759 j.uidmap(uid_map).map_err(Error::SettingUidMap)?;
760 j.gidmap(gid_map).map_err(Error::SettingGidMap)?;
761
762 // Run in an empty network namespace.
763 j.namespace_net();
764
765 j.no_new_privs();
766
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900767 // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill
768 // the entire device process if a worker thread commits a seccomp violation.
Chirantan Ekboteb0ac0072019-11-14 18:45:56 +0900769 let seccomp_policy = cfg.seccomp_policy_dir.join("fs_device.policy");
770 j.set_seccomp_filter_tsync();
771 if cfg.seccomp_log_failures {
772 j.log_seccomp_filter_failures();
773 }
774 j.parse_seccomp_filters(&seccomp_policy)
775 .map_err(Error::DeviceJail)?;
776 j.use_seccomp_filter();
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900777
778 // Don't do init setup.
779 j.run_as_init();
780 }
781
782 // Create a new mount namespace with the source directory as the root. We need this even when
783 // sandboxing is disabled as the server relies on the host kernel to prevent path traversals
784 // from leaking out of the shared directory.
785 j.namespace_vfs();
786 j.enter_pivot_root(src).map_err(Error::DevicePivotRoot)?;
787
788 // The file server opens a lot of fds and needs a really high open file limit.
789 let max_open_files = get_max_open_files()?;
790 j.set_rlimit(libc::RLIMIT_NOFILE, max_open_files, max_open_files)
791 .map_err(Error::SettingMaxOpenFiles)?;
792
793 // TODO(chirantan): Use more than one worker once the kernel driver has been fixed to not panic
794 // when num_queues > 1.
795 let dev = virtio::fs::Fs::new(tag, 1, fs_cfg).map_err(Error::FsDeviceNew)?;
796
797 Ok(VirtioDeviceStub {
798 dev: Box::new(dev),
799 jail: Some(j),
800 })
801}
802
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +0900803fn create_9p_device(cfg: &Config, src: &Path, tag: &str) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800804 let (jail, root) = match simple_jail(&cfg, "9p_device.policy")? {
805 Some(mut jail) => {
806 // The shared directory becomes the root of the device's file system.
807 let root = Path::new("/");
David Tolnayfd0971d2019-03-04 17:15:57 -0800808 jail.mount_bind(src, root, true)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800809
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +0900810 add_crosvm_user_to_jail(&mut jail, "p9")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800811 (Some(jail), root)
812 }
813 None => {
814 // There's no bind mount so we tell the server to treat the source directory as the
David Tolnay9deb7d72019-03-05 18:25:44 -0800815 // root.
David Tolnay2b089fc2019-03-04 15:33:22 -0800816 (None, src)
817 }
818 };
819
820 let dev = virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?;
821
822 Ok(VirtioDeviceStub {
823 dev: Box::new(dev),
824 jail,
825 })
826}
827
Jakub Starona3411ea2019-04-24 10:55:25 -0700828fn create_pmem_device(
829 cfg: &Config,
830 vm: &mut Vm,
831 resources: &mut SystemAllocator,
832 disk: &DiskOption,
833 index: usize,
834) -> DeviceResult {
835 let fd = OpenOptions::new()
836 .read(true)
837 .write(!disk.read_only)
838 .open(&disk.path)
839 .map_err(Error::Disk)?;
840
841 let image_size = {
842 let metadata = std::fs::metadata(&disk.path).map_err(Error::Disk)?;
843 metadata.len()
844 };
845
846 let protection = {
847 if disk.read_only {
848 Protection::read()
849 } else {
850 Protection::read_write()
851 }
852 };
853
854 let memory_mapping = {
855 // Conversion from u64 to usize may fail on 32bit system.
856 let image_size = usize::try_from(image_size).map_err(|_| Error::PmemDeviceImageTooBig)?;
857
858 MemoryMapping::from_fd_offset_protection(&fd, image_size, 0, protection)
859 .map_err(Error::ReservePmemMemory)?
860 };
861
862 let mapping_address = resources
Xiong Zhang383b3b52019-10-30 14:59:26 +0800863 .mmio_allocator(MmioType::High)
Jakub Starona3411ea2019-04-24 10:55:25 -0700864 .allocate_with_align(
865 image_size,
866 Alloc::PmemDevice(index),
867 format!("pmem_disk_image_{}", index),
868 // Linux kernel requires pmem namespaces to be 128 MiB aligned.
869 128 * 1024 * 1024, /* 128 MiB */
870 )
871 .map_err(Error::AllocatePmemDeviceAddress)?;
872
Xiong Zhang383b3b52019-10-30 14:59:26 +0800873 vm.add_mmio_memory(
Jakub Starona3411ea2019-04-24 10:55:25 -0700874 GuestAddress(mapping_address),
875 memory_mapping,
876 /* read_only = */ disk.read_only,
877 /* log_dirty_pages = */ false,
878 )
879 .map_err(Error::AddPmemDeviceMemory)?;
880
881 let dev = virtio::Pmem::new(fd, GuestAddress(mapping_address), image_size)
882 .map_err(Error::PmemDeviceNew)?;
883
884 Ok(VirtioDeviceStub {
885 dev: Box::new(dev) as Box<dyn VirtioDevice>,
Jakub Staroncc91fc82019-06-10 14:00:07 -0700886 jail: simple_jail(&cfg, "pmem_device.policy")?,
Jakub Starona3411ea2019-04-24 10:55:25 -0700887 })
888}
889
Dmitry Torokhovee42b8c2019-05-27 11:14:20 -0700890// gpu_device_socket is not used when GPU support is disabled.
891#[cfg_attr(not(feature = "gpu"), allow(unused_variables))]
David Tolnay2b089fc2019-03-04 15:33:22 -0800892fn create_virtio_devices(
893 cfg: &Config,
Zach Reizner55a9e502018-10-03 10:22:32 -0700894 mem: &GuestMemory,
Jakub Starona3411ea2019-04-24 10:55:25 -0700895 vm: &mut Vm,
896 resources: &mut SystemAllocator,
Zach Reizner55a9e502018-10-03 10:22:32 -0700897 _exit_evt: &EventFd,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700898 wayland_device_socket: VmMemoryControlRequestSocket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -0700899 gpu_device_socket: VmMemoryControlRequestSocket,
Jakub Staron1f828d72019-04-11 12:49:29 -0700900 balloon_device_socket: BalloonControlResponseSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -0700901 disk_device_sockets: &mut Vec<DiskControlResponseSocket>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800902) -> DeviceResult<Vec<VirtioDeviceStub>> {
Dylan Reid059a1882018-07-23 17:58:09 -0700903 let mut devs = Vec::new();
Zach Reizner39aa26b2017-12-12 18:03:23 -0800904
Zach Reizner8fb52112017-12-13 16:04:39 -0800905 for disk in &cfg.disks {
Daniel Verkamp92f73d72018-12-04 13:17:46 -0800906 let disk_device_socket = disk_device_sockets.remove(0);
David Tolnay2b089fc2019-03-04 15:33:22 -0800907 devs.push(create_block_device(cfg, disk, disk_device_socket)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800908 }
909
Jakub Starona3411ea2019-04-24 10:55:25 -0700910 for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() {
911 devs.push(create_pmem_device(cfg, vm, resources, pmem_disk, index)?);
912 }
913
David Tolnay2b089fc2019-03-04 15:33:22 -0800914 devs.push(create_rng_device(cfg)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800915
David Tolnayde6b29a2018-12-20 11:49:46 -0800916 #[cfg(feature = "tpm")]
917 {
David Tolnay43f8e212019-02-13 17:28:16 -0800918 if cfg.software_tpm {
David Tolnay2b089fc2019-03-04 15:33:22 -0800919 devs.push(create_tpm_device(cfg)?);
David Tolnay43f8e212019-02-13 17:28:16 -0800920 }
David Tolnayde6b29a2018-12-20 11:49:46 -0800921 }
922
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800923 if let Some(single_touch_spec) = &cfg.virtio_single_touch {
924 devs.push(create_single_touch_device(cfg, single_touch_spec)?);
925 }
926
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800927 if let Some(trackpad_spec) = &cfg.virtio_trackpad {
David Tolnay2b089fc2019-03-04 15:33:22 -0800928 devs.push(create_trackpad_device(cfg, trackpad_spec)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800929 }
930
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800931 if let Some(mouse_socket) = &cfg.virtio_mouse {
David Tolnay2b089fc2019-03-04 15:33:22 -0800932 devs.push(create_mouse_device(cfg, mouse_socket)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800933 }
934
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800935 if let Some(keyboard_socket) = &cfg.virtio_keyboard {
David Tolnay2b089fc2019-03-04 15:33:22 -0800936 devs.push(create_keyboard_device(cfg, keyboard_socket)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800937 }
938
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800939 for dev_path in &cfg.virtio_input_evdevs {
David Tolnay2b089fc2019-03-04 15:33:22 -0800940 devs.push(create_vinput_device(cfg, dev_path)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800941 }
942
David Tolnay2b089fc2019-03-04 15:33:22 -0800943 devs.push(create_balloon_device(cfg, balloon_device_socket)?);
Dylan Reid295ccac2017-11-06 14:06:24 -0800944
Zach Reizner39aa26b2017-12-12 18:03:23 -0800945 // We checked above that if the IP is defined, then the netmask is, too.
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800946 for tap_fd in &cfg.tap_fd {
David Tolnay2b089fc2019-03-04 15:33:22 -0800947 devs.push(create_tap_net_device(cfg, *tap_fd)?);
Jorge E. Moreirab7952802019-02-12 16:43:05 -0800948 }
949
David Tolnay2b089fc2019-03-04 15:33:22 -0800950 if let (Some(host_ip), Some(netmask), Some(mac_address)) =
951 (cfg.host_ip, cfg.netmask, cfg.mac_address)
952 {
953 devs.push(create_net_device(cfg, host_ip, netmask, mac_address, mem)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800954 }
955
David Tolnayfa701712019-02-13 16:42:54 -0800956 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900957 let mut resource_bridges = Vec::<virtio::resource_bridge::ResourceResponseSocket>::new();
958
959 if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() {
960 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
961 let mut wl_resource_bridge = None::<virtio::resource_bridge::ResourceRequestSocket>;
962
963 #[cfg(feature = "gpu")]
964 {
965 if cfg.gpu {
966 let (wl_socket, gpu_socket) =
967 virtio::resource_bridge::pair().map_err(Error::CreateSocket)?;
968 resource_bridges.push(gpu_socket);
969 wl_resource_bridge = Some(wl_socket);
970 }
971 }
972
973 devs.push(create_wayland_device(
974 cfg,
975 wayland_socket_path,
976 wayland_device_socket,
977 wl_resource_bridge,
978 )?);
979 }
David Tolnayfa701712019-02-13 16:42:54 -0800980
Zach Reizner3a8100a2017-09-13 19:15:43 -0700981 #[cfg(feature = "gpu")]
982 {
983 if cfg.gpu {
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700984 devs.push(create_gpu_device(
985 cfg,
986 _exit_evt,
987 gpu_device_socket,
988 resource_bridges,
989 cfg.wayland_socket_path.clone(),
990 cfg.x_display.clone(),
991 )?);
Zach Reizner3a8100a2017-09-13 19:15:43 -0700992 }
993 }
994
Zach Reizneraa575662018-08-15 10:46:32 -0700995 if let Some(cid) = cfg.cid {
David Tolnay2b089fc2019-03-04 15:33:22 -0800996 devs.push(create_vhost_vsock_device(cfg, cid, mem)?);
Zach Reizneraa575662018-08-15 10:46:32 -0700997 }
998
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900999 for shared_dir in &cfg.shared_dirs {
1000 let SharedDir {
1001 src,
1002 tag,
1003 kind,
1004 uid_map,
1005 gid_map,
1006 cfg: fs_cfg,
1007 } = shared_dir;
David Tolnay2b089fc2019-03-04 15:33:22 -08001008
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001009 let dev = match kind {
1010 SharedDirKind::FS => create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone())?,
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +09001011 SharedDirKind::P9 => create_9p_device(cfg, src, tag)?,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001012 };
1013 devs.push(dev);
David Tolnay2b089fc2019-03-04 15:33:22 -08001014 }
1015
1016 Ok(devs)
1017}
1018
1019fn create_devices(
Trent Begin17ccaad2019-04-17 13:51:25 -06001020 cfg: &Config,
David Tolnay2b089fc2019-03-04 15:33:22 -08001021 mem: &GuestMemory,
Jakub Starona3411ea2019-04-24 10:55:25 -07001022 vm: &mut Vm,
1023 resources: &mut SystemAllocator,
David Tolnay2b089fc2019-03-04 15:33:22 -08001024 exit_evt: &EventFd,
Xiong Zhanga5d248c2019-09-17 14:17:19 -07001025 control_sockets: &mut Vec<TaggedControlSocket>,
Gurchetan Singh53edb812019-05-22 08:57:16 -07001026 wayland_device_socket: VmMemoryControlRequestSocket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001027 gpu_device_socket: VmMemoryControlRequestSocket,
Jakub Staron1f828d72019-04-11 12:49:29 -07001028 balloon_device_socket: BalloonControlResponseSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -07001029 disk_device_sockets: &mut Vec<DiskControlResponseSocket>,
Jingkui Wang100e6e42019-03-08 20:41:57 -08001030 usb_provider: HostBackendDeviceProvider,
David Tolnayfdac5ed2019-03-08 16:56:14 -08001031) -> DeviceResult<Vec<(Box<dyn PciDevice>, Option<Minijail>)>> {
David Tolnay2b089fc2019-03-04 15:33:22 -08001032 let stubs = create_virtio_devices(
1033 &cfg,
1034 mem,
Jakub Starona3411ea2019-04-24 10:55:25 -07001035 vm,
1036 resources,
David Tolnay2b089fc2019-03-04 15:33:22 -08001037 exit_evt,
1038 wayland_device_socket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001039 gpu_device_socket,
David Tolnay2b089fc2019-03-04 15:33:22 -08001040 balloon_device_socket,
1041 disk_device_sockets,
1042 )?;
1043
1044 let mut pci_devices = Vec::new();
1045
1046 for stub in stubs {
Xiong Zhanga5d248c2019-09-17 14:17:19 -07001047 let dev = if stub.dev.msix_vectors() > 0 {
1048 let (msi_host_socket, msi_device_socket) =
1049 msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?;
1050 control_sockets.push(TaggedControlSocket::VmIrq(msi_host_socket));
1051
1052 VirtioPciDevice::new(mem.clone(), stub.dev, Some(msi_device_socket))
1053 .map_err(Error::VirtioPciDev)?
1054 } else {
1055 VirtioPciDevice::new(mem.clone(), stub.dev, None).map_err(Error::VirtioPciDev)?
1056 };
1057
David Tolnayfdac5ed2019-03-08 16:56:14 -08001058 let dev = Box::new(dev) as Box<dyn PciDevice>;
David Tolnay2b089fc2019-03-04 15:33:22 -08001059 pci_devices.push((dev, stub.jail));
1060 }
1061
1062 if cfg.cras_audio {
paulhsia580d4182019-05-24 16:53:55 +08001063 let mut server = Box::new(CrasClient::new().map_err(Error::CreateCrasClient)?);
1064 if cfg.cras_capture {
1065 server.enable_cras_capture();
1066 }
David Tolnay2b089fc2019-03-04 15:33:22 -08001067 let cras_audio = devices::Ac97Dev::new(mem.clone(), server);
1068
1069 pci_devices.push((
1070 Box::new(cras_audio),
1071 simple_jail(&cfg, "cras_audio_device.policy")?,
1072 ));
1073 }
1074
1075 if cfg.null_audio {
1076 let server = Box::new(DummyStreamSource::new());
1077 let null_audio = devices::Ac97Dev::new(mem.clone(), server);
1078
1079 pci_devices.push((
1080 Box::new(null_audio),
1081 simple_jail(&cfg, "null_audio_device.policy")?,
1082 ));
1083 }
Jingkui Wang100e6e42019-03-08 20:41:57 -08001084 // Create xhci controller.
1085 let usb_controller = Box::new(XhciController::new(mem.clone(), usb_provider));
1086 pci_devices.push((usb_controller, simple_jail(&cfg, "xhci.policy")?));
David Tolnay2b089fc2019-03-04 15:33:22 -08001087
Xiong Zhang17b0daf2019-04-23 17:14:50 +08001088 if cfg.vfio.is_some() {
Xiong Zhang4b5bb3a2019-04-23 17:15:21 +08001089 let (vfio_host_socket_irq, vfio_device_socket_irq) =
1090 msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?;
1091 control_sockets.push(TaggedControlSocket::VmIrq(vfio_host_socket_irq));
1092
Xiong Zhang17b0daf2019-04-23 17:14:50 +08001093 let vfio_path = cfg.vfio.as_ref().unwrap().as_path();
Xiong Zhangc554fff2019-04-23 17:14:55 +08001094 let vfiodevice =
Daniel Verkamp04a82c72019-09-24 11:06:58 -07001095 VfioDevice::new(vfio_path, vm, mem.clone()).map_err(Error::CreateVfioDevice)?;
Xiong Zhang4b5bb3a2019-04-23 17:15:21 +08001096 let vfiopcidevice = Box::new(VfioPciDevice::new(vfiodevice, vfio_device_socket_irq));
Xiong Zhang17b0daf2019-04-23 17:14:50 +08001097 pci_devices.push((vfiopcidevice, simple_jail(&cfg, "vfio_device.policy")?));
1098 }
1099
David Tolnay2b089fc2019-03-04 15:33:22 -08001100 Ok(pci_devices)
1101}
1102
1103#[derive(Copy, Clone)]
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +09001104#[cfg_attr(not(feature = "tpm"), allow(dead_code))]
David Tolnay2b089fc2019-03-04 15:33:22 -08001105struct Ids {
1106 uid: uid_t,
1107 gid: gid_t,
1108}
1109
David Tolnay48c48292019-03-01 16:54:25 -08001110// Set the uid/gid for the jailed process and give a basic id map. This is
1111// required for bind mounts to work.
David Tolnayfd0971d2019-03-04 17:15:57 -08001112fn add_crosvm_user_to_jail(jail: &mut Minijail, feature: &str) -> Result<Ids> {
David Tolnay48c48292019-03-01 16:54:25 -08001113 let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap();
1114
1115 let crosvm_uid = match get_user_id(&crosvm_user_group) {
1116 Ok(u) => u,
1117 Err(e) => {
1118 warn!("falling back to current user id for {}: {}", feature, e);
1119 geteuid()
1120 }
1121 };
1122
1123 let crosvm_gid = match get_group_id(&crosvm_user_group) {
1124 Ok(u) => u,
1125 Err(e) => {
1126 warn!("falling back to current group id for {}: {}", feature, e);
1127 getegid()
1128 }
1129 };
1130
1131 jail.change_uid(crosvm_uid);
1132 jail.change_gid(crosvm_gid);
1133 jail.uidmap(&format!("{0} {0} 1", crosvm_uid))
1134 .map_err(Error::SettingUidMap)?;
1135 jail.gidmap(&format!("{0} {0} 1", crosvm_gid))
1136 .map_err(Error::SettingGidMap)?;
1137
David Tolnay41a6f842019-03-01 16:18:44 -08001138 Ok(Ids {
1139 uid: crosvm_uid,
1140 gid: crosvm_gid,
1141 })
David Tolnay48c48292019-03-01 16:54:25 -08001142}
1143
David Tolnayfd0971d2019-03-04 17:15:57 -08001144fn raw_fd_from_path(path: &Path) -> Result<RawFd> {
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001145 if !path.is_file() {
David Tolnayfd0971d2019-03-04 17:15:57 -08001146 return Err(Error::InvalidFdPath);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001147 }
1148 let raw_fd = path
1149 .file_name()
1150 .and_then(|fd_osstr| fd_osstr.to_str())
1151 .and_then(|fd_str| fd_str.parse::<c_int>().ok())
1152 .ok_or(Error::InvalidFdPath)?;
David Tolnayfd0971d2019-03-04 17:15:57 -08001153 validate_raw_fd(raw_fd).map_err(Error::ValidateRawFd)
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001154}
1155
David Tolnayfd0971d2019-03-04 17:15:57 -08001156fn create_input_socket(path: &Path) -> Result<UnixStream> {
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001157 if path.parent() == Some(Path::new("/proc/self/fd")) {
1158 // Safe because we will validate |raw_fd|.
1159 unsafe { Ok(UnixStream::from_raw_fd(raw_fd_from_path(path)?)) }
1160 } else {
David Tolnayfd0971d2019-03-04 17:15:57 -08001161 UnixStream::connect(path).map_err(Error::InputEventsOpen)
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001162 }
1163}
1164
Matt Delco84cf9c02019-10-07 22:38:13 -07001165fn setup_vcpu_signal_handler(use_kvm_signals: bool) -> Result<()> {
1166 if use_kvm_signals {
1167 unsafe {
1168 extern "C" fn handle_signal() {}
1169 // Our signal handler does nothing and is trivially async signal safe.
1170 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
1171 .map_err(Error::RegisterSignalHandler)?;
1172 }
1173 block_signal(SIGRTMIN() + 0).map_err(Error::BlockSignal)?;
1174 } else {
1175 unsafe {
1176 extern "C" fn handle_signal() {
1177 Vcpu::set_local_immediate_exit(true);
1178 }
1179 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
1180 .map_err(Error::RegisterSignalHandler)?;
1181 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001182 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001183 Ok(())
1184}
1185
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001186#[derive(Default)]
1187struct VcpuRunMode {
1188 mtx: Mutex<VmRunMode>,
1189 cvar: Condvar,
1190}
1191
1192impl VcpuRunMode {
1193 fn set_and_notify(&self, new_mode: VmRunMode) {
1194 *self.mtx.lock() = new_mode;
1195 self.cvar.notify_all();
1196 }
1197}
1198
Zach Reizner55a9e502018-10-03 10:22:32 -07001199fn run_vcpu(
Matt Delco84cf9c02019-10-07 22:38:13 -07001200 mut vcpu: Vcpu,
Zach Reizner55a9e502018-10-03 10:22:32 -07001201 cpu_id: u32,
Daniel Verkamp107edb32019-04-05 09:58:48 -07001202 vcpu_affinity: Vec<usize>,
Zach Reizner55a9e502018-10-03 10:22:32 -07001203 start_barrier: Arc<Barrier>,
1204 io_bus: devices::Bus,
1205 mmio_bus: devices::Bus,
1206 exit_evt: EventFd,
Zach Reizner795355a2019-01-16 17:37:57 -08001207 requires_kvmclock_ctrl: bool,
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001208 run_mode_arc: Arc<VcpuRunMode>,
Matt Delco84cf9c02019-10-07 22:38:13 -07001209 use_kvm_signals: bool,
Zach Reizner55a9e502018-10-03 10:22:32 -07001210) -> Result<JoinHandle<()>> {
Zach Reizner8fb52112017-12-13 16:04:39 -08001211 thread::Builder::new()
1212 .name(format!("crosvm_vcpu{}", cpu_id))
1213 .spawn(move || {
Daniel Verkamp107edb32019-04-05 09:58:48 -07001214 if vcpu_affinity.len() != 0 {
1215 if let Err(e) = set_cpu_affinity(vcpu_affinity) {
1216 error!("Failed to set CPU affinity: {}", e);
1217 }
1218 }
1219
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001220 let mut sig_ok = true;
Matt Delco84cf9c02019-10-07 22:38:13 -07001221 if use_kvm_signals {
1222 match get_blocked_signals() {
1223 Ok(mut v) => {
1224 v.retain(|&x| x != SIGRTMIN() + 0);
1225 if let Err(e) = vcpu.set_signal_mask(&v) {
1226 error!(
1227 "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {}",
1228 cpu_id, e
1229 );
1230 sig_ok = false;
1231 }
1232 }
1233 Err(e) => {
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001234 error!(
Matt Delco84cf9c02019-10-07 22:38:13 -07001235 "Failed to retrieve signal mask for vcpu {} : {}",
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001236 cpu_id, e
1237 );
1238 sig_ok = false;
1239 }
Matt Delco84cf9c02019-10-07 22:38:13 -07001240 };
1241 } else {
1242 vcpu.set_thread_id(SIGRTMIN() + 0);
1243 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001244
Zach Reizner8fb52112017-12-13 16:04:39 -08001245 start_barrier.wait();
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001246
David Tolnay8f3a2322018-11-30 17:11:35 -08001247 if sig_ok {
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001248 'vcpu_loop: loop {
1249 let mut interrupted_by_signal = false;
David Tolnay8f3a2322018-11-30 17:11:35 -08001250 match vcpu.run() {
1251 Ok(VcpuExit::IoIn { port, mut size }) => {
1252 let mut data = [0; 8];
1253 if size > data.len() {
1254 error!("unsupported IoIn size of {} bytes", size);
1255 size = data.len();
Zach Reizner39aa26b2017-12-12 18:03:23 -08001256 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001257 io_bus.read(port as u64, &mut data[..size]);
1258 if let Err(e) = vcpu.set_data(&data[..size]) {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001259 error!("failed to set return data for IoIn: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001260 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001261 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001262 Ok(VcpuExit::IoOut {
1263 port,
1264 mut size,
1265 data,
1266 }) => {
1267 if size > data.len() {
1268 error!("unsupported IoOut size of {} bytes", size);
1269 size = data.len();
1270 }
1271 io_bus.write(port as u64, &data[..size]);
1272 }
1273 Ok(VcpuExit::MmioRead { address, size }) => {
1274 let mut data = [0; 8];
1275 mmio_bus.read(address, &mut data[..size]);
1276 // Setting data for mmio can not fail.
1277 let _ = vcpu.set_data(&data[..size]);
1278 }
1279 Ok(VcpuExit::MmioWrite {
1280 address,
1281 size,
1282 data,
1283 }) => {
1284 mmio_bus.write(address, &data[..size]);
1285 }
1286 Ok(VcpuExit::Hlt) => break,
1287 Ok(VcpuExit::Shutdown) => break,
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001288 Ok(VcpuExit::SystemEvent(_, _)) => break,
David Tolnay8f3a2322018-11-30 17:11:35 -08001289 Ok(r) => warn!("unexpected vcpu exit: {:?}", r),
1290 Err(e) => match e.errno() {
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001291 libc::EINTR => interrupted_by_signal = true,
1292 libc::EAGAIN => {}
David Tolnay8f3a2322018-11-30 17:11:35 -08001293 _ => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001294 error!("vcpu hit unknown error: {}", e);
David Tolnay8f3a2322018-11-30 17:11:35 -08001295 break;
1296 }
1297 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08001298 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001299
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001300 if interrupted_by_signal {
Matt Delco84cf9c02019-10-07 22:38:13 -07001301 if use_kvm_signals {
1302 // Try to clear the signal that we use to kick VCPU if it is pending before
1303 // attempting to handle pause requests.
1304 if let Err(e) = clear_signal(SIGRTMIN() + 0) {
1305 error!("failed to clear pending signal: {}", e);
1306 break;
1307 }
1308 } else {
1309 vcpu.set_immediate_exit(false);
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001310 }
1311 let mut run_mode_lock = run_mode_arc.mtx.lock();
1312 loop {
1313 match *run_mode_lock {
1314 VmRunMode::Running => break,
Zach Reizner795355a2019-01-16 17:37:57 -08001315 VmRunMode::Suspending => {
1316 // On KVM implementations that use a paravirtualized clock (e.g.
1317 // x86), a flag must be set to indicate to the guest kernel that
1318 // a VCPU was suspended. The guest kernel will use this flag to
1319 // prevent the soft lockup detection from triggering when this
1320 // VCPU resumes, which could happen days later in realtime.
1321 if requires_kvmclock_ctrl {
1322 if let Err(e) = vcpu.kvmclock_ctrl() {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001323 error!("failed to signal to kvm that vcpu {} is being suspended: {}", cpu_id, e);
Zach Reizner795355a2019-01-16 17:37:57 -08001324 }
1325 }
1326 }
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001327 VmRunMode::Exiting => break 'vcpu_loop,
1328 }
1329 // Give ownership of our exclusive lock to the condition variable that
1330 // will block. When the condition variable is notified, `wait` will
1331 // unblock and return a new exclusive lock.
1332 run_mode_lock = run_mode_arc.cvar.wait(run_mode_lock);
1333 }
1334 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001335 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001336 }
Zach Reizner8fb52112017-12-13 16:04:39 -08001337 exit_evt
Zach Reizner39aa26b2017-12-12 18:03:23 -08001338 .write(1)
1339 .expect("failed to signal vcpu exit eventfd");
David Tolnay2bac1e72018-12-12 14:33:42 -08001340 })
1341 .map_err(Error::SpawnVcpu)
Zach Reizner39aa26b2017-12-12 18:03:23 -08001342}
1343
Sonny Raod5f66082019-04-24 12:24:38 -07001344// Reads the contents of a file and converts the space-separated fields into a Vec of u64s.
1345// Returns an error if any of the fields fail to parse.
1346fn file_fields_to_u64<P: AsRef<Path>>(path: P) -> io::Result<Vec<u64>> {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001347 let mut file = File::open(path)?;
1348
1349 let mut buf = [0u8; 32];
1350 let count = file.read(&mut buf)?;
1351
Zach Reizner55a9e502018-10-03 10:22:32 -07001352 let content =
1353 str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1354 content
1355 .trim()
Sonny Raod5f66082019-04-24 12:24:38 -07001356 .split_whitespace()
1357 .map(|x| {
1358 x.parse::<u64>()
1359 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
1360 })
1361 .collect()
1362}
1363
1364// Reads the contents of a file and converts them into a u64, and if there
1365// are multiple fields it only returns the first one.
1366fn file_to_u64<P: AsRef<Path>>(path: P) -> io::Result<u64> {
1367 file_fields_to_u64(path)?
1368 .into_iter()
1369 .next()
1370 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty file"))
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001371}
1372
Dylan Reid059a1882018-07-23 17:58:09 -07001373pub fn run_config(cfg: Config) -> Result<()> {
Lepton Wu9105e9f2019-03-14 11:38:31 -07001374 if cfg.sandbox {
Dylan Reid059a1882018-07-23 17:58:09 -07001375 // Printing something to the syslog before entering minijail so that libc's syslogger has a
1376 // chance to open files necessary for its operation, like `/etc/localtime`. After jailing,
1377 // access to those files will not be possible.
1378 info!("crosvm entering multiprocess mode");
1379 }
1380
Jingkui Wang100e6e42019-03-08 20:41:57 -08001381 let (usb_control_socket, usb_provider) =
David Tolnay5fb3f512019-04-12 19:22:33 -07001382 HostBackendDeviceProvider::new().map_err(Error::CreateUsbProvider)?;
Dylan Reid059a1882018-07-23 17:58:09 -07001383 // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
1384 // before any jailed devices have been spawned, so that we can catch any of them that fail very
1385 // quickly.
1386 let sigchld_fd = SignalFd::new(libc::SIGCHLD).map_err(Error::CreateSignalFd)?;
1387
David Tolnay2b089fc2019-03-04 15:33:22 -08001388 let initrd_image = if let Some(initrd_path) = &cfg.initrd_path {
1389 Some(File::open(initrd_path).map_err(|e| Error::OpenInitrd(initrd_path.clone(), e))?)
Daniel Verkampe403f5c2018-12-11 16:29:26 -08001390 } else {
1391 None
1392 };
1393
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07001394 let vm_image = match cfg.executable_path {
1395 Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel(
1396 File::open(kernel_path).map_err(|e| Error::OpenKernel(kernel_path.to_path_buf(), e))?,
1397 ),
1398 Some(Executable::Bios(ref bios_path)) => VmImage::Bios(
1399 File::open(bios_path).map_err(|e| Error::OpenBios(bios_path.to_path_buf(), e))?,
1400 ),
1401 _ => panic!("Did not receive a bios or kernel, should be impossible."),
1402 };
1403
Dylan Reid059a1882018-07-23 17:58:09 -07001404 let components = VmComponents {
Jakub Staronf55f75d2019-04-26 11:22:51 -07001405 memory_size: (cfg.memory.unwrap_or(256) << 20) as u64,
Dylan Reid059a1882018-07-23 17:58:09 -07001406 vcpu_count: cfg.vcpu_count.unwrap_or(1),
Daniel Verkamp107edb32019-04-05 09:58:48 -07001407 vcpu_affinity: cfg.vcpu_affinity.clone(),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07001408 vm_image,
Tristan Muntsinger4133b012018-12-21 16:01:56 -08001409 android_fstab: cfg
1410 .android_fstab
1411 .as_ref()
David Tolnay2b089fc2019-03-04 15:33:22 -08001412 .map(|x| File::open(x).map_err(|e| Error::OpenAndroidFstab(x.to_path_buf(), e)))
Tristan Muntsinger4133b012018-12-21 16:01:56 -08001413 .map_or(Ok(None), |v| v.map(Some))?,
Daniel Verkampe403f5c2018-12-11 16:29:26 -08001414 initrd_image,
Daniel Verkampaac28132018-10-15 14:58:48 -07001415 extra_kernel_params: cfg.params.clone(),
1416 wayland_dmabuf: cfg.wayland_dmabuf,
Dylan Reid059a1882018-07-23 17:58:09 -07001417 };
1418
Zach Reiznera60744b2019-02-13 17:33:32 -08001419 let control_server_socket = match &cfg.socket_path {
1420 Some(path) => Some(UnlinkUnixSeqpacketListener(
1421 UnixSeqpacketListener::bind(path).map_err(Error::CreateSocket)?,
1422 )),
1423 None => None,
Dylan Reid059a1882018-07-23 17:58:09 -07001424 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001425
1426 let mut control_sockets = Vec::new();
Zach Reizner55a9e502018-10-03 10:22:32 -07001427 let (wayland_host_socket, wayland_device_socket) =
Gurchetan Singh53edb812019-05-22 08:57:16 -07001428 msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?;
1429 control_sockets.push(TaggedControlSocket::VmMemory(wayland_host_socket));
Dylan Reid059a1882018-07-23 17:58:09 -07001430 // Balloon gets a special socket so balloon requests can be forwarded from the main process.
Zach Reizner55a9e502018-10-03 10:22:32 -07001431 let (balloon_host_socket, balloon_device_socket) =
Jakub Staron1f828d72019-04-11 12:49:29 -07001432 msg_socket::pair::<BalloonControlCommand, ()>().map_err(Error::CreateSocket)?;
Dylan Reid059a1882018-07-23 17:58:09 -07001433
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001434 // Create one control socket per disk.
1435 let mut disk_device_sockets = Vec::new();
1436 let mut disk_host_sockets = Vec::new();
1437 let disk_count = cfg.disks.len();
1438 for _ in 0..disk_count {
1439 let (disk_host_socket, disk_device_socket) =
Jakub Staronecf81e02019-04-11 11:43:39 -07001440 msg_socket::pair::<DiskControlCommand, DiskControlResult>()
1441 .map_err(Error::CreateSocket)?;
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001442 disk_host_sockets.push(disk_host_socket);
Jakub Starone7c59052019-04-09 12:31:14 -07001443 disk_device_sockets.push(disk_device_socket);
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001444 }
1445
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001446 let (gpu_host_socket, gpu_device_socket) =
1447 msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?;
1448 control_sockets.push(TaggedControlSocket::VmMemory(gpu_host_socket));
1449
Lepton Wu20333e42019-03-14 10:48:03 -07001450 let sandbox = cfg.sandbox;
Trent Begin17ccaad2019-04-17 13:51:25 -06001451 let linux = Arch::build_vm(
1452 components,
1453 cfg.split_irqchip,
1454 &cfg.serial_parameters,
Zach Reiznera8adff02019-08-13 11:20:14 -07001455 simple_jail(&cfg, "serial.policy")?,
Jakub Starona3411ea2019-04-24 10:55:25 -07001456 |mem, vm, sys_allocator, exit_evt| {
Trent Begin17ccaad2019-04-17 13:51:25 -06001457 create_devices(
1458 &cfg,
Jakub Starona3411ea2019-04-24 10:55:25 -07001459 mem,
1460 vm,
1461 sys_allocator,
1462 exit_evt,
Xiong Zhanga5d248c2019-09-17 14:17:19 -07001463 &mut control_sockets,
Trent Begin17ccaad2019-04-17 13:51:25 -06001464 wayland_device_socket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001465 gpu_device_socket,
Trent Begin17ccaad2019-04-17 13:51:25 -06001466 balloon_device_socket,
1467 &mut disk_device_sockets,
1468 usb_provider,
1469 )
1470 },
1471 )
David Tolnaybe034262019-03-04 17:48:36 -08001472 .map_err(Error::BuildVm)?;
Lepton Wu60893882018-11-21 11:06:18 -08001473
1474 let _render_node_host = ();
1475 #[cfg(feature = "gpu-forward")]
1476 let (_render_node_host, linux) = {
1477 // Rebinds linux as mutable.
1478 let mut linux = linux;
1479
1480 // Reserve memory range for GPU buffer allocation in advance to bypass region count
1481 // limitation. We use mremap/MAP_FIXED later to make sure GPU buffers fall into this range.
1482 let gpu_mmap =
1483 MemoryMapping::new_protection(RENDER_NODE_HOST_SIZE as usize, Protection::none())
1484 .map_err(Error::ReserveGpuMemory)?;
1485
Xiong Zhang383b3b52019-10-30 14:59:26 +08001486 // Put the non-accessible memory map into high mmio so that no other devices use that
Lepton Wu60893882018-11-21 11:06:18 -08001487 // guest address space.
1488 let gpu_addr = linux
1489 .resources
Xiong Zhang383b3b52019-10-30 14:59:26 +08001490 .mmio_allocator(MmioType::High)
Daniel Prilikd92f81a2019-03-26 14:28:19 -07001491 .allocate(
1492 RENDER_NODE_HOST_SIZE,
1493 Alloc::GpuRenderNode,
1494 "gpu_render_node".to_string(),
1495 )
1496 .map_err(|_| Error::AllocateGpuDeviceAddress)?;
Lepton Wu60893882018-11-21 11:06:18 -08001497
1498 let host = RenderNodeHost::start(&gpu_mmap, gpu_addr, linux.vm.get_memory().clone());
1499
1500 // Makes the gpu memory accessible at allocated address.
1501 linux
1502 .vm
Xiong Zhang383b3b52019-10-30 14:59:26 +08001503 .add_mmio_memory(
Lepton Wu60893882018-11-21 11:06:18 -08001504 GuestAddress(gpu_addr),
1505 gpu_mmap,
1506 /* read_only = */ false,
1507 /* log_dirty_pages = */ false,
1508 )
1509 .map_err(Error::AddGpuDeviceMemory)?;
1510 (host, linux)
1511 };
1512
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001513 run_control(
1514 linux,
Zach Reiznera60744b2019-02-13 17:33:32 -08001515 control_server_socket,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001516 control_sockets,
1517 balloon_host_socket,
1518 &disk_host_sockets,
Jingkui Wang100e6e42019-03-08 20:41:57 -08001519 usb_control_socket,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001520 sigchld_fd,
Lepton Wu60893882018-11-21 11:06:18 -08001521 _render_node_host,
Lepton Wu20333e42019-03-14 10:48:03 -07001522 sandbox,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001523 )
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001524}
1525
Zach Reizner55a9e502018-10-03 10:22:32 -07001526fn run_control(
1527 mut linux: RunnableLinuxVm,
Zach Reiznera60744b2019-02-13 17:33:32 -08001528 control_server_socket: Option<UnlinkUnixSeqpacketListener>,
Jakub Starond99cd0a2019-04-11 14:09:39 -07001529 mut control_sockets: Vec<TaggedControlSocket>,
Jakub Staron1f828d72019-04-11 12:49:29 -07001530 balloon_host_socket: BalloonControlRequestSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -07001531 disk_host_sockets: &[DiskControlRequestSocket],
Jingkui Wang100e6e42019-03-08 20:41:57 -08001532 usb_control_socket: UsbControlSocket,
Zach Reizner55a9e502018-10-03 10:22:32 -07001533 sigchld_fd: SignalFd,
Lepton Wu60893882018-11-21 11:06:18 -08001534 _render_node_host: RenderNodeHost,
Lepton Wu20333e42019-03-14 10:48:03 -07001535 sandbox: bool,
Zach Reizner55a9e502018-10-03 10:22:32 -07001536) -> Result<()> {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001537 // Paths to get the currently available memory and the low memory threshold.
David Tolnay5bbbf612018-12-01 17:49:30 -08001538 const LOWMEM_MARGIN: &str = "/sys/kernel/mm/chromeos-low_mem/margin";
1539 const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available";
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001540
1541 // The amount of additional memory to claim back from the VM whenever the system is
1542 // low on memory.
1543 const ONE_GB: u64 = (1 << 30);
1544
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001545 let max_balloon_memory = match linux.vm.get_memory().memory_size() {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001546 // If the VM has at least 1.5 GB, the balloon driver can consume all but the last 1 GB.
1547 n if n >= (ONE_GB / 2) * 3 => n - ONE_GB,
1548 // Otherwise, if the VM has at least 500MB the balloon driver will consume at most
1549 // half of it.
1550 n if n >= (ONE_GB / 2) => n / 2,
1551 // Otherwise, the VM is too small for us to take memory away from it.
1552 _ => 0,
1553 };
1554 let mut current_balloon_memory: u64 = 0;
1555 let balloon_memory_increment: u64 = max_balloon_memory / 16;
1556
Zach Reizner5bed0d22018-03-28 02:31:11 -07001557 #[derive(PollToken)]
1558 enum Token {
1559 Exit,
1560 Stdin,
1561 ChildSignal,
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001562 CheckAvailableMemory,
1563 LowMemory,
1564 LowmemTimer,
Zach Reiznera60744b2019-02-13 17:33:32 -08001565 VmControlServer,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001566 VmControl { index: usize },
1567 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001568
1569 let stdin_handle = stdin();
1570 let stdin_lock = stdin_handle.lock();
1571 stdin_lock
1572 .set_raw_mode()
1573 .expect("failed to set terminal raw mode");
1574
Zach Reiznerb2110be2019-07-23 15:55:03 -07001575 let poll_ctx = PollContext::build_with(&[
1576 (&linux.exit_evt, Token::Exit),
1577 (&sigchld_fd, Token::ChildSignal),
1578 ])
1579 .map_err(Error::PollContextAdd)?;
1580
Zach Reizner5bed0d22018-03-28 02:31:11 -07001581 if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001582 warn!("failed to add stdin to poll context: {}", e);
Zach Reizner5bed0d22018-03-28 02:31:11 -07001583 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001584
1585 if let Some(socket_server) = &control_server_socket {
1586 poll_ctx
1587 .add(socket_server, Token::VmControlServer)
1588 .map_err(Error::PollContextAdd)?;
1589 }
Dylan Reid059a1882018-07-23 17:58:09 -07001590 for (index, socket) in control_sockets.iter().enumerate() {
Zach Reizner55a9e502018-10-03 10:22:32 -07001591 poll_ctx
1592 .add(socket.as_ref(), Token::VmControl { index })
1593 .map_err(Error::PollContextAdd)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001594 }
1595
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001596 // Watch for low memory notifications and take memory back from the VM.
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001597 let low_mem = File::open("/dev/chromeos-low-mem").ok();
David Tolnay64cd5ea2019-04-15 15:56:35 -07001598 if let Some(low_mem) = &low_mem {
Zach Reizner55a9e502018-10-03 10:22:32 -07001599 poll_ctx
1600 .add(low_mem, Token::LowMemory)
1601 .map_err(Error::PollContextAdd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001602 } else {
1603 warn!("Unable to open low mem indicator, maybe not a chrome os kernel");
1604 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001605
1606 // Used to rate limit balloon requests.
1607 let mut lowmem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001608 poll_ctx
1609 .add(&lowmem_timer, Token::LowmemTimer)
1610 .map_err(Error::PollContextAdd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001611
1612 // Used to check whether it's ok to start giving memory back to the VM.
1613 let mut freemem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001614 poll_ctx
1615 .add(&freemem_timer, Token::CheckAvailableMemory)
1616 .map_err(Error::PollContextAdd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001617
1618 // Used to add jitter to timer values so that we don't have a thundering herd problem when
1619 // multiple VMs are running.
Daniel Prilik22006042019-01-14 14:19:04 -08001620 let mut simple_rng = SimpleRng::new(
1621 SystemTime::now()
1622 .duration_since(UNIX_EPOCH)
1623 .expect("time went backwards")
1624 .subsec_nanos() as u64,
1625 );
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001626
Lepton Wu20333e42019-03-14 10:48:03 -07001627 if sandbox {
1628 // Before starting VCPUs, in case we started with some capabilities, drop them all.
1629 drop_capabilities().map_err(Error::DropCapabilities)?;
1630 }
Dmitry Torokhov71006072019-03-06 10:56:51 -08001631
Daniel Verkamp37c4a782019-01-04 10:44:17 -08001632 let mut vcpu_handles = Vec::with_capacity(linux.vcpus.len());
1633 let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpus.len() + 1));
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001634 let run_mode_arc = Arc::new(VcpuRunMode::default());
Matt Delco84cf9c02019-10-07 22:38:13 -07001635 let use_kvm_signals = !linux.kvm.check_extension(Cap::ImmediateExit);
1636 setup_vcpu_signal_handler(use_kvm_signals)?;
Daniel Verkamp94c35272019-09-12 13:31:30 -07001637 let vcpus = linux.vcpus.split_off(0);
1638 for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {
Zach Reizner55a9e502018-10-03 10:22:32 -07001639 let handle = run_vcpu(
1640 vcpu,
1641 cpu_id as u32,
Daniel Verkamp107edb32019-04-05 09:58:48 -07001642 linux.vcpu_affinity.clone(),
Zach Reizner55a9e502018-10-03 10:22:32 -07001643 vcpu_thread_barrier.clone(),
1644 linux.io_bus.clone(),
1645 linux.mmio_bus.clone(),
1646 linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?,
Zach Reizner795355a2019-01-16 17:37:57 -08001647 linux.vm.check_extension(Cap::KvmclockCtrl),
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001648 run_mode_arc.clone(),
Matt Delco84cf9c02019-10-07 22:38:13 -07001649 use_kvm_signals,
Zach Reizner55a9e502018-10-03 10:22:32 -07001650 )?;
Dylan Reid059a1882018-07-23 17:58:09 -07001651 vcpu_handles.push(handle);
1652 }
1653 vcpu_thread_barrier.wait();
1654
Zach Reizner39aa26b2017-12-12 18:03:23 -08001655 'poll: loop {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001656 let events = {
1657 match poll_ctx.wait() {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001658 Ok(v) => v,
1659 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001660 error!("failed to poll: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001661 break;
1662 }
1663 }
1664 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001665
1666 let mut vm_control_indices_to_remove = Vec::new();
Zach Reizner5bed0d22018-03-28 02:31:11 -07001667 for event in events.iter_readable() {
1668 match event.token() {
1669 Token::Exit => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001670 info!("vcpu requested shutdown");
1671 break 'poll;
1672 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001673 Token::Stdin => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001674 let mut out = [0u8; 64];
1675 match stdin_lock.read_raw(&mut out[..]) {
1676 Ok(0) => {
1677 // Zero-length read indicates EOF. Remove from pollables.
Zach Reizner5bed0d22018-03-28 02:31:11 -07001678 let _ = poll_ctx.delete(&stdin_handle);
Zach Reizner55a9e502018-10-03 10:22:32 -07001679 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001680 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001681 warn!("error while reading stdin: {}", e);
Zach Reizner5bed0d22018-03-28 02:31:11 -07001682 let _ = poll_ctx.delete(&stdin_handle);
Zach Reizner55a9e502018-10-03 10:22:32 -07001683 }
Jakub Staronb6515a92019-06-05 15:18:25 -07001684 Ok(count) => {
1685 if let Some(ref stdio_serial) = linux.stdio_serial {
Trent Begin17ccaad2019-04-17 13:51:25 -06001686 stdio_serial
Trent Begin17ccaad2019-04-17 13:51:25 -06001687 .queue_input_bytes(&out[..count])
1688 .expect("failed to queue bytes into serial port");
1689 }
Jakub Staronb6515a92019-06-05 15:18:25 -07001690 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001691 }
1692 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001693 Token::ChildSignal => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001694 // Print all available siginfo structs, then exit the loop.
David Tolnayf5032762018-12-03 10:46:45 -08001695 while let Some(siginfo) = sigchld_fd.read().map_err(Error::SignalFd)? {
Zach Reizner3ba00982019-01-23 19:04:43 -08001696 let pid = siginfo.ssi_pid;
1697 let pid_label = match linux.pid_debug_label_map.get(&pid) {
1698 Some(label) => format!("{} (pid {})", label, pid),
1699 None => format!("pid {}", pid),
1700 };
David Tolnayf5032762018-12-03 10:46:45 -08001701 error!(
1702 "child {} died: signo {}, status {}, code {}",
Zach Reizner3ba00982019-01-23 19:04:43 -08001703 pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code
David Tolnayf5032762018-12-03 10:46:45 -08001704 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08001705 }
David Tolnayf5032762018-12-03 10:46:45 -08001706 break 'poll;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001707 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001708 Token::CheckAvailableMemory => {
1709 // Acknowledge the timer.
1710 freemem_timer.wait().map_err(Error::TimerFd)?;
1711 if current_balloon_memory == 0 {
1712 // Nothing to see here.
1713 if let Err(e) = freemem_timer.clear() {
1714 warn!("unable to clear available memory check timer: {}", e);
1715 }
1716 continue;
1717 }
1718
1719 // Otherwise see if we can free up some memory.
1720 let margin = file_to_u64(LOWMEM_MARGIN).map_err(Error::ReadLowmemMargin)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001721 let available =
1722 file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001723
1724 // `available` and `margin` are specified in MB while `balloon_memory_increment` is in
1725 // bytes. So to correctly compare them we need to turn the increment value into MB.
Zach Reizner55a9e502018-10-03 10:22:32 -07001726 if available >= margin + 2 * (balloon_memory_increment >> 20) {
1727 current_balloon_memory =
1728 if current_balloon_memory >= balloon_memory_increment {
1729 current_balloon_memory - balloon_memory_increment
1730 } else {
1731 0
1732 };
Jakub Staron1f828d72019-04-11 12:49:29 -07001733 let command = BalloonControlCommand::Adjust {
1734 num_bytes: current_balloon_memory,
1735 };
1736 if let Err(e) = balloon_host_socket.send(&command) {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001737 warn!("failed to send memory value to balloon device: {}", e);
1738 }
1739 }
1740 }
1741 Token::LowMemory => {
David Tolnay64cd5ea2019-04-15 15:56:35 -07001742 if let Some(low_mem) = &low_mem {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001743 let old_balloon_memory = current_balloon_memory;
Zach Reizner55a9e502018-10-03 10:22:32 -07001744 current_balloon_memory = min(
1745 current_balloon_memory + balloon_memory_increment,
1746 max_balloon_memory,
1747 );
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001748 if current_balloon_memory != old_balloon_memory {
Jakub Staron1f828d72019-04-11 12:49:29 -07001749 let command = BalloonControlCommand::Adjust {
1750 num_bytes: current_balloon_memory,
1751 };
1752 if let Err(e) = balloon_host_socket.send(&command) {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001753 warn!("failed to send memory value to balloon device: {}", e);
1754 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001755 }
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001756
1757 // Stop polling the lowmem device until the timer fires.
1758 poll_ctx.delete(low_mem).map_err(Error::PollContextDelete)?;
1759
1760 // Add some jitter to the timer so that if there are multiple VMs running
1761 // they don't all start ballooning at exactly the same time.
Daniel Prilik22006042019-01-14 14:19:04 -08001762 let lowmem_dur = Duration::from_millis(1000 + simple_rng.rng() % 200);
Zach Reizner55a9e502018-10-03 10:22:32 -07001763 lowmem_timer
1764 .reset(lowmem_dur, None)
1765 .map_err(Error::ResetTimerFd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001766
1767 // Also start a timer to check when we can start giving memory back. Do the
1768 // first check after a minute (with jitter) and subsequent checks after
1769 // every 30 seconds (with jitter).
Daniel Prilik22006042019-01-14 14:19:04 -08001770 let freemem_dur = Duration::from_secs(60 + simple_rng.rng() % 12);
1771 let freemem_int = Duration::from_secs(30 + simple_rng.rng() % 6);
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001772 freemem_timer
1773 .reset(freemem_dur, Some(freemem_int))
1774 .map_err(Error::ResetTimerFd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001775 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001776 }
1777 Token::LowmemTimer => {
1778 // Acknowledge the timer.
1779 lowmem_timer.wait().map_err(Error::TimerFd)?;
1780
David Tolnay64cd5ea2019-04-15 15:56:35 -07001781 if let Some(low_mem) = &low_mem {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001782 // Start polling the lowmem device again.
Zach Reizner55a9e502018-10-03 10:22:32 -07001783 poll_ctx
1784 .add(low_mem, Token::LowMemory)
1785 .map_err(Error::PollContextAdd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001786 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001787 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001788 Token::VmControlServer => {
1789 if let Some(socket_server) = &control_server_socket {
1790 match socket_server.accept() {
1791 Ok(socket) => {
1792 poll_ctx
1793 .add(
1794 &socket,
1795 Token::VmControl {
1796 index: control_sockets.len(),
1797 },
1798 )
1799 .map_err(Error::PollContextAdd)?;
Jakub Starond99cd0a2019-04-11 14:09:39 -07001800 control_sockets
1801 .push(TaggedControlSocket::Vm(MsgSocket::new(socket)));
Zach Reiznera60744b2019-02-13 17:33:32 -08001802 }
1803 Err(e) => error!("failed to accept socket: {}", e),
1804 }
1805 }
1806 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001807 Token::VmControl { index } => {
Daniel Verkamp37c4a782019-01-04 10:44:17 -08001808 if let Some(socket) = control_sockets.get(index) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001809 match socket {
1810 TaggedControlSocket::Vm(socket) => match socket.recv() {
1811 Ok(request) => {
1812 let mut run_mode_opt = None;
1813 let response = request.execute(
1814 &mut run_mode_opt,
1815 &balloon_host_socket,
1816 disk_host_sockets,
1817 &usb_control_socket,
1818 );
1819 if let Err(e) = socket.send(&response) {
1820 error!("failed to send VmResponse: {}", e);
1821 }
1822 if let Some(run_mode) = run_mode_opt {
1823 info!("control socket changed run mode to {}", run_mode);
1824 match run_mode {
1825 VmRunMode::Exiting => {
1826 break 'poll;
1827 }
1828 other => {
1829 run_mode_arc.set_and_notify(other);
1830 for handle in &vcpu_handles {
1831 let _ = handle.kill(SIGRTMIN() + 0);
1832 }
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001833 }
1834 }
1835 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001836 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001837 Err(e) => {
1838 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1839 vm_control_indices_to_remove.push(index);
1840 } else {
1841 error!("failed to recv VmRequest: {}", e);
1842 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001843 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001844 },
Gurchetan Singh53edb812019-05-22 08:57:16 -07001845 TaggedControlSocket::VmMemory(socket) => match socket.recv() {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001846 Ok(request) => {
1847 let response =
1848 request.execute(&mut linux.vm, &mut linux.resources);
1849 if let Err(e) = socket.send(&response) {
Gurchetan Singh53edb812019-05-22 08:57:16 -07001850 error!("failed to send VmMemoryControlResponse: {}", e);
Jakub Starond99cd0a2019-04-11 14:09:39 -07001851 }
1852 }
1853 Err(e) => {
1854 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1855 vm_control_indices_to_remove.push(index);
1856 } else {
Gurchetan Singh53edb812019-05-22 08:57:16 -07001857 error!("failed to recv VmMemoryControlRequest: {}", e);
Jakub Starond99cd0a2019-04-11 14:09:39 -07001858 }
1859 }
1860 },
Xiong Zhang2515b752019-09-19 10:29:02 +08001861 TaggedControlSocket::VmIrq(socket) => match socket.recv() {
1862 Ok(request) => {
1863 let response =
1864 request.execute(&mut linux.vm, &mut linux.resources);
1865 if let Err(e) = socket.send(&response) {
1866 error!("failed to send VmIrqResponse: {}", e);
1867 }
1868 }
1869 Err(e) => {
1870 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1871 vm_control_indices_to_remove.push(index);
1872 } else {
1873 error!("failed to recv VmIrqRequest: {}", e);
1874 }
1875 }
1876 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08001877 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001878 }
1879 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001880 }
1881 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001882
Zach Reizner5bed0d22018-03-28 02:31:11 -07001883 for event in events.iter_hungup() {
Zach Reiznera60744b2019-02-13 17:33:32 -08001884 match event.token() {
1885 Token::Exit => {}
1886 Token::Stdin => {
1887 let _ = poll_ctx.delete(&stdin_handle);
1888 }
1889 Token::ChildSignal => {}
1890 Token::CheckAvailableMemory => {}
1891 Token::LowMemory => {}
1892 Token::LowmemTimer => {}
1893 Token::VmControlServer => {}
1894 Token::VmControl { index } => {
1895 // It's possible more data is readable and buffered while the socket is hungup,
1896 // so don't delete the socket from the poll context until we're sure all the
1897 // data is read.
Jakub Starond99cd0a2019-04-11 14:09:39 -07001898 match control_sockets
1899 .get(index)
1900 .map(|s| s.as_ref().get_readable_bytes())
1901 {
Zach Reiznera60744b2019-02-13 17:33:32 -08001902 Some(Ok(0)) | Some(Err(_)) => vm_control_indices_to_remove.push(index),
1903 Some(Ok(x)) => info!("control index {} has {} bytes readable", index, x),
1904 _ => {}
Zach Reizner55a9e502018-10-03 10:22:32 -07001905 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001906 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001907 }
1908 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001909
1910 // Sort in reverse so the highest indexes are removed first. This removal algorithm
Zide Chen89584072019-11-14 10:33:51 -08001911 // preserves correct indexes as each element is removed.
Zach Reiznera60744b2019-02-13 17:33:32 -08001912 vm_control_indices_to_remove.sort_unstable_by(|a, b| b.cmp(a));
1913 vm_control_indices_to_remove.dedup();
1914 for index in vm_control_indices_to_remove {
Zide Chen89584072019-11-14 10:33:51 -08001915 // Delete the socket from the `poll_ctx` synchronously. Otherwise, the kernel will do
1916 // this automatically when the FD inserted into the `poll_ctx` is closed after this
1917 // if-block, but this removal can be deferred unpredictably. In some instances where the
1918 // system is under heavy load, we can even get events returned by `poll_ctx` for an FD
1919 // that has already been closed. Because the token associated with that spurious event
1920 // now belongs to a different socket, the control loop will start to interact with
1921 // sockets that might not be ready to use. This can cause incorrect hangup detection or
1922 // blocking on a socket that will never be ready. See also: crbug.com/1019986
1923 if let Some(socket) = control_sockets.get(index) {
1924 poll_ctx.delete(socket).map_err(Error::PollContextDelete)?;
1925 }
1926
1927 // This line implicitly drops the socket at `index` when it gets returned by
1928 // `swap_remove`. After this line, the socket at `index` is not the one from
1929 // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to
1930 // use `poll_ctx.modify` to change the associated index in its `Token::VmControl`.
Zach Reiznera60744b2019-02-13 17:33:32 -08001931 control_sockets.swap_remove(index);
1932 if let Some(socket) = control_sockets.get(index) {
1933 poll_ctx
Xiong Zhang44bb3dd2019-04-23 17:09:50 +08001934 .modify(
1935 socket,
1936 WatchingEvents::empty().set_read(),
1937 Token::VmControl { index },
1938 )
Zach Reiznera60744b2019-02-13 17:33:32 -08001939 .map_err(Error::PollContextAdd)?;
1940 }
1941 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001942 }
1943
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001944 // VCPU threads MUST see the VmRunMode flag, otherwise they may re-enter the VM.
1945 run_mode_arc.set_and_notify(VmRunMode::Exiting);
Dylan Reid059a1882018-07-23 17:58:09 -07001946 for handle in vcpu_handles {
Dmitry Torokhovcd405332018-02-16 16:25:54 -08001947 match handle.kill(SIGRTMIN() + 0) {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001948 Ok(_) => {
1949 if let Err(e) = handle.join() {
1950 error!("failed to join vcpu thread: {:?}", e);
1951 }
1952 }
David Tolnayb4bd00f2019-02-12 17:51:26 -08001953 Err(e) => error!("failed to kill vcpu thread: {}", e),
Zach Reizner39aa26b2017-12-12 18:03:23 -08001954 }
1955 }
1956
Daniel Verkamp94c35272019-09-12 13:31:30 -07001957 // Explicitly drop the VM structure here to allow the devices to clean up before the
1958 // control sockets are closed when this function exits.
1959 mem::drop(linux);
1960
Zach Reizner39aa26b2017-12-12 18:03:23 -08001961 stdin_lock
1962 .set_canon_mode()
1963 .expect("failed to restore canonical mode for terminal");
1964
1965 Ok(())
1966}