blob: 1c606b91351a75689c04b03e07e27205a1b58bb2 [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>),
Daniel Verkamp6a847062019-11-26 13:16:35 -0800113 MemoryTooLarge,
David Tolnay2b089fc2019-03-04 15:33:22 -0800114 NetDeviceNew(virtio::NetError),
Tristan Muntsinger4133b012018-12-21 16:01:56 -0800115 OpenAndroidFstab(PathBuf, io::Error),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700116 OpenBios(PathBuf, io::Error),
Daniel Verkampe403f5c2018-12-11 16:29:26 -0800117 OpenInitrd(PathBuf, io::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800118 OpenKernel(PathBuf, io::Error),
David Tolnayfd0971d2019-03-04 17:15:57 -0800119 OpenVinput(PathBuf, io::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800120 P9DeviceNew(virtio::P9Error),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900121 ParseMaxOpenFiles(ParseIntError),
Lepton Wu39133a02019-02-27 12:42:29 -0800122 PivotRootDoesntExist(&'static str),
Jakub Starona3411ea2019-04-24 10:55:25 -0700123 PmemDeviceImageTooBig,
124 PmemDeviceNew(sys_util::Error),
Zach Reizner5bed0d22018-03-28 02:31:11 -0700125 PollContextAdd(sys_util::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700126 PollContextDelete(sys_util::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700127 ReadLowmemAvailable(io::Error),
128 ReadLowmemMargin(io::Error),
Dylan Reid0f579cb2018-07-09 15:39:34 -0700129 RegisterBalloon(arch::DeviceRegistrationError),
130 RegisterBlock(arch::DeviceRegistrationError),
131 RegisterGpu(arch::DeviceRegistrationError),
132 RegisterNet(arch::DeviceRegistrationError),
133 RegisterP9(arch::DeviceRegistrationError),
134 RegisterRng(arch::DeviceRegistrationError),
Mark Ryan6ed5aea2018-04-20 13:52:35 +0100135 RegisterSignalHandler(sys_util::Error),
Dylan Reid0f579cb2018-07-09 15:39:34 -0700136 RegisterWayland(arch::DeviceRegistrationError),
Lepton Wu60893882018-11-21 11:06:18 -0800137 ReserveGpuMemory(sys_util::MmapError),
138 ReserveMemory(sys_util::Error),
Jakub Starona3411ea2019-04-24 10:55:25 -0700139 ReservePmemMemory(sys_util::MmapError),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700140 ResetTimerFd(sys_util::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800141 RngDeviceNew(virtio::RngError),
Zach Reizner8fb52112017-12-13 16:04:39 -0800142 SettingGidMap(io_jail::Error),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900143 SettingMaxOpenFiles(io_jail::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800144 SettingUidMap(io_jail::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800145 SignalFd(sys_util::SignalFdError),
146 SpawnVcpu(io::Error),
Chirantan Ekbote448516e2018-07-24 16:07:42 -0700147 TimerFd(sys_util::Error),
Chirantan Ekbote2d292332018-11-16 11:35:24 -0800148 ValidateRawFd(sys_util::Error),
David Tolnay2b089fc2019-03-04 15:33:22 -0800149 VhostNetDeviceNew(virtio::vhost::Error),
150 VhostVsockDeviceNew(virtio::vhost::Error),
Daniel Verkamp56f283b2018-10-05 11:40:59 -0700151 VirtioPciDev(sys_util::Error),
Zach Reizner8fb52112017-12-13 16:04:39 -0800152 WaylandDeviceNew(sys_util::Error),
Zach Reizner39aa26b2017-12-12 18:03:23 -0800153}
154
David Tolnayc69f9752019-03-01 18:07:56 -0800155impl Display for Error {
David Tolnay3df35522019-03-11 12:36:30 -0700156 #[remain::check]
Zach Reizner39aa26b2017-12-12 18:03:23 -0800157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnayc69f9752019-03-01 18:07:56 -0800158 use self::Error::*;
159
David Tolnay3df35522019-03-11 12:36:30 -0700160 #[sorted]
Zach Reizner39aa26b2017-12-12 18:03:23 -0800161 match self {
Lepton Wu60893882018-11-21 11:06:18 -0800162 AddGpuDeviceMemory(e) => write!(f, "failed to add gpu device memory: {}", e),
Jakub Starona3411ea2019-04-24 10:55:25 -0700163 AddPmemDeviceMemory(e) => write!(f, "failed to add pmem device memory: {}", e),
Lepton Wu60893882018-11-21 11:06:18 -0800164 AllocateGpuDeviceAddress => write!(f, "failed to allocate gpu device guest address"),
Jakub Starona3411ea2019-04-24 10:55:25 -0700165 AllocatePmemDeviceAddress(e) => {
166 write!(f, "failed to allocate memory for pmem device: {}", e)
167 }
David Tolnayc69f9752019-03-01 18:07:56 -0800168 BalloonDeviceNew(e) => write!(f, "failed to create balloon: {}", e),
169 BlockDeviceNew(e) => write!(f, "failed to create block device: {}", e),
170 BlockSignal(e) => write!(f, "failed to block signal: {}", e),
David Tolnaybe034262019-03-04 17:48:36 -0800171 BuildVm(e) => write!(f, "The architecture failed to build the vm: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800172 ChownTpmStorage(e) => write!(f, "failed to chown tpm storage: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800173 CloneEventFd(e) => write!(f, "failed to clone eventfd: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800174 CreateCrasClient(e) => write!(f, "failed to create cras client: {}", e),
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700175 CreateDiskError(e) => write!(f, "failed to create virtual disk: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800176 CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e),
177 CreatePollContext(e) => write!(f, "failed to create poll context: {}", e),
178 CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e),
179 CreateSocket(e) => write!(f, "failed to create socket: {}", e),
180 CreateTapDevice(e) => write!(f, "failed to create tap device: {}", e),
181 CreateTimerFd(e) => write!(f, "failed to create timerfd: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800182 CreateTpmStorage(p, e) => {
183 write!(f, "failed to create tpm storage dir {}: {}", p.display(), e)
184 }
Jingkui Wang100e6e42019-03-08 20:41:57 -0800185 CreateUsbProvider(e) => write!(f, "failed to create usb provider: {}", e),
Xiong Zhang17b0daf2019-04-23 17:14:50 +0800186 CreateVfioDevice(e) => write!(f, "Failed to create vfio device {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800187 DeviceJail(e) => write!(f, "failed to jail device: {}", e),
188 DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e),
189 Disk(e) => write!(f, "failed to load disk image: {}", e),
190 DiskImageLock(e) => write!(f, "failed to lock disk image: {}", e),
Dmitry Torokhov71006072019-03-06 10:56:51 -0800191 DropCapabilities(e) => write!(f, "failed to drop process capabilities: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900192 FsDeviceNew(e) => write!(f, "failed to create fs device: {}", e),
193 GetMaxOpenFiles(e) => write!(f, "failed to get max number of open files: {}", e),
David Tolnay64cd5ea2019-04-15 15:56:35 -0700194 InputDeviceNew(e) => write!(f, "failed to set up input device: {}", e),
195 InputEventsOpen(e) => write!(f, "failed to open event device: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800196 InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"),
197 InvalidWaylandPath => write!(f, "wayland socket path has no parent or file name"),
David Tolnayfd0971d2019-03-04 17:15:57 -0800198 IoJail(e) => write!(f, "{}", e),
Lepton Wu39133a02019-02-27 12:42:29 -0800199 LoadKernel(e) => write!(f, "failed to load kernel: {}", e),
Daniel Verkamp6a847062019-11-26 13:16:35 -0800200 MemoryTooLarge => write!(f, "requested memory size too large"),
David Tolnayc69f9752019-03-01 18:07:56 -0800201 NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800202 OpenAndroidFstab(p, e) => write!(
David Tolnayb4bd00f2019-02-12 17:51:26 -0800203 f,
204 "failed to open android fstab file {}: {}",
205 p.display(),
206 e
207 ),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -0700208 OpenBios(p, e) => write!(f, "failed to open bios {}: {}", p.display(), e),
David Tolnay3df35522019-03-11 12:36:30 -0700209 OpenInitrd(p, e) => write!(f, "failed to open initrd {}: {}", p.display(), e),
210 OpenKernel(p, e) => write!(f, "failed to open kernel image {}: {}", p.display(), e),
David Tolnayfd0971d2019-03-04 17:15:57 -0800211 OpenVinput(p, e) => write!(f, "failed to open vinput device {}: {}", p.display(), e),
David Tolnayc69f9752019-03-01 18:07:56 -0800212 P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900213 ParseMaxOpenFiles(e) => write!(f, "failed to parse max number of open files: {}", e),
Lepton Wu39133a02019-02-27 12:42:29 -0800214 PivotRootDoesntExist(p) => write!(f, "{} doesn't exist, can't jail devices.", p),
Jakub Starona3411ea2019-04-24 10:55:25 -0700215 PmemDeviceImageTooBig => {
216 write!(f, "failed to create pmem device: pmem device image too big")
217 }
218 PmemDeviceNew(e) => write!(f, "failed to create pmem device: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800219 PollContextAdd(e) => write!(f, "failed to add fd to poll context: {}", e),
220 PollContextDelete(e) => write!(f, "failed to remove fd from poll context: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800221 ReadLowmemAvailable(e) => write!(
Zach Reizner55a9e502018-10-03 10:22:32 -0700222 f,
223 "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}",
224 e
225 ),
David Tolnayc69f9752019-03-01 18:07:56 -0800226 ReadLowmemMargin(e) => write!(
Zach Reizner55a9e502018-10-03 10:22:32 -0700227 f,
228 "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}",
229 e
230 ),
David Tolnayc69f9752019-03-01 18:07:56 -0800231 RegisterBalloon(e) => write!(f, "error registering balloon device: {}", e),
232 RegisterBlock(e) => write!(f, "error registering block device: {}", e),
233 RegisterGpu(e) => write!(f, "error registering gpu device: {}", e),
234 RegisterNet(e) => write!(f, "error registering net device: {}", e),
235 RegisterP9(e) => write!(f, "error registering 9p device: {}", e),
236 RegisterRng(e) => write!(f, "error registering rng device: {}", e),
237 RegisterSignalHandler(e) => write!(f, "error registering signal handler: {}", e),
238 RegisterWayland(e) => write!(f, "error registering wayland device: {}", e),
Lepton Wu60893882018-11-21 11:06:18 -0800239 ReserveGpuMemory(e) => write!(f, "failed to reserve gpu memory: {}", e),
240 ReserveMemory(e) => write!(f, "failed to reserve memory: {}", e),
Jakub Starona3411ea2019-04-24 10:55:25 -0700241 ReservePmemMemory(e) => write!(f, "failed to reserve pmem memory: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800242 ResetTimerFd(e) => write!(f, "failed to reset timerfd: {}", e),
243 RngDeviceNew(e) => write!(f, "failed to set up rng: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800244 SettingGidMap(e) => write!(f, "error setting GID map: {}", e),
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900245 SettingMaxOpenFiles(e) => write!(f, "error setting max open files: {}", e),
David Tolnayc69f9752019-03-01 18:07:56 -0800246 SettingUidMap(e) => write!(f, "error setting UID map: {}", e),
247 SignalFd(e) => write!(f, "failed to read signal fd: {}", e),
248 SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e),
249 TimerFd(e) => write!(f, "failed to read timer fd: {}", e),
250 ValidateRawFd(e) => write!(f, "failed to validate raw fd: {}", e),
251 VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {}", e),
252 VhostVsockDeviceNew(e) => write!(f, "failed to set up virtual socket device: {}", e),
253 VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e),
254 WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {}", e),
Zach Reizner39aa26b2017-12-12 18:03:23 -0800255 }
256 }
257}
258
David Tolnayfd0971d2019-03-04 17:15:57 -0800259impl From<io_jail::Error> for Error {
260 fn from(err: io_jail::Error) -> Self {
261 Error::IoJail(err)
262 }
263}
264
David Tolnayc69f9752019-03-01 18:07:56 -0800265impl std::error::Error for Error {}
Dylan Reid059a1882018-07-23 17:58:09 -0700266
Zach Reizner39aa26b2017-12-12 18:03:23 -0800267type Result<T> = std::result::Result<T, Error>;
268
Jakub Starond99cd0a2019-04-11 14:09:39 -0700269enum TaggedControlSocket {
270 Vm(VmControlResponseSocket),
Gurchetan Singh53edb812019-05-22 08:57:16 -0700271 VmMemory(VmMemoryControlResponseSocket),
Xiong Zhang2515b752019-09-19 10:29:02 +0800272 VmIrq(VmIrqResponseSocket),
Jakub Starond99cd0a2019-04-11 14:09:39 -0700273}
274
275impl AsRef<UnixSeqpacket> for TaggedControlSocket {
276 fn as_ref(&self) -> &UnixSeqpacket {
277 use self::TaggedControlSocket::*;
278 match &self {
279 Vm(ref socket) => socket,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700280 VmMemory(ref socket) => socket,
Xiong Zhang2515b752019-09-19 10:29:02 +0800281 VmIrq(ref socket) => socket,
Jakub Starond99cd0a2019-04-11 14:09:39 -0700282 }
283 }
284}
285
286impl AsRawFd for TaggedControlSocket {
287 fn as_raw_fd(&self) -> RawFd {
288 self.as_ref().as_raw_fd()
289 }
290}
291
Chirantan Ekbote220605a2019-11-14 18:36:06 +0900292fn get_max_open_files() -> Result<libc::rlim64_t> {
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900293 let mut buf = String::with_capacity(32);
294 File::open("/proc/sys/fs/file-max")
295 .and_then(|mut f| f.read_to_string(&mut buf))
296 .map_err(Error::GetMaxOpenFiles)?;
297
298 Ok(buf.trim().parse().map_err(Error::ParseMaxOpenFiles)?)
299}
300
Zach Reizner44863792019-06-26 14:22:08 -0700301fn create_base_minijail(
302 root: &Path,
303 log_failures: bool,
304 seccomp_policy: &Path,
305) -> Result<Minijail> {
Zach Reizner39aa26b2017-12-12 18:03:23 -0800306 // All child jails run in a new user namespace without any users mapped,
307 // they run as nobody unless otherwise configured.
David Tolnay5bbbf612018-12-01 17:49:30 -0800308 let mut j = Minijail::new().map_err(Error::DeviceJail)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800309 j.namespace_pids();
310 j.namespace_user();
311 j.namespace_user_disable_setgroups();
312 // Don't need any capabilities.
313 j.use_caps(0);
314 // Create a new mount namespace with an empty root FS.
315 j.namespace_vfs();
David Tolnay5bbbf612018-12-01 17:49:30 -0800316 j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800317 // Run in an empty network namespace.
318 j.namespace_net();
Chirantan Ekbote1a5fe952019-11-27 17:38:54 +0900319 // Most devices don't need to open many fds.
320 j.set_rlimit(libc::RLIMIT_NOFILE, 1024, 1024)
321 .map_err(Error::SettingMaxOpenFiles)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800322 // Apply the block device seccomp policy.
323 j.no_new_privs();
Stephen Barber3b1d8a52018-01-06 17:34:51 -0800324 // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill
325 // the entire device process if a worker thread commits a seccomp violation.
326 j.set_seccomp_filter_tsync();
Zach Reizner44863792019-06-26 14:22:08 -0700327 if log_failures {
328 j.log_seccomp_filter_failures();
329 }
Zach Reizner39aa26b2017-12-12 18:03:23 -0800330 j.parse_seccomp_filters(seccomp_policy)
David Tolnay5bbbf612018-12-01 17:49:30 -0800331 .map_err(Error::DeviceJail)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -0800332 j.use_seccomp_filter();
333 // Don't do init setup.
334 j.run_as_init();
335 Ok(j)
336}
337
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800338fn simple_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> {
Lepton Wu9105e9f2019-03-14 11:38:31 -0700339 if cfg.sandbox {
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800340 let pivot_root: &str = option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty");
341 // A directory for a jailed device's pivot root.
342 let root_path = Path::new(pivot_root);
343 if !root_path.exists() {
344 return Err(Error::PivotRootDoesntExist(pivot_root));
345 }
346 let policy_path: PathBuf = cfg.seccomp_policy_dir.join(policy);
Zach Reizner44863792019-06-26 14:22:08 -0700347 Ok(Some(create_base_minijail(
348 root_path,
349 cfg.seccomp_log_failures,
350 &policy_path,
351 )?))
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800352 } else {
353 Ok(None)
354 }
355}
356
David Tolnayfd0971d2019-03-04 17:15:57 -0800357type DeviceResult<T = VirtioDeviceStub> = std::result::Result<T, Error>;
David Tolnay2b089fc2019-03-04 15:33:22 -0800358
359fn create_block_device(
360 cfg: &Config,
361 disk: &DiskOption,
Jakub Staronecf81e02019-04-11 11:43:39 -0700362 disk_device_socket: DiskControlResponseSocket,
David Tolnay2b089fc2019-03-04 15:33:22 -0800363) -> DeviceResult {
364 // Special case '/proc/self/fd/*' paths. The FD is already open, just use it.
365 let raw_image: File = if disk.path.parent() == Some(Path::new("/proc/self/fd")) {
366 // Safe because we will validate |raw_fd|.
367 unsafe { File::from_raw_fd(raw_fd_from_path(&disk.path)?) }
368 } else {
369 OpenOptions::new()
370 .read(true)
371 .write(!disk.read_only)
372 .open(&disk.path)
373 .map_err(Error::Disk)?
374 };
375 // Lock the disk image to prevent other crosvm instances from using it.
376 let lock_op = if disk.read_only {
377 FlockOperation::LockShared
378 } else {
379 FlockOperation::LockExclusive
380 };
381 flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?;
382
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700383 let disk_file = disk::create_disk_file(raw_image).map_err(Error::CreateDiskError)?;
Daniel Verkampe73c80f2019-11-08 10:11:16 -0800384 let dev = virtio::Block::new(
385 disk_file,
386 disk.read_only,
387 disk.sparse,
388 Some(disk_device_socket),
389 )
390 .map_err(Error::BlockDeviceNew)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800391
392 Ok(VirtioDeviceStub {
Cody Schuffelen7d533e52019-07-02 16:54:05 -0700393 dev: Box::new(dev),
David Tolnay2b089fc2019-03-04 15:33:22 -0800394 jail: simple_jail(&cfg, "block_device.policy")?,
395 })
396}
397
398fn create_rng_device(cfg: &Config) -> DeviceResult {
399 let dev = virtio::Rng::new().map_err(Error::RngDeviceNew)?;
400
401 Ok(VirtioDeviceStub {
402 dev: Box::new(dev),
403 jail: simple_jail(&cfg, "rng_device.policy")?,
404 })
405}
406
407#[cfg(feature = "tpm")]
408fn create_tpm_device(cfg: &Config) -> DeviceResult {
409 use std::ffi::CString;
410 use std::fs;
411 use std::process;
412 use sys_util::chown;
413
414 let tpm_storage: PathBuf;
415 let mut tpm_jail = simple_jail(&cfg, "tpm_device.policy")?;
416
417 match &mut tpm_jail {
418 Some(jail) => {
419 // Create a tmpfs in the device's root directory for tpm
420 // simulator storage. The size is 20*1024, or 20 KB.
421 jail.mount_with_data(
422 Path::new("none"),
423 Path::new("/"),
424 "tmpfs",
425 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
426 "size=20480",
427 )?;
428
429 let crosvm_ids = add_crosvm_user_to_jail(jail, "tpm")?;
430
431 let pid = process::id();
432 let tpm_pid_dir = format!("/run/vm/tpm.{}", pid);
433 tpm_storage = Path::new(&tpm_pid_dir).to_owned();
David Tolnayfd0971d2019-03-04 17:15:57 -0800434 fs::create_dir_all(&tpm_storage)
435 .map_err(|e| Error::CreateTpmStorage(tpm_storage.to_owned(), e))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800436 let tpm_pid_dir_c = CString::new(tpm_pid_dir).expect("no nul bytes");
David Tolnayfd0971d2019-03-04 17:15:57 -0800437 chown(&tpm_pid_dir_c, crosvm_ids.uid, crosvm_ids.gid)
438 .map_err(Error::ChownTpmStorage)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800439
440 jail.mount_bind(&tpm_storage, &tpm_storage, true)?;
441 }
442 None => {
443 // Path used inside cros_sdk which does not have /run/vm.
444 tpm_storage = Path::new("/tmp/tpm-simulator").to_owned();
445 }
446 }
447
448 let dev = virtio::Tpm::new(tpm_storage);
449
450 Ok(VirtioDeviceStub {
451 dev: Box::new(dev),
452 jail: tpm_jail,
453 })
454}
455
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800456fn create_single_touch_device(cfg: &Config, single_touch_spec: &TouchDeviceOption) -> DeviceResult {
457 let socket = create_input_socket(&single_touch_spec.path).map_err(|e| {
458 error!("failed configuring virtio single touch: {:?}", e);
459 e
460 })?;
461
462 let dev = virtio::new_single_touch(socket, single_touch_spec.width, single_touch_spec.height)
463 .map_err(Error::InputDeviceNew)?;
464 Ok(VirtioDeviceStub {
465 dev: Box::new(dev),
466 jail: simple_jail(&cfg, "input_device.policy")?,
467 })
468}
469
470fn create_trackpad_device(cfg: &Config, trackpad_spec: &TouchDeviceOption) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800471 let socket = create_input_socket(&trackpad_spec.path).map_err(|e| {
472 error!("failed configuring virtio trackpad: {}", e);
473 e
474 })?;
475
476 let dev = virtio::new_trackpad(socket, trackpad_spec.width, trackpad_spec.height)
477 .map_err(Error::InputDeviceNew)?;
478
479 Ok(VirtioDeviceStub {
480 dev: Box::new(dev),
481 jail: simple_jail(&cfg, "input_device.policy")?,
482 })
483}
484
485fn create_mouse_device(cfg: &Config, mouse_socket: &Path) -> DeviceResult {
486 let socket = create_input_socket(&mouse_socket).map_err(|e| {
487 error!("failed configuring virtio mouse: {}", e);
488 e
489 })?;
490
491 let dev = virtio::new_mouse(socket).map_err(Error::InputDeviceNew)?;
492
493 Ok(VirtioDeviceStub {
494 dev: Box::new(dev),
495 jail: simple_jail(&cfg, "input_device.policy")?,
496 })
497}
498
499fn create_keyboard_device(cfg: &Config, keyboard_socket: &Path) -> DeviceResult {
500 let socket = create_input_socket(&keyboard_socket).map_err(|e| {
501 error!("failed configuring virtio keyboard: {}", e);
502 e
503 })?;
504
505 let dev = virtio::new_keyboard(socket).map_err(Error::InputDeviceNew)?;
506
507 Ok(VirtioDeviceStub {
508 dev: Box::new(dev),
509 jail: simple_jail(&cfg, "input_device.policy")?,
510 })
511}
512
513fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult {
514 let dev_file = OpenOptions::new()
515 .read(true)
516 .write(true)
517 .open(dev_path)
David Tolnayfd0971d2019-03-04 17:15:57 -0800518 .map_err(|e| Error::OpenVinput(dev_path.to_owned(), e))?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800519
520 let dev = virtio::new_evdev(dev_file).map_err(Error::InputDeviceNew)?;
521
522 Ok(VirtioDeviceStub {
523 dev: Box::new(dev),
524 jail: simple_jail(&cfg, "input_device.policy")?,
525 })
526}
527
Jakub Staron1f828d72019-04-11 12:49:29 -0700528fn create_balloon_device(cfg: &Config, socket: BalloonControlResponseSocket) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800529 let dev = virtio::Balloon::new(socket).map_err(Error::BalloonDeviceNew)?;
530
531 Ok(VirtioDeviceStub {
532 dev: Box::new(dev),
533 jail: simple_jail(&cfg, "balloon_device.policy")?,
534 })
535}
536
537fn create_tap_net_device(cfg: &Config, tap_fd: RawFd) -> DeviceResult {
538 // Safe because we ensure that we get a unique handle to the fd.
539 let tap = unsafe {
540 Tap::from_raw_fd(validate_raw_fd(tap_fd).map_err(Error::ValidateRawFd)?)
541 .map_err(Error::CreateTapDevice)?
542 };
543
544 let dev = virtio::Net::from(tap).map_err(Error::NetDeviceNew)?;
545
546 Ok(VirtioDeviceStub {
547 dev: Box::new(dev),
548 jail: simple_jail(&cfg, "net_device.policy")?,
549 })
550}
551
552fn create_net_device(
553 cfg: &Config,
554 host_ip: Ipv4Addr,
555 netmask: Ipv4Addr,
556 mac_address: MacAddress,
557 mem: &GuestMemory,
558) -> DeviceResult {
559 let dev = if cfg.vhost_net {
560 let dev =
561 virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, netmask, mac_address, mem)
562 .map_err(Error::VhostNetDeviceNew)?;
David Tolnayfdac5ed2019-03-08 16:56:14 -0800563 Box::new(dev) as Box<dyn VirtioDevice>
David Tolnay2b089fc2019-03-04 15:33:22 -0800564 } else {
565 let dev =
566 virtio::Net::<Tap>::new(host_ip, netmask, mac_address).map_err(Error::NetDeviceNew)?;
David Tolnayfdac5ed2019-03-08 16:56:14 -0800567 Box::new(dev) as Box<dyn VirtioDevice>
David Tolnay2b089fc2019-03-04 15:33:22 -0800568 };
569
570 let policy = if cfg.vhost_net {
571 "vhost_net_device.policy"
572 } else {
573 "net_device.policy"
574 };
575
576 Ok(VirtioDeviceStub {
577 dev,
578 jail: simple_jail(&cfg, policy)?,
579 })
580}
581
582#[cfg(feature = "gpu")]
583fn create_gpu_device(
584 cfg: &Config,
585 exit_evt: &EventFd,
Gurchetan Singh7ec58fa2019-05-15 15:30:38 -0700586 gpu_device_socket: VmMemoryControlRequestSocket,
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900587 gpu_sockets: Vec<virtio::resource_bridge::ResourceResponseSocket>,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700588 wayland_socket_path: Option<PathBuf>,
589 x_display: Option<String>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800590) -> DeviceResult {
591 let jailed_wayland_path = Path::new("/wayland-0");
592
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700593 let mut display_backends = vec![
594 virtio::DisplayBackend::X(x_display),
595 virtio::DisplayBackend::Null,
596 ];
597
598 if let Some(socket_path) = wayland_socket_path.as_ref() {
599 display_backends.insert(
600 0,
601 virtio::DisplayBackend::Wayland(if cfg.sandbox {
602 Some(jailed_wayland_path.to_owned())
603 } else {
604 Some(socket_path.to_owned())
605 }),
606 );
607 }
608
David Tolnay2b089fc2019-03-04 15:33:22 -0800609 let dev = virtio::Gpu::new(
610 exit_evt.try_clone().map_err(Error::CloneEventFd)?,
Gurchetan Singh7ec58fa2019-05-15 15:30:38 -0700611 Some(gpu_device_socket),
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700612 NonZeroU8::new(1).unwrap(), // number of scanouts
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900613 gpu_sockets,
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700614 display_backends,
David Tolnay2b089fc2019-03-04 15:33:22 -0800615 );
616
617 let jail = match simple_jail(&cfg, "gpu_device.policy")? {
618 Some(mut jail) => {
619 // Create a tmpfs in the device's root directory so that we can bind mount the
620 // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
621 jail.mount_with_data(
622 Path::new("none"),
623 Path::new("/"),
624 "tmpfs",
625 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
626 "size=67108864",
David Tolnayfd0971d2019-03-04 17:15:57 -0800627 )?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800628
629 // Device nodes required for DRM.
630 let sys_dev_char_path = Path::new("/sys/dev/char");
David Tolnayfd0971d2019-03-04 17:15:57 -0800631 jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800632 let sys_devices_path = Path::new("/sys/devices");
David Tolnayfd0971d2019-03-04 17:15:57 -0800633 jail.mount_bind(sys_devices_path, sys_devices_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800634 let drm_dri_path = Path::new("/dev/dri");
David Tolnayfd0971d2019-03-04 17:15:57 -0800635 jail.mount_bind(drm_dri_path, drm_dri_path, false)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800636
David Riley06787c52019-07-24 12:09:07 -0700637 // If the ARM specific devices exist on the host, bind mount them in.
638 let mali0_path = Path::new("/dev/mali0");
639 if mali0_path.exists() {
640 jail.mount_bind(mali0_path, mali0_path, true)?;
641 }
642
643 let pvr_sync_path = Path::new("/dev/pvr_sync");
644 if pvr_sync_path.exists() {
645 jail.mount_bind(pvr_sync_path, pvr_sync_path, true)?;
646 }
647
David Tolnay2b089fc2019-03-04 15:33:22 -0800648 // Libraries that are required when mesa drivers are dynamically loaded.
David Riley06787c52019-07-24 12:09:07 -0700649 let lib_dirs = &["/usr/lib", "/usr/lib64", "/lib", "/lib64"];
650 for dir in lib_dirs {
651 let dir_path = Path::new(dir);
652 if dir_path.exists() {
653 jail.mount_bind(dir_path, dir_path, false)?;
654 }
655 }
David Tolnay2b089fc2019-03-04 15:33:22 -0800656
657 // Bind mount the wayland socket into jail's root. This is necessary since each
658 // new wayland context must open() the socket.
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700659 if let Some(path) = wayland_socket_path {
660 jail.mount_bind(path.as_ref(), jailed_wayland_path, true)?;
661 }
David Tolnay2b089fc2019-03-04 15:33:22 -0800662
663 add_crosvm_user_to_jail(&mut jail, "gpu")?;
664
David Riley54e660b2019-07-24 17:22:50 -0700665 // pvr driver requires read access to /proc/self/task/*/comm.
666 let proc_path = Path::new("/proc");
667 jail.mount(
668 proc_path,
669 proc_path,
670 "proc",
671 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RDONLY) as usize,
672 )?;
673
David Tolnay2b089fc2019-03-04 15:33:22 -0800674 Some(jail)
675 }
676 None => None,
677 };
678
679 Ok(VirtioDeviceStub {
680 dev: Box::new(dev),
681 jail,
682 })
683}
684
685fn create_wayland_device(
686 cfg: &Config,
687 socket_path: &Path,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700688 socket: VmMemoryControlRequestSocket,
David Tolnay2b089fc2019-03-04 15:33:22 -0800689 resource_bridge: Option<virtio::resource_bridge::ResourceRequestSocket>,
690) -> DeviceResult {
691 let wayland_socket_dir = socket_path.parent().ok_or(Error::InvalidWaylandPath)?;
692 let wayland_socket_name = socket_path.file_name().ok_or(Error::InvalidWaylandPath)?;
693 let jailed_wayland_dir = Path::new("/wayland");
694 let jailed_wayland_path = jailed_wayland_dir.join(wayland_socket_name);
695
696 let dev = virtio::Wl::new(
Lepton Wu9105e9f2019-03-14 11:38:31 -0700697 if cfg.sandbox {
David Tolnay2b089fc2019-03-04 15:33:22 -0800698 &jailed_wayland_path
699 } else {
700 socket_path
701 },
702 socket,
703 resource_bridge,
704 )
705 .map_err(Error::WaylandDeviceNew)?;
706
707 let jail = match simple_jail(&cfg, "wl_device.policy")? {
708 Some(mut jail) => {
709 // Create a tmpfs in the device's root directory so that we can bind mount the wayland
710 // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB.
711 jail.mount_with_data(
712 Path::new("none"),
713 Path::new("/"),
714 "tmpfs",
715 (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize,
716 "size=67108864",
David Tolnayfd0971d2019-03-04 17:15:57 -0800717 )?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800718
719 // Bind mount the wayland socket's directory into jail's root. This is necessary since
720 // each new wayland context must open() the socket. If the wayland socket is ever
721 // destroyed and remade in the same host directory, new connections will be possible
722 // without restarting the wayland device.
David Tolnayfd0971d2019-03-04 17:15:57 -0800723 jail.mount_bind(wayland_socket_dir, jailed_wayland_dir, true)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800724
725 add_crosvm_user_to_jail(&mut jail, "Wayland")?;
726
727 Some(jail)
728 }
729 None => None,
730 };
731
732 Ok(VirtioDeviceStub {
733 dev: Box::new(dev),
734 jail,
735 })
736}
737
738fn create_vhost_vsock_device(cfg: &Config, cid: u64, mem: &GuestMemory) -> DeviceResult {
739 let dev = virtio::vhost::Vsock::new(cid, mem).map_err(Error::VhostVsockDeviceNew)?;
740
741 Ok(VirtioDeviceStub {
742 dev: Box::new(dev),
743 jail: simple_jail(&cfg, "vhost_vsock_device.policy")?,
744 })
745}
746
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900747fn create_fs_device(
748 cfg: &Config,
749 uid_map: &str,
750 gid_map: &str,
751 src: &Path,
752 tag: &str,
753 fs_cfg: virtio::fs::passthrough::Config,
754) -> DeviceResult {
755 let mut j = Minijail::new().map_err(Error::DeviceJail)?;
756
757 if cfg.sandbox {
758 j.namespace_pids();
759 j.namespace_user();
760 j.namespace_user_disable_setgroups();
761 j.uidmap(uid_map).map_err(Error::SettingUidMap)?;
762 j.gidmap(gid_map).map_err(Error::SettingGidMap)?;
763
764 // Run in an empty network namespace.
765 j.namespace_net();
766
767 j.no_new_privs();
768
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900769 // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, which will correctly kill
770 // the entire device process if a worker thread commits a seccomp violation.
Chirantan Ekboteb0ac0072019-11-14 18:45:56 +0900771 let seccomp_policy = cfg.seccomp_policy_dir.join("fs_device.policy");
772 j.set_seccomp_filter_tsync();
773 if cfg.seccomp_log_failures {
774 j.log_seccomp_filter_failures();
775 }
776 j.parse_seccomp_filters(&seccomp_policy)
777 .map_err(Error::DeviceJail)?;
778 j.use_seccomp_filter();
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +0900779
780 // Don't do init setup.
781 j.run_as_init();
782 }
783
784 // Create a new mount namespace with the source directory as the root. We need this even when
785 // sandboxing is disabled as the server relies on the host kernel to prevent path traversals
786 // from leaking out of the shared directory.
787 j.namespace_vfs();
788 j.enter_pivot_root(src).map_err(Error::DevicePivotRoot)?;
789
790 // The file server opens a lot of fds and needs a really high open file limit.
791 let max_open_files = get_max_open_files()?;
792 j.set_rlimit(libc::RLIMIT_NOFILE, max_open_files, max_open_files)
793 .map_err(Error::SettingMaxOpenFiles)?;
794
795 // TODO(chirantan): Use more than one worker once the kernel driver has been fixed to not panic
796 // when num_queues > 1.
797 let dev = virtio::fs::Fs::new(tag, 1, fs_cfg).map_err(Error::FsDeviceNew)?;
798
799 Ok(VirtioDeviceStub {
800 dev: Box::new(dev),
801 jail: Some(j),
802 })
803}
804
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +0900805fn create_9p_device(cfg: &Config, src: &Path, tag: &str) -> DeviceResult {
David Tolnay2b089fc2019-03-04 15:33:22 -0800806 let (jail, root) = match simple_jail(&cfg, "9p_device.policy")? {
807 Some(mut jail) => {
808 // The shared directory becomes the root of the device's file system.
809 let root = Path::new("/");
David Tolnayfd0971d2019-03-04 17:15:57 -0800810 jail.mount_bind(src, root, true)?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800811
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +0900812 add_crosvm_user_to_jail(&mut jail, "p9")?;
David Tolnay2b089fc2019-03-04 15:33:22 -0800813 (Some(jail), root)
814 }
815 None => {
816 // There's no bind mount so we tell the server to treat the source directory as the
David Tolnay9deb7d72019-03-05 18:25:44 -0800817 // root.
David Tolnay2b089fc2019-03-04 15:33:22 -0800818 (None, src)
819 }
820 };
821
822 let dev = virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?;
823
824 Ok(VirtioDeviceStub {
825 dev: Box::new(dev),
826 jail,
827 })
828}
829
Jakub Starona3411ea2019-04-24 10:55:25 -0700830fn create_pmem_device(
831 cfg: &Config,
832 vm: &mut Vm,
833 resources: &mut SystemAllocator,
834 disk: &DiskOption,
835 index: usize,
836) -> DeviceResult {
837 let fd = OpenOptions::new()
838 .read(true)
839 .write(!disk.read_only)
840 .open(&disk.path)
841 .map_err(Error::Disk)?;
842
843 let image_size = {
844 let metadata = std::fs::metadata(&disk.path).map_err(Error::Disk)?;
845 metadata.len()
846 };
847
848 let protection = {
849 if disk.read_only {
850 Protection::read()
851 } else {
852 Protection::read_write()
853 }
854 };
855
856 let memory_mapping = {
857 // Conversion from u64 to usize may fail on 32bit system.
858 let image_size = usize::try_from(image_size).map_err(|_| Error::PmemDeviceImageTooBig)?;
859
860 MemoryMapping::from_fd_offset_protection(&fd, image_size, 0, protection)
861 .map_err(Error::ReservePmemMemory)?
862 };
863
864 let mapping_address = resources
Xiong Zhang383b3b52019-10-30 14:59:26 +0800865 .mmio_allocator(MmioType::High)
Jakub Starona3411ea2019-04-24 10:55:25 -0700866 .allocate_with_align(
867 image_size,
868 Alloc::PmemDevice(index),
869 format!("pmem_disk_image_{}", index),
870 // Linux kernel requires pmem namespaces to be 128 MiB aligned.
871 128 * 1024 * 1024, /* 128 MiB */
872 )
873 .map_err(Error::AllocatePmemDeviceAddress)?;
874
Xiong Zhang383b3b52019-10-30 14:59:26 +0800875 vm.add_mmio_memory(
Jakub Starona3411ea2019-04-24 10:55:25 -0700876 GuestAddress(mapping_address),
877 memory_mapping,
878 /* read_only = */ disk.read_only,
879 /* log_dirty_pages = */ false,
880 )
881 .map_err(Error::AddPmemDeviceMemory)?;
882
883 let dev = virtio::Pmem::new(fd, GuestAddress(mapping_address), image_size)
884 .map_err(Error::PmemDeviceNew)?;
885
886 Ok(VirtioDeviceStub {
887 dev: Box::new(dev) as Box<dyn VirtioDevice>,
Jakub Staroncc91fc82019-06-10 14:00:07 -0700888 jail: simple_jail(&cfg, "pmem_device.policy")?,
Jakub Starona3411ea2019-04-24 10:55:25 -0700889 })
890}
891
Dmitry Torokhovee42b8c2019-05-27 11:14:20 -0700892// gpu_device_socket is not used when GPU support is disabled.
893#[cfg_attr(not(feature = "gpu"), allow(unused_variables))]
David Tolnay2b089fc2019-03-04 15:33:22 -0800894fn create_virtio_devices(
895 cfg: &Config,
Zach Reizner55a9e502018-10-03 10:22:32 -0700896 mem: &GuestMemory,
Jakub Starona3411ea2019-04-24 10:55:25 -0700897 vm: &mut Vm,
898 resources: &mut SystemAllocator,
Zach Reizner55a9e502018-10-03 10:22:32 -0700899 _exit_evt: &EventFd,
Gurchetan Singh53edb812019-05-22 08:57:16 -0700900 wayland_device_socket: VmMemoryControlRequestSocket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -0700901 gpu_device_socket: VmMemoryControlRequestSocket,
Jakub Staron1f828d72019-04-11 12:49:29 -0700902 balloon_device_socket: BalloonControlResponseSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -0700903 disk_device_sockets: &mut Vec<DiskControlResponseSocket>,
David Tolnay2b089fc2019-03-04 15:33:22 -0800904) -> DeviceResult<Vec<VirtioDeviceStub>> {
Dylan Reid059a1882018-07-23 17:58:09 -0700905 let mut devs = Vec::new();
Zach Reizner39aa26b2017-12-12 18:03:23 -0800906
Zach Reizner8fb52112017-12-13 16:04:39 -0800907 for disk in &cfg.disks {
Daniel Verkamp92f73d72018-12-04 13:17:46 -0800908 let disk_device_socket = disk_device_sockets.remove(0);
David Tolnay2b089fc2019-03-04 15:33:22 -0800909 devs.push(create_block_device(cfg, disk, disk_device_socket)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800910 }
911
Jakub Starona3411ea2019-04-24 10:55:25 -0700912 for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() {
913 devs.push(create_pmem_device(cfg, vm, resources, pmem_disk, index)?);
914 }
915
David Tolnay2b089fc2019-03-04 15:33:22 -0800916 devs.push(create_rng_device(cfg)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800917
David Tolnayde6b29a2018-12-20 11:49:46 -0800918 #[cfg(feature = "tpm")]
919 {
David Tolnay43f8e212019-02-13 17:28:16 -0800920 if cfg.software_tpm {
David Tolnay2b089fc2019-03-04 15:33:22 -0800921 devs.push(create_tpm_device(cfg)?);
David Tolnay43f8e212019-02-13 17:28:16 -0800922 }
David Tolnayde6b29a2018-12-20 11:49:46 -0800923 }
924
Jorge E. Moreira99d3f082019-03-07 10:59:54 -0800925 if let Some(single_touch_spec) = &cfg.virtio_single_touch {
926 devs.push(create_single_touch_device(cfg, single_touch_spec)?);
927 }
928
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800929 if let Some(trackpad_spec) = &cfg.virtio_trackpad {
David Tolnay2b089fc2019-03-04 15:33:22 -0800930 devs.push(create_trackpad_device(cfg, trackpad_spec)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800931 }
932
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800933 if let Some(mouse_socket) = &cfg.virtio_mouse {
David Tolnay2b089fc2019-03-04 15:33:22 -0800934 devs.push(create_mouse_device(cfg, mouse_socket)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800935 }
936
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800937 if let Some(keyboard_socket) = &cfg.virtio_keyboard {
David Tolnay2b089fc2019-03-04 15:33:22 -0800938 devs.push(create_keyboard_device(cfg, keyboard_socket)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800939 }
940
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800941 for dev_path in &cfg.virtio_input_evdevs {
David Tolnay2b089fc2019-03-04 15:33:22 -0800942 devs.push(create_vinput_device(cfg, dev_path)?);
Jorge E. Moreiradffec502019-01-14 18:44:49 -0800943 }
944
David Tolnay2b089fc2019-03-04 15:33:22 -0800945 devs.push(create_balloon_device(cfg, balloon_device_socket)?);
Dylan Reid295ccac2017-11-06 14:06:24 -0800946
Zach Reizner39aa26b2017-12-12 18:03:23 -0800947 // We checked above that if the IP is defined, then the netmask is, too.
Jianxun Zhang8f4d7682019-02-21 12:55:31 -0800948 for tap_fd in &cfg.tap_fd {
David Tolnay2b089fc2019-03-04 15:33:22 -0800949 devs.push(create_tap_net_device(cfg, *tap_fd)?);
Jorge E. Moreirab7952802019-02-12 16:43:05 -0800950 }
951
David Tolnay2b089fc2019-03-04 15:33:22 -0800952 if let (Some(host_ip), Some(netmask), Some(mac_address)) =
953 (cfg.host_ip, cfg.netmask, cfg.mac_address)
954 {
955 devs.push(create_net_device(cfg, host_ip, netmask, mac_address, mem)?);
Zach Reizner39aa26b2017-12-12 18:03:23 -0800956 }
957
David Tolnayfa701712019-02-13 16:42:54 -0800958 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
Chirantan Ekbotedd11d432019-06-11 21:50:46 +0900959 let mut resource_bridges = Vec::<virtio::resource_bridge::ResourceResponseSocket>::new();
960
961 if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() {
962 #[cfg_attr(not(feature = "gpu"), allow(unused_mut))]
963 let mut wl_resource_bridge = None::<virtio::resource_bridge::ResourceRequestSocket>;
964
965 #[cfg(feature = "gpu")]
966 {
967 if cfg.gpu {
968 let (wl_socket, gpu_socket) =
969 virtio::resource_bridge::pair().map_err(Error::CreateSocket)?;
970 resource_bridges.push(gpu_socket);
971 wl_resource_bridge = Some(wl_socket);
972 }
973 }
974
975 devs.push(create_wayland_device(
976 cfg,
977 wayland_socket_path,
978 wayland_device_socket,
979 wl_resource_bridge,
980 )?);
981 }
David Tolnayfa701712019-02-13 16:42:54 -0800982
Zach Reizner3a8100a2017-09-13 19:15:43 -0700983 #[cfg(feature = "gpu")]
984 {
985 if cfg.gpu {
Zach Reizner0f2cfb02019-06-19 17:46:03 -0700986 devs.push(create_gpu_device(
987 cfg,
988 _exit_evt,
989 gpu_device_socket,
990 resource_bridges,
991 cfg.wayland_socket_path.clone(),
992 cfg.x_display.clone(),
993 )?);
Zach Reizner3a8100a2017-09-13 19:15:43 -0700994 }
995 }
996
Zach Reizneraa575662018-08-15 10:46:32 -0700997 if let Some(cid) = cfg.cid {
David Tolnay2b089fc2019-03-04 15:33:22 -0800998 devs.push(create_vhost_vsock_device(cfg, cid, mem)?);
Zach Reizneraa575662018-08-15 10:46:32 -0700999 }
1000
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001001 for shared_dir in &cfg.shared_dirs {
1002 let SharedDir {
1003 src,
1004 tag,
1005 kind,
1006 uid_map,
1007 gid_map,
1008 cfg: fs_cfg,
1009 } = shared_dir;
David Tolnay2b089fc2019-03-04 15:33:22 -08001010
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001011 let dev = match kind {
1012 SharedDirKind::FS => create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone())?,
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +09001013 SharedDirKind::P9 => create_9p_device(cfg, src, tag)?,
Chirantan Ekbotebd4723b2019-07-17 10:50:30 +09001014 };
1015 devs.push(dev);
David Tolnay2b089fc2019-03-04 15:33:22 -08001016 }
1017
1018 Ok(devs)
1019}
1020
1021fn create_devices(
Trent Begin17ccaad2019-04-17 13:51:25 -06001022 cfg: &Config,
David Tolnay2b089fc2019-03-04 15:33:22 -08001023 mem: &GuestMemory,
Jakub Starona3411ea2019-04-24 10:55:25 -07001024 vm: &mut Vm,
1025 resources: &mut SystemAllocator,
David Tolnay2b089fc2019-03-04 15:33:22 -08001026 exit_evt: &EventFd,
Xiong Zhanga5d248c2019-09-17 14:17:19 -07001027 control_sockets: &mut Vec<TaggedControlSocket>,
Gurchetan Singh53edb812019-05-22 08:57:16 -07001028 wayland_device_socket: VmMemoryControlRequestSocket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001029 gpu_device_socket: VmMemoryControlRequestSocket,
Jakub Staron1f828d72019-04-11 12:49:29 -07001030 balloon_device_socket: BalloonControlResponseSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -07001031 disk_device_sockets: &mut Vec<DiskControlResponseSocket>,
Jingkui Wang100e6e42019-03-08 20:41:57 -08001032 usb_provider: HostBackendDeviceProvider,
David Tolnayfdac5ed2019-03-08 16:56:14 -08001033) -> DeviceResult<Vec<(Box<dyn PciDevice>, Option<Minijail>)>> {
David Tolnay2b089fc2019-03-04 15:33:22 -08001034 let stubs = create_virtio_devices(
1035 &cfg,
1036 mem,
Jakub Starona3411ea2019-04-24 10:55:25 -07001037 vm,
1038 resources,
David Tolnay2b089fc2019-03-04 15:33:22 -08001039 exit_evt,
1040 wayland_device_socket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001041 gpu_device_socket,
David Tolnay2b089fc2019-03-04 15:33:22 -08001042 balloon_device_socket,
1043 disk_device_sockets,
1044 )?;
1045
1046 let mut pci_devices = Vec::new();
1047
1048 for stub in stubs {
Daniel Verkampbb712d62019-11-19 09:47:33 -08001049 let (msi_host_socket, msi_device_socket) =
1050 msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?;
1051 control_sockets.push(TaggedControlSocket::VmIrq(msi_host_socket));
1052 let dev = VirtioPciDevice::new(mem.clone(), stub.dev, msi_device_socket)
1053 .map_err(Error::VirtioPciDev)?;
David Tolnayfdac5ed2019-03-08 16:56:14 -08001054 let dev = Box::new(dev) as Box<dyn PciDevice>;
David Tolnay2b089fc2019-03-04 15:33:22 -08001055 pci_devices.push((dev, stub.jail));
1056 }
1057
1058 if cfg.cras_audio {
paulhsia580d4182019-05-24 16:53:55 +08001059 let mut server = Box::new(CrasClient::new().map_err(Error::CreateCrasClient)?);
1060 if cfg.cras_capture {
1061 server.enable_cras_capture();
1062 }
David Tolnay2b089fc2019-03-04 15:33:22 -08001063 let cras_audio = devices::Ac97Dev::new(mem.clone(), server);
1064
1065 pci_devices.push((
1066 Box::new(cras_audio),
1067 simple_jail(&cfg, "cras_audio_device.policy")?,
1068 ));
1069 }
1070
1071 if cfg.null_audio {
1072 let server = Box::new(DummyStreamSource::new());
1073 let null_audio = devices::Ac97Dev::new(mem.clone(), server);
1074
1075 pci_devices.push((
1076 Box::new(null_audio),
1077 simple_jail(&cfg, "null_audio_device.policy")?,
1078 ));
1079 }
Jingkui Wang100e6e42019-03-08 20:41:57 -08001080 // Create xhci controller.
1081 let usb_controller = Box::new(XhciController::new(mem.clone(), usb_provider));
1082 pci_devices.push((usb_controller, simple_jail(&cfg, "xhci.policy")?));
David Tolnay2b089fc2019-03-04 15:33:22 -08001083
Xiong Zhang17b0daf2019-04-23 17:14:50 +08001084 if cfg.vfio.is_some() {
Xiong Zhang4b5bb3a2019-04-23 17:15:21 +08001085 let (vfio_host_socket_irq, vfio_device_socket_irq) =
1086 msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?;
1087 control_sockets.push(TaggedControlSocket::VmIrq(vfio_host_socket_irq));
1088
Xiong Zhang85abeff2019-04-23 17:15:24 +08001089 let (vfio_host_socket_mem, vfio_device_socket_mem) =
1090 msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?;
1091 control_sockets.push(TaggedControlSocket::VmMemory(vfio_host_socket_mem));
1092
Xiong 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 Zhang85abeff2019-04-23 17:15:24 +08001096 let vfiopcidevice = Box::new(VfioPciDevice::new(
1097 vfiodevice,
1098 vfio_device_socket_irq,
1099 vfio_device_socket_mem,
1100 ));
Xiong Zhang17b0daf2019-04-23 17:14:50 +08001101 pci_devices.push((vfiopcidevice, simple_jail(&cfg, "vfio_device.policy")?));
1102 }
1103
David Tolnay2b089fc2019-03-04 15:33:22 -08001104 Ok(pci_devices)
1105}
1106
1107#[derive(Copy, Clone)]
Chirantan Ekbote1a2683b2019-11-26 16:28:23 +09001108#[cfg_attr(not(feature = "tpm"), allow(dead_code))]
David Tolnay2b089fc2019-03-04 15:33:22 -08001109struct Ids {
1110 uid: uid_t,
1111 gid: gid_t,
1112}
1113
David Tolnay48c48292019-03-01 16:54:25 -08001114// Set the uid/gid for the jailed process and give a basic id map. This is
1115// required for bind mounts to work.
David Tolnayfd0971d2019-03-04 17:15:57 -08001116fn add_crosvm_user_to_jail(jail: &mut Minijail, feature: &str) -> Result<Ids> {
David Tolnay48c48292019-03-01 16:54:25 -08001117 let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap();
1118
1119 let crosvm_uid = match get_user_id(&crosvm_user_group) {
1120 Ok(u) => u,
1121 Err(e) => {
1122 warn!("falling back to current user id for {}: {}", feature, e);
1123 geteuid()
1124 }
1125 };
1126
1127 let crosvm_gid = match get_group_id(&crosvm_user_group) {
1128 Ok(u) => u,
1129 Err(e) => {
1130 warn!("falling back to current group id for {}: {}", feature, e);
1131 getegid()
1132 }
1133 };
1134
1135 jail.change_uid(crosvm_uid);
1136 jail.change_gid(crosvm_gid);
1137 jail.uidmap(&format!("{0} {0} 1", crosvm_uid))
1138 .map_err(Error::SettingUidMap)?;
1139 jail.gidmap(&format!("{0} {0} 1", crosvm_gid))
1140 .map_err(Error::SettingGidMap)?;
1141
David Tolnay41a6f842019-03-01 16:18:44 -08001142 Ok(Ids {
1143 uid: crosvm_uid,
1144 gid: crosvm_gid,
1145 })
David Tolnay48c48292019-03-01 16:54:25 -08001146}
1147
David Tolnayfd0971d2019-03-04 17:15:57 -08001148fn raw_fd_from_path(path: &Path) -> Result<RawFd> {
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001149 if !path.is_file() {
David Tolnayfd0971d2019-03-04 17:15:57 -08001150 return Err(Error::InvalidFdPath);
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001151 }
1152 let raw_fd = path
1153 .file_name()
1154 .and_then(|fd_osstr| fd_osstr.to_str())
1155 .and_then(|fd_str| fd_str.parse::<c_int>().ok())
1156 .ok_or(Error::InvalidFdPath)?;
David Tolnayfd0971d2019-03-04 17:15:57 -08001157 validate_raw_fd(raw_fd).map_err(Error::ValidateRawFd)
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001158}
1159
David Tolnayfd0971d2019-03-04 17:15:57 -08001160fn create_input_socket(path: &Path) -> Result<UnixStream> {
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001161 if path.parent() == Some(Path::new("/proc/self/fd")) {
1162 // Safe because we will validate |raw_fd|.
1163 unsafe { Ok(UnixStream::from_raw_fd(raw_fd_from_path(path)?)) }
1164 } else {
David Tolnayfd0971d2019-03-04 17:15:57 -08001165 UnixStream::connect(path).map_err(Error::InputEventsOpen)
Jorge E. Moreiradffec502019-01-14 18:44:49 -08001166 }
1167}
1168
Matt Delco84cf9c02019-10-07 22:38:13 -07001169fn setup_vcpu_signal_handler(use_kvm_signals: bool) -> Result<()> {
1170 if use_kvm_signals {
1171 unsafe {
1172 extern "C" fn handle_signal() {}
1173 // Our signal handler does nothing and is trivially async signal safe.
1174 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
1175 .map_err(Error::RegisterSignalHandler)?;
1176 }
1177 block_signal(SIGRTMIN() + 0).map_err(Error::BlockSignal)?;
1178 } else {
1179 unsafe {
1180 extern "C" fn handle_signal() {
1181 Vcpu::set_local_immediate_exit(true);
1182 }
1183 register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
1184 .map_err(Error::RegisterSignalHandler)?;
1185 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001186 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001187 Ok(())
1188}
1189
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001190#[derive(Default)]
1191struct VcpuRunMode {
1192 mtx: Mutex<VmRunMode>,
1193 cvar: Condvar,
1194}
1195
1196impl VcpuRunMode {
1197 fn set_and_notify(&self, new_mode: VmRunMode) {
1198 *self.mtx.lock() = new_mode;
1199 self.cvar.notify_all();
1200 }
1201}
1202
Zach Reizner55a9e502018-10-03 10:22:32 -07001203fn run_vcpu(
Matt Delco84cf9c02019-10-07 22:38:13 -07001204 mut vcpu: Vcpu,
Zach Reizner55a9e502018-10-03 10:22:32 -07001205 cpu_id: u32,
Daniel Verkamp107edb32019-04-05 09:58:48 -07001206 vcpu_affinity: Vec<usize>,
Zach Reizner55a9e502018-10-03 10:22:32 -07001207 start_barrier: Arc<Barrier>,
1208 io_bus: devices::Bus,
1209 mmio_bus: devices::Bus,
1210 exit_evt: EventFd,
Zach Reizner795355a2019-01-16 17:37:57 -08001211 requires_kvmclock_ctrl: bool,
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001212 run_mode_arc: Arc<VcpuRunMode>,
Matt Delco84cf9c02019-10-07 22:38:13 -07001213 use_kvm_signals: bool,
Zach Reizner55a9e502018-10-03 10:22:32 -07001214) -> Result<JoinHandle<()>> {
Zach Reizner8fb52112017-12-13 16:04:39 -08001215 thread::Builder::new()
1216 .name(format!("crosvm_vcpu{}", cpu_id))
1217 .spawn(move || {
Daniel Verkamp107edb32019-04-05 09:58:48 -07001218 if vcpu_affinity.len() != 0 {
1219 if let Err(e) = set_cpu_affinity(vcpu_affinity) {
1220 error!("Failed to set CPU affinity: {}", e);
1221 }
1222 }
1223
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001224 let mut sig_ok = true;
Matt Delco84cf9c02019-10-07 22:38:13 -07001225 if use_kvm_signals {
1226 match get_blocked_signals() {
1227 Ok(mut v) => {
1228 v.retain(|&x| x != SIGRTMIN() + 0);
1229 if let Err(e) = vcpu.set_signal_mask(&v) {
1230 error!(
1231 "Failed to set the KVM_SIGNAL_MASK for vcpu {} : {}",
1232 cpu_id, e
1233 );
1234 sig_ok = false;
1235 }
1236 }
1237 Err(e) => {
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001238 error!(
Matt Delco84cf9c02019-10-07 22:38:13 -07001239 "Failed to retrieve signal mask for vcpu {} : {}",
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001240 cpu_id, e
1241 );
1242 sig_ok = false;
1243 }
Matt Delco84cf9c02019-10-07 22:38:13 -07001244 };
1245 } else {
1246 vcpu.set_thread_id(SIGRTMIN() + 0);
1247 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001248
Zach Reizner8fb52112017-12-13 16:04:39 -08001249 start_barrier.wait();
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001250
David Tolnay8f3a2322018-11-30 17:11:35 -08001251 if sig_ok {
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001252 'vcpu_loop: loop {
1253 let mut interrupted_by_signal = false;
David Tolnay8f3a2322018-11-30 17:11:35 -08001254 match vcpu.run() {
1255 Ok(VcpuExit::IoIn { port, mut size }) => {
1256 let mut data = [0; 8];
1257 if size > data.len() {
1258 error!("unsupported IoIn size of {} bytes", size);
1259 size = data.len();
Zach Reizner39aa26b2017-12-12 18:03:23 -08001260 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001261 io_bus.read(port as u64, &mut data[..size]);
1262 if let Err(e) = vcpu.set_data(&data[..size]) {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001263 error!("failed to set return data for IoIn: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001264 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001265 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001266 Ok(VcpuExit::IoOut {
1267 port,
1268 mut size,
1269 data,
1270 }) => {
1271 if size > data.len() {
1272 error!("unsupported IoOut size of {} bytes", size);
1273 size = data.len();
1274 }
1275 io_bus.write(port as u64, &data[..size]);
1276 }
1277 Ok(VcpuExit::MmioRead { address, size }) => {
1278 let mut data = [0; 8];
1279 mmio_bus.read(address, &mut data[..size]);
1280 // Setting data for mmio can not fail.
1281 let _ = vcpu.set_data(&data[..size]);
1282 }
1283 Ok(VcpuExit::MmioWrite {
1284 address,
1285 size,
1286 data,
1287 }) => {
1288 mmio_bus.write(address, &data[..size]);
1289 }
1290 Ok(VcpuExit::Hlt) => break,
1291 Ok(VcpuExit::Shutdown) => break,
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001292 Ok(VcpuExit::SystemEvent(_, _)) => break,
David Tolnay8f3a2322018-11-30 17:11:35 -08001293 Ok(r) => warn!("unexpected vcpu exit: {:?}", r),
1294 Err(e) => match e.errno() {
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001295 libc::EINTR => interrupted_by_signal = true,
1296 libc::EAGAIN => {}
David Tolnay8f3a2322018-11-30 17:11:35 -08001297 _ => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001298 error!("vcpu hit unknown error: {}", e);
David Tolnay8f3a2322018-11-30 17:11:35 -08001299 break;
1300 }
1301 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08001302 }
Mark Ryan6ed5aea2018-04-20 13:52:35 +01001303
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001304 if interrupted_by_signal {
Matt Delco84cf9c02019-10-07 22:38:13 -07001305 if use_kvm_signals {
1306 // Try to clear the signal that we use to kick VCPU if it is pending before
1307 // attempting to handle pause requests.
1308 if let Err(e) = clear_signal(SIGRTMIN() + 0) {
1309 error!("failed to clear pending signal: {}", e);
1310 break;
1311 }
1312 } else {
1313 vcpu.set_immediate_exit(false);
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001314 }
1315 let mut run_mode_lock = run_mode_arc.mtx.lock();
1316 loop {
1317 match *run_mode_lock {
1318 VmRunMode::Running => break,
Zach Reizner795355a2019-01-16 17:37:57 -08001319 VmRunMode::Suspending => {
1320 // On KVM implementations that use a paravirtualized clock (e.g.
1321 // x86), a flag must be set to indicate to the guest kernel that
1322 // a VCPU was suspended. The guest kernel will use this flag to
1323 // prevent the soft lockup detection from triggering when this
1324 // VCPU resumes, which could happen days later in realtime.
1325 if requires_kvmclock_ctrl {
1326 if let Err(e) = vcpu.kvmclock_ctrl() {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001327 error!("failed to signal to kvm that vcpu {} is being suspended: {}", cpu_id, e);
Zach Reizner795355a2019-01-16 17:37:57 -08001328 }
1329 }
1330 }
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001331 VmRunMode::Exiting => break 'vcpu_loop,
1332 }
1333 // Give ownership of our exclusive lock to the condition variable that
1334 // will block. When the condition variable is notified, `wait` will
1335 // unblock and return a new exclusive lock.
1336 run_mode_lock = run_mode_arc.cvar.wait(run_mode_lock);
1337 }
1338 }
David Tolnay8f3a2322018-11-30 17:11:35 -08001339 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001340 }
Zach Reizner8fb52112017-12-13 16:04:39 -08001341 exit_evt
Zach Reizner39aa26b2017-12-12 18:03:23 -08001342 .write(1)
1343 .expect("failed to signal vcpu exit eventfd");
David Tolnay2bac1e72018-12-12 14:33:42 -08001344 })
1345 .map_err(Error::SpawnVcpu)
Zach Reizner39aa26b2017-12-12 18:03:23 -08001346}
1347
Sonny Raod5f66082019-04-24 12:24:38 -07001348// Reads the contents of a file and converts the space-separated fields into a Vec of u64s.
1349// Returns an error if any of the fields fail to parse.
1350fn file_fields_to_u64<P: AsRef<Path>>(path: P) -> io::Result<Vec<u64>> {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001351 let mut file = File::open(path)?;
1352
1353 let mut buf = [0u8; 32];
1354 let count = file.read(&mut buf)?;
1355
Zach Reizner55a9e502018-10-03 10:22:32 -07001356 let content =
1357 str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1358 content
1359 .trim()
Sonny Raod5f66082019-04-24 12:24:38 -07001360 .split_whitespace()
1361 .map(|x| {
1362 x.parse::<u64>()
1363 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
1364 })
1365 .collect()
1366}
1367
1368// Reads the contents of a file and converts them into a u64, and if there
1369// are multiple fields it only returns the first one.
1370fn file_to_u64<P: AsRef<Path>>(path: P) -> io::Result<u64> {
1371 file_fields_to_u64(path)?
1372 .into_iter()
1373 .next()
1374 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty file"))
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001375}
1376
Dylan Reid059a1882018-07-23 17:58:09 -07001377pub fn run_config(cfg: Config) -> Result<()> {
Lepton Wu9105e9f2019-03-14 11:38:31 -07001378 if cfg.sandbox {
Dylan Reid059a1882018-07-23 17:58:09 -07001379 // Printing something to the syslog before entering minijail so that libc's syslogger has a
1380 // chance to open files necessary for its operation, like `/etc/localtime`. After jailing,
1381 // access to those files will not be possible.
1382 info!("crosvm entering multiprocess mode");
1383 }
1384
Jingkui Wang100e6e42019-03-08 20:41:57 -08001385 let (usb_control_socket, usb_provider) =
David Tolnay5fb3f512019-04-12 19:22:33 -07001386 HostBackendDeviceProvider::new().map_err(Error::CreateUsbProvider)?;
Dylan Reid059a1882018-07-23 17:58:09 -07001387 // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
1388 // before any jailed devices have been spawned, so that we can catch any of them that fail very
1389 // quickly.
1390 let sigchld_fd = SignalFd::new(libc::SIGCHLD).map_err(Error::CreateSignalFd)?;
1391
David Tolnay2b089fc2019-03-04 15:33:22 -08001392 let initrd_image = if let Some(initrd_path) = &cfg.initrd_path {
1393 Some(File::open(initrd_path).map_err(|e| Error::OpenInitrd(initrd_path.clone(), e))?)
Daniel Verkampe403f5c2018-12-11 16:29:26 -08001394 } else {
1395 None
1396 };
1397
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07001398 let vm_image = match cfg.executable_path {
1399 Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel(
1400 File::open(kernel_path).map_err(|e| Error::OpenKernel(kernel_path.to_path_buf(), e))?,
1401 ),
1402 Some(Executable::Bios(ref bios_path)) => VmImage::Bios(
1403 File::open(bios_path).map_err(|e| Error::OpenBios(bios_path.to_path_buf(), e))?,
1404 ),
1405 _ => panic!("Did not receive a bios or kernel, should be impossible."),
1406 };
1407
Dylan Reid059a1882018-07-23 17:58:09 -07001408 let components = VmComponents {
Daniel Verkamp6a847062019-11-26 13:16:35 -08001409 memory_size: cfg
1410 .memory
1411 .unwrap_or(256)
1412 .checked_mul(1024 * 1024)
1413 .ok_or(Error::MemoryTooLarge)?,
Dylan Reid059a1882018-07-23 17:58:09 -07001414 vcpu_count: cfg.vcpu_count.unwrap_or(1),
Daniel Verkamp107edb32019-04-05 09:58:48 -07001415 vcpu_affinity: cfg.vcpu_affinity.clone(),
Cody Schuffelen6d1ab502019-05-21 12:12:38 -07001416 vm_image,
Tristan Muntsinger4133b012018-12-21 16:01:56 -08001417 android_fstab: cfg
1418 .android_fstab
1419 .as_ref()
David Tolnay2b089fc2019-03-04 15:33:22 -08001420 .map(|x| File::open(x).map_err(|e| Error::OpenAndroidFstab(x.to_path_buf(), e)))
Tristan Muntsinger4133b012018-12-21 16:01:56 -08001421 .map_or(Ok(None), |v| v.map(Some))?,
Daniel Verkampe403f5c2018-12-11 16:29:26 -08001422 initrd_image,
Daniel Verkampaac28132018-10-15 14:58:48 -07001423 extra_kernel_params: cfg.params.clone(),
1424 wayland_dmabuf: cfg.wayland_dmabuf,
Dylan Reid059a1882018-07-23 17:58:09 -07001425 };
1426
Zach Reiznera60744b2019-02-13 17:33:32 -08001427 let control_server_socket = match &cfg.socket_path {
1428 Some(path) => Some(UnlinkUnixSeqpacketListener(
1429 UnixSeqpacketListener::bind(path).map_err(Error::CreateSocket)?,
1430 )),
1431 None => None,
Dylan Reid059a1882018-07-23 17:58:09 -07001432 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001433
1434 let mut control_sockets = Vec::new();
Zach Reizner55a9e502018-10-03 10:22:32 -07001435 let (wayland_host_socket, wayland_device_socket) =
Gurchetan Singh53edb812019-05-22 08:57:16 -07001436 msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?;
1437 control_sockets.push(TaggedControlSocket::VmMemory(wayland_host_socket));
Dylan Reid059a1882018-07-23 17:58:09 -07001438 // Balloon gets a special socket so balloon requests can be forwarded from the main process.
Zach Reizner55a9e502018-10-03 10:22:32 -07001439 let (balloon_host_socket, balloon_device_socket) =
Jakub Staron1f828d72019-04-11 12:49:29 -07001440 msg_socket::pair::<BalloonControlCommand, ()>().map_err(Error::CreateSocket)?;
Dylan Reid059a1882018-07-23 17:58:09 -07001441
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001442 // Create one control socket per disk.
1443 let mut disk_device_sockets = Vec::new();
1444 let mut disk_host_sockets = Vec::new();
1445 let disk_count = cfg.disks.len();
1446 for _ in 0..disk_count {
1447 let (disk_host_socket, disk_device_socket) =
Jakub Staronecf81e02019-04-11 11:43:39 -07001448 msg_socket::pair::<DiskControlCommand, DiskControlResult>()
1449 .map_err(Error::CreateSocket)?;
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001450 disk_host_sockets.push(disk_host_socket);
Jakub Starone7c59052019-04-09 12:31:14 -07001451 disk_device_sockets.push(disk_device_socket);
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001452 }
1453
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001454 let (gpu_host_socket, gpu_device_socket) =
1455 msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?;
1456 control_sockets.push(TaggedControlSocket::VmMemory(gpu_host_socket));
1457
Lepton Wu20333e42019-03-14 10:48:03 -07001458 let sandbox = cfg.sandbox;
Trent Begin17ccaad2019-04-17 13:51:25 -06001459 let linux = Arch::build_vm(
1460 components,
1461 cfg.split_irqchip,
1462 &cfg.serial_parameters,
Zach Reiznera8adff02019-08-13 11:20:14 -07001463 simple_jail(&cfg, "serial.policy")?,
Jakub Starona3411ea2019-04-24 10:55:25 -07001464 |mem, vm, sys_allocator, exit_evt| {
Trent Begin17ccaad2019-04-17 13:51:25 -06001465 create_devices(
1466 &cfg,
Jakub Starona3411ea2019-04-24 10:55:25 -07001467 mem,
1468 vm,
1469 sys_allocator,
1470 exit_evt,
Xiong Zhanga5d248c2019-09-17 14:17:19 -07001471 &mut control_sockets,
Trent Begin17ccaad2019-04-17 13:51:25 -06001472 wayland_device_socket,
Gurchetan Singh96beafc2019-05-15 09:46:52 -07001473 gpu_device_socket,
Trent Begin17ccaad2019-04-17 13:51:25 -06001474 balloon_device_socket,
1475 &mut disk_device_sockets,
1476 usb_provider,
1477 )
1478 },
1479 )
David Tolnaybe034262019-03-04 17:48:36 -08001480 .map_err(Error::BuildVm)?;
Lepton Wu60893882018-11-21 11:06:18 -08001481
1482 let _render_node_host = ();
1483 #[cfg(feature = "gpu-forward")]
1484 let (_render_node_host, linux) = {
1485 // Rebinds linux as mutable.
1486 let mut linux = linux;
1487
1488 // Reserve memory range for GPU buffer allocation in advance to bypass region count
1489 // limitation. We use mremap/MAP_FIXED later to make sure GPU buffers fall into this range.
1490 let gpu_mmap =
1491 MemoryMapping::new_protection(RENDER_NODE_HOST_SIZE as usize, Protection::none())
1492 .map_err(Error::ReserveGpuMemory)?;
1493
Xiong Zhang383b3b52019-10-30 14:59:26 +08001494 // Put the non-accessible memory map into high mmio so that no other devices use that
Lepton Wu60893882018-11-21 11:06:18 -08001495 // guest address space.
1496 let gpu_addr = linux
1497 .resources
Xiong Zhang383b3b52019-10-30 14:59:26 +08001498 .mmio_allocator(MmioType::High)
Daniel Prilikd92f81a2019-03-26 14:28:19 -07001499 .allocate(
1500 RENDER_NODE_HOST_SIZE,
1501 Alloc::GpuRenderNode,
1502 "gpu_render_node".to_string(),
1503 )
1504 .map_err(|_| Error::AllocateGpuDeviceAddress)?;
Lepton Wu60893882018-11-21 11:06:18 -08001505
1506 let host = RenderNodeHost::start(&gpu_mmap, gpu_addr, linux.vm.get_memory().clone());
1507
1508 // Makes the gpu memory accessible at allocated address.
1509 linux
1510 .vm
Xiong Zhang383b3b52019-10-30 14:59:26 +08001511 .add_mmio_memory(
Lepton Wu60893882018-11-21 11:06:18 -08001512 GuestAddress(gpu_addr),
1513 gpu_mmap,
1514 /* read_only = */ false,
1515 /* log_dirty_pages = */ false,
1516 )
1517 .map_err(Error::AddGpuDeviceMemory)?;
1518 (host, linux)
1519 };
1520
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001521 run_control(
1522 linux,
Zach Reiznera60744b2019-02-13 17:33:32 -08001523 control_server_socket,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001524 control_sockets,
1525 balloon_host_socket,
1526 &disk_host_sockets,
Jingkui Wang100e6e42019-03-08 20:41:57 -08001527 usb_control_socket,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001528 sigchld_fd,
Lepton Wu60893882018-11-21 11:06:18 -08001529 _render_node_host,
Lepton Wu20333e42019-03-14 10:48:03 -07001530 sandbox,
Daniel Verkamp92f73d72018-12-04 13:17:46 -08001531 )
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001532}
1533
Zach Reizner55a9e502018-10-03 10:22:32 -07001534fn run_control(
1535 mut linux: RunnableLinuxVm,
Zach Reiznera60744b2019-02-13 17:33:32 -08001536 control_server_socket: Option<UnlinkUnixSeqpacketListener>,
Jakub Starond99cd0a2019-04-11 14:09:39 -07001537 mut control_sockets: Vec<TaggedControlSocket>,
Jakub Staron1f828d72019-04-11 12:49:29 -07001538 balloon_host_socket: BalloonControlRequestSocket,
Jakub Staronecf81e02019-04-11 11:43:39 -07001539 disk_host_sockets: &[DiskControlRequestSocket],
Jingkui Wang100e6e42019-03-08 20:41:57 -08001540 usb_control_socket: UsbControlSocket,
Zach Reizner55a9e502018-10-03 10:22:32 -07001541 sigchld_fd: SignalFd,
Lepton Wu60893882018-11-21 11:06:18 -08001542 _render_node_host: RenderNodeHost,
Lepton Wu20333e42019-03-14 10:48:03 -07001543 sandbox: bool,
Zach Reizner55a9e502018-10-03 10:22:32 -07001544) -> Result<()> {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001545 // Paths to get the currently available memory and the low memory threshold.
David Tolnay5bbbf612018-12-01 17:49:30 -08001546 const LOWMEM_MARGIN: &str = "/sys/kernel/mm/chromeos-low_mem/margin";
1547 const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available";
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001548
1549 // The amount of additional memory to claim back from the VM whenever the system is
1550 // low on memory.
1551 const ONE_GB: u64 = (1 << 30);
1552
Dylan Reid0ed91ab2018-05-31 15:42:18 -07001553 let max_balloon_memory = match linux.vm.get_memory().memory_size() {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001554 // If the VM has at least 1.5 GB, the balloon driver can consume all but the last 1 GB.
1555 n if n >= (ONE_GB / 2) * 3 => n - ONE_GB,
1556 // Otherwise, if the VM has at least 500MB the balloon driver will consume at most
1557 // half of it.
1558 n if n >= (ONE_GB / 2) => n / 2,
1559 // Otherwise, the VM is too small for us to take memory away from it.
1560 _ => 0,
1561 };
1562 let mut current_balloon_memory: u64 = 0;
1563 let balloon_memory_increment: u64 = max_balloon_memory / 16;
1564
Zach Reizner5bed0d22018-03-28 02:31:11 -07001565 #[derive(PollToken)]
1566 enum Token {
1567 Exit,
1568 Stdin,
1569 ChildSignal,
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001570 CheckAvailableMemory,
1571 LowMemory,
1572 LowmemTimer,
Zach Reiznera60744b2019-02-13 17:33:32 -08001573 VmControlServer,
Zach Reizner5bed0d22018-03-28 02:31:11 -07001574 VmControl { index: usize },
1575 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001576
1577 let stdin_handle = stdin();
1578 let stdin_lock = stdin_handle.lock();
1579 stdin_lock
1580 .set_raw_mode()
1581 .expect("failed to set terminal raw mode");
1582
Zach Reiznerb2110be2019-07-23 15:55:03 -07001583 let poll_ctx = PollContext::build_with(&[
1584 (&linux.exit_evt, Token::Exit),
1585 (&sigchld_fd, Token::ChildSignal),
1586 ])
1587 .map_err(Error::PollContextAdd)?;
1588
Zach Reizner5bed0d22018-03-28 02:31:11 -07001589 if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001590 warn!("failed to add stdin to poll context: {}", e);
Zach Reizner5bed0d22018-03-28 02:31:11 -07001591 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001592
1593 if let Some(socket_server) = &control_server_socket {
1594 poll_ctx
1595 .add(socket_server, Token::VmControlServer)
1596 .map_err(Error::PollContextAdd)?;
1597 }
Dylan Reid059a1882018-07-23 17:58:09 -07001598 for (index, socket) in control_sockets.iter().enumerate() {
Zach Reizner55a9e502018-10-03 10:22:32 -07001599 poll_ctx
1600 .add(socket.as_ref(), Token::VmControl { index })
1601 .map_err(Error::PollContextAdd)?;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001602 }
1603
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001604 // Watch for low memory notifications and take memory back from the VM.
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001605 let low_mem = File::open("/dev/chromeos-low-mem").ok();
David Tolnay64cd5ea2019-04-15 15:56:35 -07001606 if let Some(low_mem) = &low_mem {
Zach Reizner55a9e502018-10-03 10:22:32 -07001607 poll_ctx
1608 .add(low_mem, Token::LowMemory)
1609 .map_err(Error::PollContextAdd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001610 } else {
1611 warn!("Unable to open low mem indicator, maybe not a chrome os kernel");
1612 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001613
1614 // Used to rate limit balloon requests.
1615 let mut lowmem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001616 poll_ctx
1617 .add(&lowmem_timer, Token::LowmemTimer)
1618 .map_err(Error::PollContextAdd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001619
1620 // Used to check whether it's ok to start giving memory back to the VM.
1621 let mut freemem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001622 poll_ctx
1623 .add(&freemem_timer, Token::CheckAvailableMemory)
1624 .map_err(Error::PollContextAdd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001625
1626 // Used to add jitter to timer values so that we don't have a thundering herd problem when
1627 // multiple VMs are running.
Daniel Prilik22006042019-01-14 14:19:04 -08001628 let mut simple_rng = SimpleRng::new(
1629 SystemTime::now()
1630 .duration_since(UNIX_EPOCH)
1631 .expect("time went backwards")
1632 .subsec_nanos() as u64,
1633 );
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001634
Lepton Wu20333e42019-03-14 10:48:03 -07001635 if sandbox {
1636 // Before starting VCPUs, in case we started with some capabilities, drop them all.
1637 drop_capabilities().map_err(Error::DropCapabilities)?;
1638 }
Dmitry Torokhov71006072019-03-06 10:56:51 -08001639
Daniel Verkamp37c4a782019-01-04 10:44:17 -08001640 let mut vcpu_handles = Vec::with_capacity(linux.vcpus.len());
1641 let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpus.len() + 1));
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001642 let run_mode_arc = Arc::new(VcpuRunMode::default());
Matt Delco84cf9c02019-10-07 22:38:13 -07001643 let use_kvm_signals = !linux.kvm.check_extension(Cap::ImmediateExit);
1644 setup_vcpu_signal_handler(use_kvm_signals)?;
Daniel Verkamp94c35272019-09-12 13:31:30 -07001645 let vcpus = linux.vcpus.split_off(0);
1646 for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {
Zach Reizner55a9e502018-10-03 10:22:32 -07001647 let handle = run_vcpu(
1648 vcpu,
1649 cpu_id as u32,
Daniel Verkamp107edb32019-04-05 09:58:48 -07001650 linux.vcpu_affinity.clone(),
Zach Reizner55a9e502018-10-03 10:22:32 -07001651 vcpu_thread_barrier.clone(),
1652 linux.io_bus.clone(),
1653 linux.mmio_bus.clone(),
1654 linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?,
Zach Reizner795355a2019-01-16 17:37:57 -08001655 linux.vm.check_extension(Cap::KvmclockCtrl),
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001656 run_mode_arc.clone(),
Matt Delco84cf9c02019-10-07 22:38:13 -07001657 use_kvm_signals,
Zach Reizner55a9e502018-10-03 10:22:32 -07001658 )?;
Dylan Reid059a1882018-07-23 17:58:09 -07001659 vcpu_handles.push(handle);
1660 }
1661 vcpu_thread_barrier.wait();
1662
Zach Reizner39aa26b2017-12-12 18:03:23 -08001663 'poll: loop {
Zach Reizner5bed0d22018-03-28 02:31:11 -07001664 let events = {
1665 match poll_ctx.wait() {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001666 Ok(v) => v,
1667 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001668 error!("failed to poll: {}", e);
Zach Reizner39aa26b2017-12-12 18:03:23 -08001669 break;
1670 }
1671 }
1672 };
Zach Reiznera60744b2019-02-13 17:33:32 -08001673
1674 let mut vm_control_indices_to_remove = Vec::new();
Zach Reizner5bed0d22018-03-28 02:31:11 -07001675 for event in events.iter_readable() {
1676 match event.token() {
1677 Token::Exit => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001678 info!("vcpu requested shutdown");
1679 break 'poll;
1680 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001681 Token::Stdin => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001682 let mut out = [0u8; 64];
1683 match stdin_lock.read_raw(&mut out[..]) {
1684 Ok(0) => {
1685 // Zero-length read indicates EOF. Remove from pollables.
Zach Reizner5bed0d22018-03-28 02:31:11 -07001686 let _ = poll_ctx.delete(&stdin_handle);
Zach Reizner55a9e502018-10-03 10:22:32 -07001687 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001688 Err(e) => {
David Tolnayb4bd00f2019-02-12 17:51:26 -08001689 warn!("error while reading stdin: {}", e);
Zach Reizner5bed0d22018-03-28 02:31:11 -07001690 let _ = poll_ctx.delete(&stdin_handle);
Zach Reizner55a9e502018-10-03 10:22:32 -07001691 }
Jakub Staronb6515a92019-06-05 15:18:25 -07001692 Ok(count) => {
1693 if let Some(ref stdio_serial) = linux.stdio_serial {
Trent Begin17ccaad2019-04-17 13:51:25 -06001694 stdio_serial
Trent Begin17ccaad2019-04-17 13:51:25 -06001695 .queue_input_bytes(&out[..count])
1696 .expect("failed to queue bytes into serial port");
1697 }
Jakub Staronb6515a92019-06-05 15:18:25 -07001698 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001699 }
1700 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001701 Token::ChildSignal => {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001702 // Print all available siginfo structs, then exit the loop.
David Tolnayf5032762018-12-03 10:46:45 -08001703 while let Some(siginfo) = sigchld_fd.read().map_err(Error::SignalFd)? {
Zach Reizner3ba00982019-01-23 19:04:43 -08001704 let pid = siginfo.ssi_pid;
1705 let pid_label = match linux.pid_debug_label_map.get(&pid) {
1706 Some(label) => format!("{} (pid {})", label, pid),
1707 None => format!("pid {}", pid),
1708 };
David Tolnayf5032762018-12-03 10:46:45 -08001709 error!(
1710 "child {} died: signo {}, status {}, code {}",
Zach Reizner3ba00982019-01-23 19:04:43 -08001711 pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code
David Tolnayf5032762018-12-03 10:46:45 -08001712 );
Zach Reizner39aa26b2017-12-12 18:03:23 -08001713 }
David Tolnayf5032762018-12-03 10:46:45 -08001714 break 'poll;
Zach Reizner39aa26b2017-12-12 18:03:23 -08001715 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001716 Token::CheckAvailableMemory => {
1717 // Acknowledge the timer.
1718 freemem_timer.wait().map_err(Error::TimerFd)?;
1719 if current_balloon_memory == 0 {
1720 // Nothing to see here.
1721 if let Err(e) = freemem_timer.clear() {
1722 warn!("unable to clear available memory check timer: {}", e);
1723 }
1724 continue;
1725 }
1726
1727 // Otherwise see if we can free up some memory.
1728 let margin = file_to_u64(LOWMEM_MARGIN).map_err(Error::ReadLowmemMargin)?;
Zach Reizner55a9e502018-10-03 10:22:32 -07001729 let available =
1730 file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001731
1732 // `available` and `margin` are specified in MB while `balloon_memory_increment` is in
1733 // bytes. So to correctly compare them we need to turn the increment value into MB.
Zach Reizner55a9e502018-10-03 10:22:32 -07001734 if available >= margin + 2 * (balloon_memory_increment >> 20) {
1735 current_balloon_memory =
1736 if current_balloon_memory >= balloon_memory_increment {
1737 current_balloon_memory - balloon_memory_increment
1738 } else {
1739 0
1740 };
Jakub Staron1f828d72019-04-11 12:49:29 -07001741 let command = BalloonControlCommand::Adjust {
1742 num_bytes: current_balloon_memory,
1743 };
1744 if let Err(e) = balloon_host_socket.send(&command) {
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001745 warn!("failed to send memory value to balloon device: {}", e);
1746 }
1747 }
1748 }
1749 Token::LowMemory => {
David Tolnay64cd5ea2019-04-15 15:56:35 -07001750 if let Some(low_mem) = &low_mem {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001751 let old_balloon_memory = current_balloon_memory;
Zach Reizner55a9e502018-10-03 10:22:32 -07001752 current_balloon_memory = min(
1753 current_balloon_memory + balloon_memory_increment,
1754 max_balloon_memory,
1755 );
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001756 if current_balloon_memory != old_balloon_memory {
Jakub Staron1f828d72019-04-11 12:49:29 -07001757 let command = BalloonControlCommand::Adjust {
1758 num_bytes: current_balloon_memory,
1759 };
1760 if let Err(e) = balloon_host_socket.send(&command) {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001761 warn!("failed to send memory value to balloon device: {}", e);
1762 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001763 }
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001764
1765 // Stop polling the lowmem device until the timer fires.
1766 poll_ctx.delete(low_mem).map_err(Error::PollContextDelete)?;
1767
1768 // Add some jitter to the timer so that if there are multiple VMs running
1769 // they don't all start ballooning at exactly the same time.
Daniel Prilik22006042019-01-14 14:19:04 -08001770 let lowmem_dur = Duration::from_millis(1000 + simple_rng.rng() % 200);
Zach Reizner55a9e502018-10-03 10:22:32 -07001771 lowmem_timer
1772 .reset(lowmem_dur, None)
1773 .map_err(Error::ResetTimerFd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001774
1775 // Also start a timer to check when we can start giving memory back. Do the
1776 // first check after a minute (with jitter) and subsequent checks after
1777 // every 30 seconds (with jitter).
Daniel Prilik22006042019-01-14 14:19:04 -08001778 let freemem_dur = Duration::from_secs(60 + simple_rng.rng() % 12);
1779 let freemem_int = Duration::from_secs(30 + simple_rng.rng() % 6);
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001780 freemem_timer
1781 .reset(freemem_dur, Some(freemem_int))
1782 .map_err(Error::ResetTimerFd)?;
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001783 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001784 }
1785 Token::LowmemTimer => {
1786 // Acknowledge the timer.
1787 lowmem_timer.wait().map_err(Error::TimerFd)?;
1788
David Tolnay64cd5ea2019-04-15 15:56:35 -07001789 if let Some(low_mem) = &low_mem {
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001790 // Start polling the lowmem device again.
Zach Reizner55a9e502018-10-03 10:22:32 -07001791 poll_ctx
1792 .add(low_mem, Token::LowMemory)
1793 .map_err(Error::PollContextAdd)?;
Dylan Reidf11e6ed2018-07-31 10:24:06 -07001794 }
Chirantan Ekbote448516e2018-07-24 16:07:42 -07001795 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001796 Token::VmControlServer => {
1797 if let Some(socket_server) = &control_server_socket {
1798 match socket_server.accept() {
1799 Ok(socket) => {
1800 poll_ctx
1801 .add(
1802 &socket,
1803 Token::VmControl {
1804 index: control_sockets.len(),
1805 },
1806 )
1807 .map_err(Error::PollContextAdd)?;
Jakub Starond99cd0a2019-04-11 14:09:39 -07001808 control_sockets
1809 .push(TaggedControlSocket::Vm(MsgSocket::new(socket)));
Zach Reiznera60744b2019-02-13 17:33:32 -08001810 }
1811 Err(e) => error!("failed to accept socket: {}", e),
1812 }
1813 }
1814 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001815 Token::VmControl { index } => {
Daniel Verkamp37c4a782019-01-04 10:44:17 -08001816 if let Some(socket) = control_sockets.get(index) {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001817 match socket {
1818 TaggedControlSocket::Vm(socket) => match socket.recv() {
1819 Ok(request) => {
1820 let mut run_mode_opt = None;
1821 let response = request.execute(
1822 &mut run_mode_opt,
1823 &balloon_host_socket,
1824 disk_host_sockets,
1825 &usb_control_socket,
1826 );
1827 if let Err(e) = socket.send(&response) {
1828 error!("failed to send VmResponse: {}", e);
1829 }
1830 if let Some(run_mode) = run_mode_opt {
1831 info!("control socket changed run mode to {}", run_mode);
1832 match run_mode {
1833 VmRunMode::Exiting => {
1834 break 'poll;
1835 }
1836 other => {
1837 run_mode_arc.set_and_notify(other);
1838 for handle in &vcpu_handles {
1839 let _ = handle.kill(SIGRTMIN() + 0);
1840 }
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001841 }
1842 }
1843 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001844 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001845 Err(e) => {
1846 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1847 vm_control_indices_to_remove.push(index);
1848 } else {
1849 error!("failed to recv VmRequest: {}", e);
1850 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001851 }
Jakub Starond99cd0a2019-04-11 14:09:39 -07001852 },
Gurchetan Singh53edb812019-05-22 08:57:16 -07001853 TaggedControlSocket::VmMemory(socket) => match socket.recv() {
Jakub Starond99cd0a2019-04-11 14:09:39 -07001854 Ok(request) => {
1855 let response =
1856 request.execute(&mut linux.vm, &mut linux.resources);
1857 if let Err(e) = socket.send(&response) {
Gurchetan Singh53edb812019-05-22 08:57:16 -07001858 error!("failed to send VmMemoryControlResponse: {}", e);
Jakub Starond99cd0a2019-04-11 14:09:39 -07001859 }
1860 }
1861 Err(e) => {
1862 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1863 vm_control_indices_to_remove.push(index);
1864 } else {
Gurchetan Singh53edb812019-05-22 08:57:16 -07001865 error!("failed to recv VmMemoryControlRequest: {}", e);
Jakub Starond99cd0a2019-04-11 14:09:39 -07001866 }
1867 }
1868 },
Xiong Zhang2515b752019-09-19 10:29:02 +08001869 TaggedControlSocket::VmIrq(socket) => match socket.recv() {
1870 Ok(request) => {
1871 let response =
1872 request.execute(&mut linux.vm, &mut linux.resources);
1873 if let Err(e) = socket.send(&response) {
1874 error!("failed to send VmIrqResponse: {}", e);
1875 }
1876 }
1877 Err(e) => {
1878 if let MsgError::BadRecvSize { actual: 0, .. } = e {
1879 vm_control_indices_to_remove.push(index);
1880 } else {
1881 error!("failed to recv VmIrqRequest: {}", e);
1882 }
1883 }
1884 },
Zach Reizner39aa26b2017-12-12 18:03:23 -08001885 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001886 }
1887 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001888 }
1889 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001890
Zach Reizner5bed0d22018-03-28 02:31:11 -07001891 for event in events.iter_hungup() {
Zach Reiznera60744b2019-02-13 17:33:32 -08001892 match event.token() {
1893 Token::Exit => {}
1894 Token::Stdin => {
1895 let _ = poll_ctx.delete(&stdin_handle);
1896 }
1897 Token::ChildSignal => {}
1898 Token::CheckAvailableMemory => {}
1899 Token::LowMemory => {}
1900 Token::LowmemTimer => {}
1901 Token::VmControlServer => {}
1902 Token::VmControl { index } => {
1903 // It's possible more data is readable and buffered while the socket is hungup,
1904 // so don't delete the socket from the poll context until we're sure all the
1905 // data is read.
Jakub Starond99cd0a2019-04-11 14:09:39 -07001906 match control_sockets
1907 .get(index)
1908 .map(|s| s.as_ref().get_readable_bytes())
1909 {
Zach Reiznera60744b2019-02-13 17:33:32 -08001910 Some(Ok(0)) | Some(Err(_)) => vm_control_indices_to_remove.push(index),
1911 Some(Ok(x)) => info!("control index {} has {} bytes readable", index, x),
1912 _ => {}
Zach Reizner55a9e502018-10-03 10:22:32 -07001913 }
Zach Reizner5bed0d22018-03-28 02:31:11 -07001914 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001915 }
1916 }
Zach Reiznera60744b2019-02-13 17:33:32 -08001917
1918 // Sort in reverse so the highest indexes are removed first. This removal algorithm
Zide Chen89584072019-11-14 10:33:51 -08001919 // preserves correct indexes as each element is removed.
Zach Reiznera60744b2019-02-13 17:33:32 -08001920 vm_control_indices_to_remove.sort_unstable_by(|a, b| b.cmp(a));
1921 vm_control_indices_to_remove.dedup();
1922 for index in vm_control_indices_to_remove {
Zide Chen89584072019-11-14 10:33:51 -08001923 // Delete the socket from the `poll_ctx` synchronously. Otherwise, the kernel will do
1924 // this automatically when the FD inserted into the `poll_ctx` is closed after this
1925 // if-block, but this removal can be deferred unpredictably. In some instances where the
1926 // system is under heavy load, we can even get events returned by `poll_ctx` for an FD
1927 // that has already been closed. Because the token associated with that spurious event
1928 // now belongs to a different socket, the control loop will start to interact with
1929 // sockets that might not be ready to use. This can cause incorrect hangup detection or
1930 // blocking on a socket that will never be ready. See also: crbug.com/1019986
1931 if let Some(socket) = control_sockets.get(index) {
1932 poll_ctx.delete(socket).map_err(Error::PollContextDelete)?;
1933 }
1934
1935 // This line implicitly drops the socket at `index` when it gets returned by
1936 // `swap_remove`. After this line, the socket at `index` is not the one from
1937 // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to
1938 // use `poll_ctx.modify` to change the associated index in its `Token::VmControl`.
Zach Reiznera60744b2019-02-13 17:33:32 -08001939 control_sockets.swap_remove(index);
1940 if let Some(socket) = control_sockets.get(index) {
1941 poll_ctx
Xiong Zhang44bb3dd2019-04-23 17:09:50 +08001942 .modify(
1943 socket,
1944 WatchingEvents::empty().set_read(),
1945 Token::VmControl { index },
1946 )
Zach Reiznera60744b2019-02-13 17:33:32 -08001947 .map_err(Error::PollContextAdd)?;
1948 }
1949 }
Zach Reizner39aa26b2017-12-12 18:03:23 -08001950 }
1951
Zach Reizner6a8fdd92019-01-16 14:38:41 -08001952 // VCPU threads MUST see the VmRunMode flag, otherwise they may re-enter the VM.
1953 run_mode_arc.set_and_notify(VmRunMode::Exiting);
Dylan Reid059a1882018-07-23 17:58:09 -07001954 for handle in vcpu_handles {
Dmitry Torokhovcd405332018-02-16 16:25:54 -08001955 match handle.kill(SIGRTMIN() + 0) {
Zach Reizner39aa26b2017-12-12 18:03:23 -08001956 Ok(_) => {
1957 if let Err(e) = handle.join() {
1958 error!("failed to join vcpu thread: {:?}", e);
1959 }
1960 }
David Tolnayb4bd00f2019-02-12 17:51:26 -08001961 Err(e) => error!("failed to kill vcpu thread: {}", e),
Zach Reizner39aa26b2017-12-12 18:03:23 -08001962 }
1963 }
1964
Daniel Verkamp94c35272019-09-12 13:31:30 -07001965 // Explicitly drop the VM structure here to allow the devices to clean up before the
1966 // control sockets are closed when this function exits.
1967 mem::drop(linux);
1968
Zach Reizner39aa26b2017-12-12 18:03:23 -08001969 stdin_lock
1970 .set_canon_mode()
1971 .expect("failed to restore canonical mode for terminal");
1972
1973 Ok(())
1974}