Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1 | // Copyright 2017 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
Daniel Verkamp | 8c2f000 | 2020-08-31 15:13:35 -0700 | [diff] [blame] | 5 | use std::cmp::{max, Reverse}; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 6 | use std::convert::TryFrom; |
John Bates | b220eac | 2020-09-14 17:03:02 -0700 | [diff] [blame] | 7 | #[cfg(feature = "gpu")] |
| 8 | use std::env; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 9 | use std::error::Error as StdError; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 10 | use std::ffi::CStr; |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 11 | use std::fmt::{self, Display}; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 12 | use std::fs::{File, OpenOptions}; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 13 | use std::io::{self, stdin, Read}; |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 14 | use std::iter; |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 15 | use std::mem; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 16 | use std::net::Ipv4Addr; |
Daniel Verkamp | 6f9215c | 2019-08-20 09:41:22 -0700 | [diff] [blame] | 17 | #[cfg(feature = "gpu")] |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 18 | use std::num::NonZeroU8; |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 19 | use std::num::ParseIntError; |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 20 | use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 21 | use std::os::unix::net::UnixStream; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 22 | use std::path::{Path, PathBuf}; |
Chirantan Ekbote | aa77ea4 | 2019-12-09 14:58:54 +0900 | [diff] [blame] | 23 | use std::ptr; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 24 | use std::str; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 25 | use std::sync::{Arc, Barrier}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 26 | use std::thread; |
| 27 | use std::thread::JoinHandle; |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 28 | use std::time::Duration; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 29 | |
David Tolnay | 41a6f84 | 2019-03-01 16:18:44 -0800 | [diff] [blame] | 30 | use libc::{self, c_int, gid_t, uid_t}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 31 | |
Tomasz Jeznach | 4264464 | 2020-05-20 23:27:59 -0700 | [diff] [blame] | 32 | use acpi_tables::sdt::SDT; |
| 33 | |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 34 | use base::net::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener}; |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 35 | #[cfg(feature = "gpu")] |
| 36 | use devices::virtio::EventDevice; |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 37 | use devices::virtio::{self, Console, VirtioDevice}; |
paulhsia | ce17e6e | 2020-08-28 18:37:45 +0800 | [diff] [blame] | 38 | #[cfg(feature = "audio")] |
| 39 | use devices::Ac97Dev; |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 40 | use devices::{ |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 41 | self, HostBackendDeviceProvider, KvmKernelIrqChip, PciDevice, VfioContainer, VfioDevice, |
| 42 | VfioPciDevice, VirtioPciDevice, XhciController, |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 43 | }; |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 44 | use hypervisor::kvm::{Kvm, KvmVcpu, KvmVm}; |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 45 | use hypervisor::{Hypervisor, HypervisorCap, Vcpu, VcpuExit, VcpuRunHandle, Vm, VmCap}; |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 46 | use minijail::{self, Minijail}; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 47 | use msg_socket::{MsgError, MsgReceiver, MsgSender, MsgSocket}; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 48 | use net_util::{Error as NetError, MacAddress, Tap}; |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 49 | use remain::sorted; |
Xiong Zhang | 87a3b44 | 2019-10-29 17:32:44 +0800 | [diff] [blame] | 50 | use resources::{Alloc, MmioType, SystemAllocator}; |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 51 | use sync::{Condvar, Mutex}; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 52 | |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 53 | use base::{ |
David Tolnay | 633426a | 2019-04-12 12:18:35 -0700 | [diff] [blame] | 54 | self, block_signal, clear_signal, drop_capabilities, error, flock, get_blocked_signals, |
Fletcher Woodruff | 82ff397 | 2019-10-02 13:11:34 -0600 | [diff] [blame] | 55 | get_group_id, get_user_id, getegid, geteuid, info, register_rt_signal_handler, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 56 | set_cpu_affinity, set_rt_prio_limit, set_rt_round_robin, signal, validate_raw_fd, warn, Event, |
| 57 | ExternalMapping, FlockOperation, Killable, MemoryMappingArena, PollContext, PollToken, |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 58 | Protection, ScopedEvent, SignalFd, Terminal, Timer, WatchingEvents, SIGRTMIN, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 59 | }; |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 60 | use vm_control::{ |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 61 | BalloonControlCommand, BalloonControlRequestSocket, BalloonControlResponseSocket, |
Charles William Dick | 664cc3c | 2020-01-10 14:31:52 +0900 | [diff] [blame] | 62 | BalloonControlResult, DiskControlCommand, DiskControlRequestSocket, DiskControlResponseSocket, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 63 | DiskControlResult, IrqSetup, UsbControlSocket, VmControlResponseSocket, VmIrqRequest, |
| 64 | VmIrqRequestSocket, VmIrqResponse, VmIrqResponseSocket, VmMemoryControlRequestSocket, |
| 65 | VmMemoryControlResponseSocket, VmMemoryRequest, VmMemoryResponse, VmMsyncRequest, |
| 66 | VmMsyncRequestSocket, VmMsyncResponse, VmMsyncResponseSocket, VmRunMode, |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 67 | }; |
Dylan Reid | ec058d6 | 2020-07-20 20:21:11 -0700 | [diff] [blame] | 68 | use vm_memory::{GuestAddress, GuestMemory}; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 69 | |
Daniel Verkamp | 50740ce | 2020-02-28 12:36:56 -0800 | [diff] [blame] | 70 | use crate::{Config, DiskOption, Executable, SharedDir, SharedDirKind, TouchDeviceOption}; |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 71 | use arch::{ |
Daniel Verkamp | c677fb4 | 2020-09-08 13:47:49 -0700 | [diff] [blame] | 72 | self, LinuxArch, RunnableLinuxVm, SerialHardware, SerialParameters, VcpuAffinity, |
| 73 | VirtioDeviceStub, VmComponents, VmImage, |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 74 | }; |
Sonny Rao | ed517d1 | 2018-02-13 22:09:43 -0800 | [diff] [blame] | 75 | |
Sonny Rao | 2ffa0cb | 2018-02-26 17:27:40 -0800 | [diff] [blame] | 76 | #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 77 | use { |
| 78 | aarch64::AArch64 as Arch, |
| 79 | devices::{IrqChip, IrqChipAArch64 as IrqChipArch}, |
| 80 | hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch}, |
| 81 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 82 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 83 | use { |
| 84 | devices::{IrqChipX86_64, IrqChipX86_64 as IrqChipArch, KvmSplitIrqChip}, |
| 85 | hypervisor::{VcpuX86_64, VcpuX86_64 as VcpuArch, VmX86_64 as VmArch}, |
| 86 | x86_64::X8664arch as Arch, |
| 87 | }; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 88 | |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 89 | #[sorted] |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 90 | #[derive(Debug)] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 91 | pub enum Error { |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 92 | AddGpuDeviceMemory(base::Error), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 93 | AddIrqChipVcpu(base::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 94 | AddPmemDeviceMemory(base::Error), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 95 | AllocateGpuDeviceAddress, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 96 | AllocatePmemDeviceAddress(resources::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 97 | BalloonDeviceNew(virtio::BalloonError), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 98 | BlockDeviceNew(base::Error), |
| 99 | BlockSignal(base::signal::Error), |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 100 | BuildVm(<Arch as LinuxArch>::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 101 | ChownTpmStorage(base::Error), |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 102 | CloneEvent(base::Error), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 103 | CloneVcpu(base::Error), |
| 104 | ConfigureVcpu(<Arch as LinuxArch>::Error), |
Andrew Scull | 1590e6f | 2020-03-18 18:00:47 +0000 | [diff] [blame] | 105 | #[cfg(feature = "audio")] |
Judy Hsiao | d5c1e96 | 2020-02-04 12:30:01 +0800 | [diff] [blame] | 106 | CreateAc97(devices::PciDeviceError), |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 107 | CreateConsole(arch::serial::Error), |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 108 | CreateDiskError(disk::Error), |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 109 | CreateEvent(base::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 110 | CreatePollContext(base::Error), |
| 111 | CreateSignalFd(base::SignalFdError), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 112 | CreateSocket(io::Error), |
Chirantan Ekbote | 49fa08f | 2018-11-16 13:26:53 -0800 | [diff] [blame] | 113 | CreateTapDevice(NetError), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 114 | CreateTimer(base::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 115 | CreateTpmStorage(PathBuf, io::Error), |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 116 | CreateUsbProvider(devices::usb::host_backend::error::Error), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 117 | CreateVcpu(base::Error), |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 118 | CreateVfioDevice(devices::vfio::VfioError), |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 119 | DeviceJail(minijail::Error), |
| 120 | DevicePivotRoot(minijail::Error), |
Daniel Verkamp | 46d61ba | 2020-02-25 10:17:50 -0800 | [diff] [blame] | 121 | Disk(PathBuf, io::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 122 | DiskImageLock(base::Error), |
| 123 | DropCapabilities(base::Error), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 124 | FsDeviceNew(virtio::fs::Error), |
| 125 | GetMaxOpenFiles(io::Error), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 126 | GetSignalMask(signal::Error), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 127 | InputDeviceNew(virtio::InputError), |
| 128 | InputEventsOpen(std::io::Error), |
Dylan Reid | 2056644 | 2018-04-02 15:06:15 -0700 | [diff] [blame] | 129 | InvalidFdPath, |
Zach Reizner | 579bd2c | 2018-09-14 15:43:33 -0700 | [diff] [blame] | 130 | InvalidWaylandPath, |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 131 | IoJail(minijail::Error), |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 132 | LoadKernel(Box<dyn StdError>), |
Daniel Verkamp | 6a84706 | 2019-11-26 13:16:35 -0800 | [diff] [blame] | 133 | MemoryTooLarge, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 134 | NetDeviceNew(virtio::NetError), |
Tomasz Jeznach | 4264464 | 2020-05-20 23:27:59 -0700 | [diff] [blame] | 135 | OpenAcpiTable(PathBuf, io::Error), |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 136 | OpenAndroidFstab(PathBuf, io::Error), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 137 | OpenBios(PathBuf, io::Error), |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 138 | OpenInitrd(PathBuf, io::Error), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 139 | OpenKernel(PathBuf, io::Error), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 140 | OpenVinput(PathBuf, io::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 141 | P9DeviceNew(virtio::P9Error), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 142 | ParseMaxOpenFiles(ParseIntError), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 143 | PivotRootDoesntExist(&'static str), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 144 | PmemDeviceImageTooBig, |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 145 | PmemDeviceNew(base::Error), |
| 146 | PollContextAdd(base::Error), |
| 147 | PollContextDelete(base::Error), |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 148 | ReadMemAvailable(io::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 149 | RegisterBalloon(arch::DeviceRegistrationError), |
| 150 | RegisterBlock(arch::DeviceRegistrationError), |
| 151 | RegisterGpu(arch::DeviceRegistrationError), |
| 152 | RegisterNet(arch::DeviceRegistrationError), |
| 153 | RegisterP9(arch::DeviceRegistrationError), |
| 154 | RegisterRng(arch::DeviceRegistrationError), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 155 | RegisterSignalHandler(base::Error), |
Dylan Reid | 0f579cb | 2018-07-09 15:39:34 -0700 | [diff] [blame] | 156 | RegisterWayland(arch::DeviceRegistrationError), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 157 | ReserveGpuMemory(base::MmapError), |
| 158 | ReserveMemory(base::Error), |
| 159 | ReservePmemMemory(base::MmapError), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 160 | ResetTimer(base::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 161 | RngDeviceNew(virtio::RngError), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 162 | RunnableVcpu(base::Error), |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 163 | SettingGidMap(minijail::Error), |
| 164 | SettingMaxOpenFiles(minijail::Error), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 165 | SettingSignalMask(base::Error), |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 166 | SettingUidMap(minijail::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 167 | SignalFd(base::SignalFdError), |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 168 | SpawnVcpu(io::Error), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 169 | Timer(base::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 170 | ValidateRawFd(base::Error), |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 171 | VhostNetDeviceNew(virtio::vhost::Error), |
| 172 | VhostVsockDeviceNew(virtio::vhost::Error), |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 173 | VirtioPciDev(base::Error), |
| 174 | WaylandDeviceNew(base::Error), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 175 | } |
| 176 | |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 177 | impl Display for Error { |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 178 | #[remain::check] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 179 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 180 | use self::Error::*; |
| 181 | |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 182 | #[sorted] |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 183 | match self { |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 184 | AddGpuDeviceMemory(e) => write!(f, "failed to add gpu device memory: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 185 | AddIrqChipVcpu(e) => write!(f, "failed to add vcpu to irq chip: {}", e), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 186 | AddPmemDeviceMemory(e) => write!(f, "failed to add pmem device memory: {}", e), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 187 | AllocateGpuDeviceAddress => write!(f, "failed to allocate gpu device guest address"), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 188 | AllocatePmemDeviceAddress(e) => { |
| 189 | write!(f, "failed to allocate memory for pmem device: {}", e) |
| 190 | } |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 191 | BalloonDeviceNew(e) => write!(f, "failed to create balloon: {}", e), |
| 192 | BlockDeviceNew(e) => write!(f, "failed to create block device: {}", e), |
| 193 | BlockSignal(e) => write!(f, "failed to block signal: {}", e), |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 194 | BuildVm(e) => write!(f, "The architecture failed to build the vm: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 195 | ChownTpmStorage(e) => write!(f, "failed to chown tpm storage: {}", e), |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 196 | CloneEvent(e) => write!(f, "failed to clone event: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 197 | CloneVcpu(e) => write!(f, "failed to clone vcpu: {}", e), |
| 198 | ConfigureVcpu(e) => write!(f, "failed to configure vcpu: {}", e), |
Andrew Scull | 1590e6f | 2020-03-18 18:00:47 +0000 | [diff] [blame] | 199 | #[cfg(feature = "audio")] |
Judy Hsiao | d5c1e96 | 2020-02-04 12:30:01 +0800 | [diff] [blame] | 200 | CreateAc97(e) => write!(f, "failed to create ac97 device: {}", e), |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 201 | CreateConsole(e) => write!(f, "failed to create console device: {}", e), |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 202 | CreateDiskError(e) => write!(f, "failed to create virtual disk: {}", e), |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 203 | CreateEvent(e) => write!(f, "failed to create event: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 204 | CreatePollContext(e) => write!(f, "failed to create poll context: {}", e), |
| 205 | CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e), |
| 206 | CreateSocket(e) => write!(f, "failed to create socket: {}", e), |
| 207 | CreateTapDevice(e) => write!(f, "failed to create tap device: {}", e), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 208 | CreateTimer(e) => write!(f, "failed to create Timer: {}", e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 209 | CreateTpmStorage(p, e) => { |
| 210 | write!(f, "failed to create tpm storage dir {}: {}", p.display(), e) |
| 211 | } |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 212 | CreateUsbProvider(e) => write!(f, "failed to create usb provider: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 213 | CreateVcpu(e) => write!(f, "failed to create vcpu: {}", e), |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 214 | CreateVfioDevice(e) => write!(f, "Failed to create vfio device {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 215 | DeviceJail(e) => write!(f, "failed to jail device: {}", e), |
| 216 | DevicePivotRoot(e) => write!(f, "failed to pivot root device: {}", e), |
Daniel Verkamp | 46d61ba | 2020-02-25 10:17:50 -0800 | [diff] [blame] | 217 | Disk(p, e) => write!(f, "failed to load disk image {}: {}", p.display(), e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 218 | DiskImageLock(e) => write!(f, "failed to lock disk image: {}", e), |
Dmitry Torokhov | 7100607 | 2019-03-06 10:56:51 -0800 | [diff] [blame] | 219 | DropCapabilities(e) => write!(f, "failed to drop process capabilities: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 220 | FsDeviceNew(e) => write!(f, "failed to create fs device: {}", e), |
| 221 | GetMaxOpenFiles(e) => write!(f, "failed to get max number of open files: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 222 | GetSignalMask(e) => write!(f, "failed to retrieve signal mask for vcpu: {}", e), |
David Tolnay | 64cd5ea | 2019-04-15 15:56:35 -0700 | [diff] [blame] | 223 | InputDeviceNew(e) => write!(f, "failed to set up input device: {}", e), |
| 224 | InputEventsOpen(e) => write!(f, "failed to open event device: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 225 | InvalidFdPath => write!(f, "failed parsing a /proc/self/fd/*"), |
| 226 | InvalidWaylandPath => write!(f, "wayland socket path has no parent or file name"), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 227 | IoJail(e) => write!(f, "{}", e), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 228 | LoadKernel(e) => write!(f, "failed to load kernel: {}", e), |
Daniel Verkamp | 6a84706 | 2019-11-26 13:16:35 -0800 | [diff] [blame] | 229 | MemoryTooLarge => write!(f, "requested memory size too large"), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 230 | NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e), |
Tomasz Jeznach | 4264464 | 2020-05-20 23:27:59 -0700 | [diff] [blame] | 231 | OpenAcpiTable(p, e) => write!(f, "failed to open ACPI file {}: {}", p.display(), e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 232 | OpenAndroidFstab(p, e) => write!( |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 233 | f, |
| 234 | "failed to open android fstab file {}: {}", |
| 235 | p.display(), |
| 236 | e |
| 237 | ), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 238 | OpenBios(p, e) => write!(f, "failed to open bios {}: {}", p.display(), e), |
David Tolnay | 3df3552 | 2019-03-11 12:36:30 -0700 | [diff] [blame] | 239 | OpenInitrd(p, e) => write!(f, "failed to open initrd {}: {}", p.display(), e), |
| 240 | OpenKernel(p, e) => write!(f, "failed to open kernel image {}: {}", p.display(), e), |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 241 | OpenVinput(p, e) => write!(f, "failed to open vinput device {}: {}", p.display(), e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 242 | P9DeviceNew(e) => write!(f, "failed to create 9p device: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 243 | ParseMaxOpenFiles(e) => write!(f, "failed to parse max number of open files: {}", e), |
Lepton Wu | 39133a0 | 2019-02-27 12:42:29 -0800 | [diff] [blame] | 244 | PivotRootDoesntExist(p) => write!(f, "{} doesn't exist, can't jail devices.", p), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 245 | PmemDeviceImageTooBig => { |
| 246 | write!(f, "failed to create pmem device: pmem device image too big") |
| 247 | } |
| 248 | PmemDeviceNew(e) => write!(f, "failed to create pmem device: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 249 | PollContextAdd(e) => write!(f, "failed to add fd to poll context: {}", e), |
| 250 | PollContextDelete(e) => write!(f, "failed to remove fd from poll context: {}", e), |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 251 | ReadMemAvailable(e) => write!(f, "failed to read /proc/meminfo: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 252 | RegisterBalloon(e) => write!(f, "error registering balloon device: {}", e), |
| 253 | RegisterBlock(e) => write!(f, "error registering block device: {}", e), |
| 254 | RegisterGpu(e) => write!(f, "error registering gpu device: {}", e), |
| 255 | RegisterNet(e) => write!(f, "error registering net device: {}", e), |
| 256 | RegisterP9(e) => write!(f, "error registering 9p device: {}", e), |
| 257 | RegisterRng(e) => write!(f, "error registering rng device: {}", e), |
| 258 | RegisterSignalHandler(e) => write!(f, "error registering signal handler: {}", e), |
| 259 | RegisterWayland(e) => write!(f, "error registering wayland device: {}", e), |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 260 | ReserveGpuMemory(e) => write!(f, "failed to reserve gpu memory: {}", e), |
| 261 | ReserveMemory(e) => write!(f, "failed to reserve memory: {}", e), |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 262 | ReservePmemMemory(e) => write!(f, "failed to reserve pmem memory: {}", e), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 263 | ResetTimer(e) => write!(f, "failed to reset Timer: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 264 | RngDeviceNew(e) => write!(f, "failed to set up rng: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 265 | RunnableVcpu(e) => write!(f, "failed to set thread id for vcpu: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 266 | SettingGidMap(e) => write!(f, "error setting GID map: {}", e), |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 267 | SettingMaxOpenFiles(e) => write!(f, "error setting max open files: {}", e), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 268 | SettingSignalMask(e) => write!(f, "failed to set the signal mask for vcpu: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 269 | SettingUidMap(e) => write!(f, "error setting UID map: {}", e), |
| 270 | SignalFd(e) => write!(f, "failed to read signal fd: {}", e), |
| 271 | SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e), |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 272 | Timer(e) => write!(f, "failed to read timer fd: {}", e), |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 273 | ValidateRawFd(e) => write!(f, "failed to validate raw fd: {}", e), |
| 274 | VhostNetDeviceNew(e) => write!(f, "failed to set up vhost networking: {}", e), |
| 275 | VhostVsockDeviceNew(e) => write!(f, "failed to set up virtual socket device: {}", e), |
| 276 | VirtioPciDev(e) => write!(f, "failed to create virtio pci dev: {}", e), |
| 277 | WaylandDeviceNew(e) => write!(f, "failed to create wayland device: {}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
Allen Webb | f3024c8 | 2020-06-19 07:19:48 -0700 | [diff] [blame] | 282 | impl From<minijail::Error> for Error { |
| 283 | fn from(err: minijail::Error) -> Self { |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 284 | Error::IoJail(err) |
| 285 | } |
| 286 | } |
| 287 | |
David Tolnay | c69f975 | 2019-03-01 18:07:56 -0800 | [diff] [blame] | 288 | impl std::error::Error for Error {} |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 289 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 290 | type Result<T> = std::result::Result<T, Error>; |
| 291 | |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 292 | enum TaggedControlSocket { |
| 293 | Vm(VmControlResponseSocket), |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 294 | VmMemory(VmMemoryControlResponseSocket), |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 295 | VmIrq(VmIrqResponseSocket), |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 296 | VmMsync(VmMsyncResponseSocket), |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 297 | } |
| 298 | |
| 299 | impl AsRef<UnixSeqpacket> for TaggedControlSocket { |
| 300 | fn as_ref(&self) -> &UnixSeqpacket { |
| 301 | use self::TaggedControlSocket::*; |
| 302 | match &self { |
Chirantan Ekbote | 5058253 | 2020-01-16 16:49:14 +0900 | [diff] [blame] | 303 | Vm(ref socket) => socket.as_ref(), |
| 304 | VmMemory(ref socket) => socket.as_ref(), |
| 305 | VmIrq(ref socket) => socket.as_ref(), |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 306 | VmMsync(ref socket) => socket.as_ref(), |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | impl AsRawFd for TaggedControlSocket { |
| 312 | fn as_raw_fd(&self) -> RawFd { |
| 313 | self.as_ref().as_raw_fd() |
| 314 | } |
| 315 | } |
| 316 | |
Andrew Walbran | f50bab6 | 2020-07-07 13:22:53 +0100 | [diff] [blame] | 317 | fn get_max_open_files() -> Result<u64> { |
Chirantan Ekbote | aa77ea4 | 2019-12-09 14:58:54 +0900 | [diff] [blame] | 318 | let mut buf = mem::MaybeUninit::<libc::rlimit64>::zeroed(); |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 319 | |
Chirantan Ekbote | aa77ea4 | 2019-12-09 14:58:54 +0900 | [diff] [blame] | 320 | // Safe because this will only modify `buf` and we check the return value. |
| 321 | let res = unsafe { libc::prlimit64(0, libc::RLIMIT_NOFILE, ptr::null(), buf.as_mut_ptr()) }; |
| 322 | if res == 0 { |
| 323 | // Safe because the kernel guarantees that the struct is fully initialized. |
| 324 | let limit = unsafe { buf.assume_init() }; |
| 325 | Ok(limit.rlim_max) |
| 326 | } else { |
| 327 | Err(Error::GetMaxOpenFiles(io::Error::last_os_error())) |
| 328 | } |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 329 | } |
| 330 | |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 331 | struct SandboxConfig<'a> { |
| 332 | limit_caps: bool, |
| 333 | log_failures: bool, |
| 334 | seccomp_policy: &'a Path, |
| 335 | uid_map: Option<&'a str>, |
| 336 | gid_map: Option<&'a str>, |
| 337 | } |
| 338 | |
Zach Reizner | 4486379 | 2019-06-26 14:22:08 -0700 | [diff] [blame] | 339 | fn create_base_minijail( |
| 340 | root: &Path, |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 341 | r_limit: Option<u64>, |
| 342 | config: Option<&SandboxConfig>, |
Zach Reizner | 4486379 | 2019-06-26 14:22:08 -0700 | [diff] [blame] | 343 | ) -> Result<Minijail> { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 344 | // All child jails run in a new user namespace without any users mapped, |
| 345 | // they run as nobody unless otherwise configured. |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 346 | let mut j = Minijail::new().map_err(Error::DeviceJail)?; |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 347 | |
| 348 | if let Some(config) = config { |
| 349 | j.namespace_pids(); |
| 350 | j.namespace_user(); |
| 351 | j.namespace_user_disable_setgroups(); |
| 352 | if config.limit_caps { |
| 353 | // Don't need any capabilities. |
| 354 | j.use_caps(0); |
| 355 | } |
| 356 | if let Some(uid_map) = config.uid_map { |
| 357 | j.uidmap(uid_map).map_err(Error::SettingUidMap)?; |
| 358 | } |
| 359 | if let Some(gid_map) = config.gid_map { |
| 360 | j.gidmap(gid_map).map_err(Error::SettingGidMap)?; |
| 361 | } |
Chirantan Ekbote | f84c229 | 2020-02-21 16:37:27 +0900 | [diff] [blame] | 362 | // Run in a new mount namespace. |
| 363 | j.namespace_vfs(); |
| 364 | |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 365 | // Run in an empty network namespace. |
| 366 | j.namespace_net(); |
Chirantan Ekbote | f84c229 | 2020-02-21 16:37:27 +0900 | [diff] [blame] | 367 | |
| 368 | // Don't allow the device to gain new privileges. |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 369 | j.no_new_privs(); |
| 370 | |
| 371 | // By default we'll prioritize using the pre-compiled .bpf over the .policy |
| 372 | // file (the .bpf is expected to be compiled using "trap" as the failure |
| 373 | // behavior instead of the default "kill" behavior). |
| 374 | // Refer to the code comment for the "seccomp-log-failures" |
| 375 | // command-line parameter for an explanation about why the |log_failures| |
| 376 | // flag forces the use of .policy files (and the build-time alternative to |
| 377 | // this run-time flag). |
| 378 | let bpf_policy_file = config.seccomp_policy.with_extension("bpf"); |
| 379 | if bpf_policy_file.exists() && !config.log_failures { |
| 380 | j.parse_seccomp_program(&bpf_policy_file) |
| 381 | .map_err(Error::DeviceJail)?; |
| 382 | } else { |
| 383 | // Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP, |
| 384 | // which will correctly kill the entire device process if a worker |
| 385 | // thread commits a seccomp violation. |
| 386 | j.set_seccomp_filter_tsync(); |
| 387 | if config.log_failures { |
| 388 | j.log_seccomp_filter_failures(); |
| 389 | } |
| 390 | j.parse_seccomp_filters(&config.seccomp_policy.with_extension("policy")) |
| 391 | .map_err(Error::DeviceJail)?; |
| 392 | } |
| 393 | j.use_seccomp_filter(); |
| 394 | // Don't do init setup. |
| 395 | j.run_as_init(); |
| 396 | } |
| 397 | |
Chirantan Ekbote | f84c229 | 2020-02-21 16:37:27 +0900 | [diff] [blame] | 398 | // Only pivot_root if we are not re-using the current root directory. |
| 399 | if root != Path::new("/") { |
| 400 | // It's safe to call `namespace_vfs` multiple times. |
| 401 | j.namespace_vfs(); |
| 402 | j.enter_pivot_root(root).map_err(Error::DevicePivotRoot)?; |
| 403 | } |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 404 | |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 405 | // Most devices don't need to open many fds. |
| 406 | let limit = if let Some(r) = r_limit { r } else { 1024u64 }; |
| 407 | j.set_rlimit(libc::RLIMIT_NOFILE as i32, limit, limit) |
| 408 | .map_err(Error::SettingMaxOpenFiles)?; |
| 409 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 410 | Ok(j) |
| 411 | } |
| 412 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 413 | fn simple_jail(cfg: &Config, policy: &str) -> Result<Option<Minijail>> { |
Lepton Wu | 9105e9f | 2019-03-14 11:38:31 -0700 | [diff] [blame] | 414 | if cfg.sandbox { |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 415 | let pivot_root: &str = option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty"); |
| 416 | // A directory for a jailed device's pivot root. |
| 417 | let root_path = Path::new(pivot_root); |
| 418 | if !root_path.exists() { |
| 419 | return Err(Error::PivotRootDoesntExist(pivot_root)); |
| 420 | } |
| 421 | let policy_path: PathBuf = cfg.seccomp_policy_dir.join(policy); |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 422 | let config = SandboxConfig { |
| 423 | limit_caps: true, |
| 424 | log_failures: cfg.seccomp_log_failures, |
| 425 | seccomp_policy: &policy_path, |
| 426 | uid_map: None, |
| 427 | gid_map: None, |
| 428 | }; |
| 429 | Ok(Some(create_base_minijail(root_path, None, Some(&config))?)) |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 430 | } else { |
| 431 | Ok(None) |
| 432 | } |
| 433 | } |
| 434 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 435 | type DeviceResult<T = VirtioDeviceStub> = std::result::Result<T, Error>; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 436 | |
| 437 | fn create_block_device( |
| 438 | cfg: &Config, |
| 439 | disk: &DiskOption, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 440 | disk_device_socket: DiskControlResponseSocket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 441 | ) -> DeviceResult { |
| 442 | // Special case '/proc/self/fd/*' paths. The FD is already open, just use it. |
| 443 | let raw_image: File = if disk.path.parent() == Some(Path::new("/proc/self/fd")) { |
| 444 | // Safe because we will validate |raw_fd|. |
| 445 | unsafe { File::from_raw_fd(raw_fd_from_path(&disk.path)?) } |
| 446 | } else { |
| 447 | OpenOptions::new() |
| 448 | .read(true) |
| 449 | .write(!disk.read_only) |
| 450 | .open(&disk.path) |
Daniel Verkamp | 46d61ba | 2020-02-25 10:17:50 -0800 | [diff] [blame] | 451 | .map_err(|e| Error::Disk(disk.path.to_path_buf(), e))? |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 452 | }; |
| 453 | // Lock the disk image to prevent other crosvm instances from using it. |
| 454 | let lock_op = if disk.read_only { |
| 455 | FlockOperation::LockShared |
| 456 | } else { |
| 457 | FlockOperation::LockExclusive |
| 458 | }; |
| 459 | flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?; |
| 460 | |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 461 | let disk_file = disk::create_disk_file(raw_image).map_err(Error::CreateDiskError)?; |
Daniel Verkamp | e73c80f | 2019-11-08 10:11:16 -0800 | [diff] [blame] | 462 | let dev = virtio::Block::new( |
| 463 | disk_file, |
| 464 | disk.read_only, |
| 465 | disk.sparse, |
Daniel Verkamp | 2767223 | 2019-12-06 17:26:55 +1100 | [diff] [blame] | 466 | disk.block_size, |
Daniel Verkamp | e73c80f | 2019-11-08 10:11:16 -0800 | [diff] [blame] | 467 | Some(disk_device_socket), |
| 468 | ) |
| 469 | .map_err(Error::BlockDeviceNew)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 470 | |
| 471 | Ok(VirtioDeviceStub { |
Cody Schuffelen | 7d533e5 | 2019-07-02 16:54:05 -0700 | [diff] [blame] | 472 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 473 | jail: simple_jail(&cfg, "block_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 474 | }) |
| 475 | } |
| 476 | |
| 477 | fn create_rng_device(cfg: &Config) -> DeviceResult { |
| 478 | let dev = virtio::Rng::new().map_err(Error::RngDeviceNew)?; |
| 479 | |
| 480 | Ok(VirtioDeviceStub { |
| 481 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 482 | jail: simple_jail(&cfg, "rng_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 483 | }) |
| 484 | } |
| 485 | |
| 486 | #[cfg(feature = "tpm")] |
| 487 | fn create_tpm_device(cfg: &Config) -> DeviceResult { |
Michael Hoyle | 6b19695 | 2020-08-02 20:09:41 -0700 | [diff] [blame] | 488 | use base::chown; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 489 | use std::ffi::CString; |
| 490 | use std::fs; |
| 491 | use std::process; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 492 | |
| 493 | let tpm_storage: PathBuf; |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 494 | let mut tpm_jail = simple_jail(&cfg, "tpm_device")?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 495 | |
| 496 | match &mut tpm_jail { |
| 497 | Some(jail) => { |
| 498 | // Create a tmpfs in the device's root directory for tpm |
| 499 | // simulator storage. The size is 20*1024, or 20 KB. |
| 500 | jail.mount_with_data( |
| 501 | Path::new("none"), |
| 502 | Path::new("/"), |
| 503 | "tmpfs", |
| 504 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 505 | "size=20480", |
| 506 | )?; |
| 507 | |
| 508 | let crosvm_ids = add_crosvm_user_to_jail(jail, "tpm")?; |
| 509 | |
| 510 | let pid = process::id(); |
| 511 | let tpm_pid_dir = format!("/run/vm/tpm.{}", pid); |
| 512 | tpm_storage = Path::new(&tpm_pid_dir).to_owned(); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 513 | fs::create_dir_all(&tpm_storage) |
| 514 | .map_err(|e| Error::CreateTpmStorage(tpm_storage.to_owned(), e))?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 515 | let tpm_pid_dir_c = CString::new(tpm_pid_dir).expect("no nul bytes"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 516 | chown(&tpm_pid_dir_c, crosvm_ids.uid, crosvm_ids.gid) |
| 517 | .map_err(Error::ChownTpmStorage)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 518 | |
| 519 | jail.mount_bind(&tpm_storage, &tpm_storage, true)?; |
| 520 | } |
| 521 | None => { |
| 522 | // Path used inside cros_sdk which does not have /run/vm. |
| 523 | tpm_storage = Path::new("/tmp/tpm-simulator").to_owned(); |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | let dev = virtio::Tpm::new(tpm_storage); |
| 528 | |
| 529 | Ok(VirtioDeviceStub { |
| 530 | dev: Box::new(dev), |
| 531 | jail: tpm_jail, |
| 532 | }) |
| 533 | } |
| 534 | |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 535 | fn create_single_touch_device(cfg: &Config, single_touch_spec: &TouchDeviceOption) -> DeviceResult { |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 536 | let socket = single_touch_spec |
| 537 | .get_path() |
| 538 | .into_unix_stream() |
| 539 | .map_err(|e| { |
| 540 | error!("failed configuring virtio single touch: {:?}", e); |
| 541 | e |
| 542 | })?; |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 543 | |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 544 | let (width, height) = single_touch_spec.get_size(); |
| 545 | let dev = virtio::new_single_touch(socket, width, height).map_err(Error::InputDeviceNew)?; |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 546 | Ok(VirtioDeviceStub { |
| 547 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 548 | jail: simple_jail(&cfg, "input_device")?, |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 549 | }) |
| 550 | } |
| 551 | |
| 552 | fn create_trackpad_device(cfg: &Config, trackpad_spec: &TouchDeviceOption) -> DeviceResult { |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 553 | let socket = trackpad_spec.get_path().into_unix_stream().map_err(|e| { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 554 | error!("failed configuring virtio trackpad: {}", e); |
| 555 | e |
| 556 | })?; |
| 557 | |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 558 | let (width, height) = trackpad_spec.get_size(); |
| 559 | let dev = virtio::new_trackpad(socket, width, height).map_err(Error::InputDeviceNew)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 560 | |
| 561 | Ok(VirtioDeviceStub { |
| 562 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 563 | jail: simple_jail(&cfg, "input_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 564 | }) |
| 565 | } |
| 566 | |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 567 | fn create_mouse_device<T: IntoUnixStream>(cfg: &Config, mouse_socket: T) -> DeviceResult { |
| 568 | let socket = mouse_socket.into_unix_stream().map_err(|e| { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 569 | error!("failed configuring virtio mouse: {}", e); |
| 570 | e |
| 571 | })?; |
| 572 | |
| 573 | let dev = virtio::new_mouse(socket).map_err(Error::InputDeviceNew)?; |
| 574 | |
| 575 | Ok(VirtioDeviceStub { |
| 576 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 577 | jail: simple_jail(&cfg, "input_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 578 | }) |
| 579 | } |
| 580 | |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 581 | fn create_keyboard_device<T: IntoUnixStream>(cfg: &Config, keyboard_socket: T) -> DeviceResult { |
| 582 | let socket = keyboard_socket.into_unix_stream().map_err(|e| { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 583 | error!("failed configuring virtio keyboard: {}", e); |
| 584 | e |
| 585 | })?; |
| 586 | |
| 587 | let dev = virtio::new_keyboard(socket).map_err(Error::InputDeviceNew)?; |
| 588 | |
| 589 | Ok(VirtioDeviceStub { |
| 590 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 591 | jail: simple_jail(&cfg, "input_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 592 | }) |
| 593 | } |
| 594 | |
| 595 | fn create_vinput_device(cfg: &Config, dev_path: &Path) -> DeviceResult { |
| 596 | let dev_file = OpenOptions::new() |
| 597 | .read(true) |
| 598 | .write(true) |
| 599 | .open(dev_path) |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 600 | .map_err(|e| Error::OpenVinput(dev_path.to_owned(), e))?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 601 | |
| 602 | let dev = virtio::new_evdev(dev_file).map_err(Error::InputDeviceNew)?; |
| 603 | |
| 604 | Ok(VirtioDeviceStub { |
| 605 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 606 | jail: simple_jail(&cfg, "input_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 607 | }) |
| 608 | } |
| 609 | |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 610 | fn create_balloon_device(cfg: &Config, socket: BalloonControlResponseSocket) -> DeviceResult { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 611 | let dev = virtio::Balloon::new(socket).map_err(Error::BalloonDeviceNew)?; |
| 612 | |
| 613 | Ok(VirtioDeviceStub { |
| 614 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 615 | jail: simple_jail(&cfg, "balloon_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 616 | }) |
| 617 | } |
| 618 | |
| 619 | fn create_tap_net_device(cfg: &Config, tap_fd: RawFd) -> DeviceResult { |
| 620 | // Safe because we ensure that we get a unique handle to the fd. |
| 621 | let tap = unsafe { |
| 622 | Tap::from_raw_fd(validate_raw_fd(tap_fd).map_err(Error::ValidateRawFd)?) |
| 623 | .map_err(Error::CreateTapDevice)? |
| 624 | }; |
| 625 | |
Xiong Zhang | 773c707 | 2020-03-20 10:39:55 +0800 | [diff] [blame] | 626 | let mut vq_pairs = cfg.net_vq_pairs.unwrap_or(1); |
| 627 | let vcpu_count = cfg.vcpu_count.unwrap_or(1); |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 628 | if vcpu_count < vq_pairs as usize { |
Xiong Zhang | 773c707 | 2020-03-20 10:39:55 +0800 | [diff] [blame] | 629 | error!("net vq pairs must be smaller than vcpu count, fall back to single queue mode"); |
| 630 | vq_pairs = 1; |
| 631 | } |
| 632 | let dev = virtio::Net::from(tap, vq_pairs).map_err(Error::NetDeviceNew)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 633 | |
| 634 | Ok(VirtioDeviceStub { |
| 635 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 636 | jail: simple_jail(&cfg, "net_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 637 | }) |
| 638 | } |
| 639 | |
| 640 | fn create_net_device( |
| 641 | cfg: &Config, |
| 642 | host_ip: Ipv4Addr, |
| 643 | netmask: Ipv4Addr, |
| 644 | mac_address: MacAddress, |
| 645 | mem: &GuestMemory, |
| 646 | ) -> DeviceResult { |
Xiong Zhang | 773c707 | 2020-03-20 10:39:55 +0800 | [diff] [blame] | 647 | let mut vq_pairs = cfg.net_vq_pairs.unwrap_or(1); |
| 648 | let vcpu_count = cfg.vcpu_count.unwrap_or(1); |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 649 | if vcpu_count < vq_pairs as usize { |
Xiong Zhang | 773c707 | 2020-03-20 10:39:55 +0800 | [diff] [blame] | 650 | error!("net vq pairs must be smaller than vcpu count, fall back to single queue mode"); |
| 651 | vq_pairs = 1; |
| 652 | } |
| 653 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 654 | let dev = if cfg.vhost_net { |
| 655 | let dev = |
| 656 | virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, netmask, mac_address, mem) |
| 657 | .map_err(Error::VhostNetDeviceNew)?; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 658 | Box::new(dev) as Box<dyn VirtioDevice> |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 659 | } else { |
Xiong Zhang | 773c707 | 2020-03-20 10:39:55 +0800 | [diff] [blame] | 660 | let dev = virtio::Net::<Tap>::new(host_ip, netmask, mac_address, vq_pairs) |
| 661 | .map_err(Error::NetDeviceNew)?; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 662 | Box::new(dev) as Box<dyn VirtioDevice> |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 663 | }; |
| 664 | |
| 665 | let policy = if cfg.vhost_net { |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 666 | "vhost_net_device" |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 667 | } else { |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 668 | "net_device" |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 669 | }; |
| 670 | |
| 671 | Ok(VirtioDeviceStub { |
| 672 | dev, |
| 673 | jail: simple_jail(&cfg, policy)?, |
| 674 | }) |
| 675 | } |
| 676 | |
| 677 | #[cfg(feature = "gpu")] |
| 678 | fn create_gpu_device( |
| 679 | cfg: &Config, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 680 | exit_evt: &Event, |
Gurchetan Singh | 7ec58fa | 2019-05-15 15:30:38 -0700 | [diff] [blame] | 681 | gpu_device_socket: VmMemoryControlRequestSocket, |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 682 | gpu_sockets: Vec<virtio::resource_bridge::ResourceResponseSocket>, |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 683 | wayland_socket_path: Option<&PathBuf>, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 684 | x_display: Option<String>, |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 685 | event_devices: Vec<EventDevice>, |
Lingfeng Yang | 5572c8d | 2020-05-05 08:40:36 -0700 | [diff] [blame] | 686 | map_request: Arc<Mutex<Option<ExternalMapping>>>, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 687 | ) -> DeviceResult { |
| 688 | let jailed_wayland_path = Path::new("/wayland-0"); |
| 689 | |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 690 | let mut display_backends = vec![ |
| 691 | virtio::DisplayBackend::X(x_display), |
Jason Macnak | 60eb1fb | 2020-01-09 14:36:29 -0800 | [diff] [blame] | 692 | virtio::DisplayBackend::Stub, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 693 | ]; |
| 694 | |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 695 | if let Some(socket_path) = wayland_socket_path { |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 696 | display_backends.insert( |
| 697 | 0, |
| 698 | virtio::DisplayBackend::Wayland(if cfg.sandbox { |
| 699 | Some(jailed_wayland_path.to_owned()) |
| 700 | } else { |
| 701 | Some(socket_path.to_owned()) |
| 702 | }), |
| 703 | ); |
| 704 | } |
| 705 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 706 | let dev = virtio::Gpu::new( |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 707 | exit_evt.try_clone().map_err(Error::CloneEvent)?, |
Gurchetan Singh | 7ec58fa | 2019-05-15 15:30:38 -0700 | [diff] [blame] | 708 | Some(gpu_device_socket), |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 709 | NonZeroU8::new(1).unwrap(), // number of scanouts |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 710 | gpu_sockets, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 711 | display_backends, |
Jason Macnak | cc7070b | 2019-11-06 14:48:12 -0800 | [diff] [blame] | 712 | cfg.gpu_parameters.as_ref().unwrap(), |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 713 | event_devices, |
Lingfeng Yang | 5572c8d | 2020-05-05 08:40:36 -0700 | [diff] [blame] | 714 | map_request, |
| 715 | cfg.sandbox, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 716 | ); |
| 717 | |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 718 | let jail = match simple_jail(&cfg, "gpu_device")? { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 719 | Some(mut jail) => { |
| 720 | // Create a tmpfs in the device's root directory so that we can bind mount the |
| 721 | // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
| 722 | jail.mount_with_data( |
| 723 | Path::new("none"), |
| 724 | Path::new("/"), |
| 725 | "tmpfs", |
| 726 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 727 | "size=67108864", |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 728 | )?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 729 | |
| 730 | // Device nodes required for DRM. |
| 731 | let sys_dev_char_path = Path::new("/sys/dev/char"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 732 | jail.mount_bind(sys_dev_char_path, sys_dev_char_path, false)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 733 | let sys_devices_path = Path::new("/sys/devices"); |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 734 | jail.mount_bind(sys_devices_path, sys_devices_path, false)?; |
Jason Macnak | 2340052 | 2020-08-28 09:10:46 -0700 | [diff] [blame] | 735 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 736 | let drm_dri_path = Path::new("/dev/dri"); |
Jason Macnak | 2340052 | 2020-08-28 09:10:46 -0700 | [diff] [blame] | 737 | if drm_dri_path.exists() { |
| 738 | jail.mount_bind(drm_dri_path, drm_dri_path, false)?; |
| 739 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 740 | |
John Bates | b220eac | 2020-09-14 17:03:02 -0700 | [diff] [blame] | 741 | // Prepare GPU shader disk cache directory. |
| 742 | if let Some(cache_dir) = cfg |
| 743 | .gpu_parameters |
| 744 | .as_ref() |
| 745 | .and_then(|params| params.cache_path.as_ref()) |
| 746 | { |
| 747 | if cfg!(any(target_arch = "arm", target_arch = "aarch64")) && cfg.sandbox { |
| 748 | warn!("shader caching not yet supported on ARM with sandbox enabled"); |
| 749 | env::set_var("MESA_GLSL_CACHE_DISABLE", "true"); |
| 750 | } else { |
| 751 | env::set_var("MESA_GLSL_CACHE_DIR", cache_dir); |
| 752 | if let Some(cache_size) = cfg |
| 753 | .gpu_parameters |
| 754 | .as_ref() |
| 755 | .and_then(|params| params.cache_size.as_ref()) |
| 756 | { |
| 757 | env::set_var("MESA_GLSL_CACHE_MAX_SIZE", cache_size); |
| 758 | } |
| 759 | let shadercache_path = Path::new(cache_dir); |
| 760 | jail.mount_bind(shadercache_path, shadercache_path, true)?; |
| 761 | } |
| 762 | } |
| 763 | |
David Riley | 06787c5 | 2019-07-24 12:09:07 -0700 | [diff] [blame] | 764 | // If the ARM specific devices exist on the host, bind mount them in. |
| 765 | let mali0_path = Path::new("/dev/mali0"); |
| 766 | if mali0_path.exists() { |
| 767 | jail.mount_bind(mali0_path, mali0_path, true)?; |
| 768 | } |
| 769 | |
| 770 | let pvr_sync_path = Path::new("/dev/pvr_sync"); |
| 771 | if pvr_sync_path.exists() { |
| 772 | jail.mount_bind(pvr_sync_path, pvr_sync_path, true)?; |
| 773 | } |
| 774 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 775 | // Libraries that are required when mesa drivers are dynamically loaded. |
David Riley | 06787c5 | 2019-07-24 12:09:07 -0700 | [diff] [blame] | 776 | let lib_dirs = &["/usr/lib", "/usr/lib64", "/lib", "/lib64"]; |
| 777 | for dir in lib_dirs { |
| 778 | let dir_path = Path::new(dir); |
| 779 | if dir_path.exists() { |
| 780 | jail.mount_bind(dir_path, dir_path, false)?; |
| 781 | } |
| 782 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 783 | |
| 784 | // Bind mount the wayland socket into jail's root. This is necessary since each |
| 785 | // new wayland context must open() the socket. |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 786 | if let Some(path) = wayland_socket_path { |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 787 | jail.mount_bind(path, jailed_wayland_path, true)?; |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 788 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 789 | |
| 790 | add_crosvm_user_to_jail(&mut jail, "gpu")?; |
| 791 | |
David Riley | 54e660b | 2019-07-24 17:22:50 -0700 | [diff] [blame] | 792 | // pvr driver requires read access to /proc/self/task/*/comm. |
| 793 | let proc_path = Path::new("/proc"); |
| 794 | jail.mount( |
| 795 | proc_path, |
| 796 | proc_path, |
| 797 | "proc", |
| 798 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RDONLY) as usize, |
| 799 | )?; |
| 800 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 801 | Some(jail) |
| 802 | } |
| 803 | None => None, |
| 804 | }; |
| 805 | |
| 806 | Ok(VirtioDeviceStub { |
| 807 | dev: Box::new(dev), |
| 808 | jail, |
| 809 | }) |
| 810 | } |
| 811 | |
| 812 | fn create_wayland_device( |
| 813 | cfg: &Config, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 814 | socket: VmMemoryControlRequestSocket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 815 | resource_bridge: Option<virtio::resource_bridge::ResourceRequestSocket>, |
| 816 | ) -> DeviceResult { |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 817 | let wayland_socket_dirs = cfg |
| 818 | .wayland_socket_paths |
| 819 | .iter() |
| 820 | .map(|(_name, path)| path.parent()) |
| 821 | .collect::<Option<Vec<_>>>() |
| 822 | .ok_or(Error::InvalidWaylandPath)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 823 | |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 824 | let dev = virtio::Wl::new(cfg.wayland_socket_paths.clone(), socket, resource_bridge) |
| 825 | .map_err(Error::WaylandDeviceNew)?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 826 | |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 827 | let jail = match simple_jail(&cfg, "wl_device")? { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 828 | Some(mut jail) => { |
| 829 | // Create a tmpfs in the device's root directory so that we can bind mount the wayland |
| 830 | // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. |
| 831 | jail.mount_with_data( |
| 832 | Path::new("none"), |
| 833 | Path::new("/"), |
| 834 | "tmpfs", |
| 835 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 836 | "size=67108864", |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 837 | )?; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 838 | |
| 839 | // Bind mount the wayland socket's directory into jail's root. This is necessary since |
| 840 | // each new wayland context must open() the socket. If the wayland socket is ever |
| 841 | // destroyed and remade in the same host directory, new connections will be possible |
| 842 | // without restarting the wayland device. |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 843 | for dir in &wayland_socket_dirs { |
| 844 | jail.mount_bind(dir, dir, true)?; |
| 845 | } |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 846 | add_crosvm_user_to_jail(&mut jail, "Wayland")?; |
| 847 | |
| 848 | Some(jail) |
| 849 | } |
| 850 | None => None, |
| 851 | }; |
| 852 | |
| 853 | Ok(VirtioDeviceStub { |
| 854 | dev: Box::new(dev), |
| 855 | jail, |
| 856 | }) |
| 857 | } |
| 858 | |
Keiichi Watanabe | 57df6a0 | 2019-12-06 22:24:40 +0900 | [diff] [blame] | 859 | #[cfg(any(feature = "video-decoder", feature = "video-encoder"))] |
| 860 | fn create_video_device( |
| 861 | cfg: &Config, |
| 862 | typ: devices::virtio::VideoDeviceType, |
| 863 | resource_bridge: virtio::resource_bridge::ResourceRequestSocket, |
| 864 | ) -> DeviceResult { |
| 865 | let jail = match simple_jail(&cfg, "video_device")? { |
| 866 | Some(mut jail) => { |
| 867 | match typ { |
| 868 | devices::virtio::VideoDeviceType::Decoder => { |
| 869 | add_crosvm_user_to_jail(&mut jail, "video-decoder")? |
| 870 | } |
| 871 | devices::virtio::VideoDeviceType::Encoder => { |
| 872 | add_crosvm_user_to_jail(&mut jail, "video-encoder")? |
| 873 | } |
| 874 | }; |
| 875 | |
| 876 | // Create a tmpfs in the device's root directory so that we can bind mount files. |
| 877 | jail.mount_with_data( |
| 878 | Path::new("none"), |
| 879 | Path::new("/"), |
| 880 | "tmpfs", |
| 881 | (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, |
| 882 | "size=67108864", |
| 883 | )?; |
| 884 | |
| 885 | // Render node for libvda. |
| 886 | let dev_dri_path = Path::new("/dev/dri/renderD128"); |
| 887 | jail.mount_bind(dev_dri_path, dev_dri_path, false)?; |
| 888 | |
| 889 | // Device nodes required by libchrome which establishes Mojo connection in libvda. |
| 890 | let dev_urandom_path = Path::new("/dev/urandom"); |
| 891 | jail.mount_bind(dev_urandom_path, dev_urandom_path, false)?; |
| 892 | let system_bus_socket_path = Path::new("/run/dbus/system_bus_socket"); |
| 893 | jail.mount_bind(system_bus_socket_path, system_bus_socket_path, true)?; |
| 894 | |
| 895 | Some(jail) |
| 896 | } |
| 897 | None => None, |
| 898 | }; |
| 899 | |
| 900 | Ok(VirtioDeviceStub { |
| 901 | dev: Box::new(devices::virtio::VideoDevice::new( |
| 902 | typ, |
| 903 | Some(resource_bridge), |
| 904 | )), |
| 905 | jail, |
| 906 | }) |
| 907 | } |
| 908 | |
| 909 | #[cfg(any(feature = "video-decoder", feature = "video-encoder"))] |
| 910 | fn register_video_device( |
| 911 | devs: &mut Vec<VirtioDeviceStub>, |
| 912 | resource_bridges: &mut Vec<virtio::resource_bridge::ResourceResponseSocket>, |
| 913 | cfg: &Config, |
| 914 | typ: devices::virtio::VideoDeviceType, |
| 915 | ) -> std::result::Result<(), Error> { |
| 916 | let (video_socket, gpu_socket) = |
| 917 | virtio::resource_bridge::pair().map_err(Error::CreateSocket)?; |
| 918 | resource_bridges.push(gpu_socket); |
| 919 | devs.push(create_video_device(cfg, typ, video_socket)?); |
| 920 | Ok(()) |
| 921 | } |
| 922 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 923 | fn create_vhost_vsock_device(cfg: &Config, cid: u64, mem: &GuestMemory) -> DeviceResult { |
| 924 | let dev = virtio::vhost::Vsock::new(cid, mem).map_err(Error::VhostVsockDeviceNew)?; |
| 925 | |
| 926 | Ok(VirtioDeviceStub { |
| 927 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 928 | jail: simple_jail(&cfg, "vhost_vsock_device")?, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 929 | }) |
| 930 | } |
| 931 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 932 | fn create_fs_device( |
| 933 | cfg: &Config, |
| 934 | uid_map: &str, |
| 935 | gid_map: &str, |
| 936 | src: &Path, |
| 937 | tag: &str, |
| 938 | fs_cfg: virtio::fs::passthrough::Config, |
| 939 | ) -> DeviceResult { |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 940 | let max_open_files = get_max_open_files()?; |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 941 | let j = if cfg.sandbox { |
| 942 | let seccomp_policy = cfg.seccomp_policy_dir.join("fs_device"); |
| 943 | let config = SandboxConfig { |
| 944 | limit_caps: false, |
| 945 | uid_map: Some(uid_map), |
| 946 | gid_map: Some(gid_map), |
| 947 | log_failures: cfg.seccomp_log_failures, |
| 948 | seccomp_policy: &seccomp_policy, |
| 949 | }; |
Chirantan Ekbote | 34d45e5 | 2020-04-20 18:15:02 +0900 | [diff] [blame] | 950 | let mut jail = create_base_minijail(src, Some(max_open_files), Some(&config))?; |
| 951 | // We want bind mounts from the parent namespaces to propagate into the fs device's |
| 952 | // namespace. |
| 953 | jail.set_remount_mode(libc::MS_SLAVE); |
| 954 | |
| 955 | jail |
Matt Delco | c24ad78 | 2020-02-14 13:24:36 -0800 | [diff] [blame] | 956 | } else { |
| 957 | create_base_minijail(src, Some(max_open_files), None)? |
| 958 | }; |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 959 | |
| 960 | // TODO(chirantan): Use more than one worker once the kernel driver has been fixed to not panic |
| 961 | // when num_queues > 1. |
| 962 | let dev = virtio::fs::Fs::new(tag, 1, fs_cfg).map_err(Error::FsDeviceNew)?; |
| 963 | |
| 964 | Ok(VirtioDeviceStub { |
| 965 | dev: Box::new(dev), |
| 966 | jail: Some(j), |
| 967 | }) |
| 968 | } |
| 969 | |
Chirantan Ekbote | c6b73e3 | 2020-02-20 15:53:06 +0900 | [diff] [blame] | 970 | fn create_9p_device( |
| 971 | cfg: &Config, |
| 972 | uid_map: &str, |
| 973 | gid_map: &str, |
| 974 | src: &Path, |
| 975 | tag: &str, |
| 976 | ) -> DeviceResult { |
| 977 | let max_open_files = get_max_open_files()?; |
| 978 | let (jail, root) = if cfg.sandbox { |
| 979 | let seccomp_policy = cfg.seccomp_policy_dir.join("9p_device"); |
| 980 | let config = SandboxConfig { |
| 981 | limit_caps: false, |
| 982 | uid_map: Some(uid_map), |
| 983 | gid_map: Some(gid_map), |
| 984 | log_failures: cfg.seccomp_log_failures, |
| 985 | seccomp_policy: &seccomp_policy, |
| 986 | }; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 987 | |
Chirantan Ekbote | c6b73e3 | 2020-02-20 15:53:06 +0900 | [diff] [blame] | 988 | let mut jail = create_base_minijail(src, Some(max_open_files), Some(&config))?; |
| 989 | // We want bind mounts from the parent namespaces to propagate into the 9p server's |
| 990 | // namespace. |
| 991 | jail.set_remount_mode(libc::MS_SLAVE); |
Chirantan Ekbote | 055de38 | 2020-01-24 12:16:58 +0900 | [diff] [blame] | 992 | |
Chirantan Ekbote | c6b73e3 | 2020-02-20 15:53:06 +0900 | [diff] [blame] | 993 | // The shared directory becomes the root of the device's file system. |
| 994 | let root = Path::new("/"); |
| 995 | (Some(jail), root) |
| 996 | } else { |
| 997 | // There's no mount namespace so we tell the server to treat the source directory as the |
| 998 | // root. |
| 999 | (None, src) |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1000 | }; |
| 1001 | |
| 1002 | let dev = virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?; |
| 1003 | |
| 1004 | Ok(VirtioDeviceStub { |
| 1005 | dev: Box::new(dev), |
| 1006 | jail, |
| 1007 | }) |
| 1008 | } |
| 1009 | |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1010 | fn create_pmem_device( |
| 1011 | cfg: &Config, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1012 | vm: &mut impl Vm, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1013 | resources: &mut SystemAllocator, |
| 1014 | disk: &DiskOption, |
| 1015 | index: usize, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1016 | pmem_device_socket: VmMsyncRequestSocket, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1017 | ) -> DeviceResult { |
| 1018 | let fd = OpenOptions::new() |
| 1019 | .read(true) |
| 1020 | .write(!disk.read_only) |
| 1021 | .open(&disk.path) |
Daniel Verkamp | 46d61ba | 2020-02-25 10:17:50 -0800 | [diff] [blame] | 1022 | .map_err(|e| Error::Disk(disk.path.to_path_buf(), e))?; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1023 | |
Iliyan Malchev | ed14986 | 2020-04-17 23:57:47 +0000 | [diff] [blame] | 1024 | let arena_size = { |
Daniel Verkamp | 46d61ba | 2020-02-25 10:17:50 -0800 | [diff] [blame] | 1025 | let metadata = |
| 1026 | std::fs::metadata(&disk.path).map_err(|e| Error::Disk(disk.path.to_path_buf(), e))?; |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1027 | let disk_len = metadata.len(); |
| 1028 | // Linux requires pmem region sizes to be 2 MiB aligned. Linux will fill any partial page |
| 1029 | // at the end of an mmap'd file and won't write back beyond the actual file length, but if |
| 1030 | // we just align the size of the file to 2 MiB then access beyond the last page of the |
| 1031 | // mapped file will generate SIGBUS. So use a memory mapping arena that will provide |
| 1032 | // padding up to 2 MiB. |
| 1033 | let alignment = 2 * 1024 * 1024; |
| 1034 | let align_adjust = if disk_len % alignment != 0 { |
| 1035 | alignment - (disk_len % alignment) |
| 1036 | } else { |
| 1037 | 0 |
| 1038 | }; |
Iliyan Malchev | ed14986 | 2020-04-17 23:57:47 +0000 | [diff] [blame] | 1039 | disk_len |
| 1040 | .checked_add(align_adjust) |
| 1041 | .ok_or(Error::PmemDeviceImageTooBig)? |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1042 | }; |
| 1043 | |
| 1044 | let protection = { |
| 1045 | if disk.read_only { |
| 1046 | Protection::read() |
| 1047 | } else { |
| 1048 | Protection::read_write() |
| 1049 | } |
| 1050 | }; |
| 1051 | |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1052 | let arena = { |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1053 | // Conversion from u64 to usize may fail on 32bit system. |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1054 | let arena_size = usize::try_from(arena_size).map_err(|_| Error::PmemDeviceImageTooBig)?; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1055 | |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1056 | let mut arena = MemoryMappingArena::new(arena_size).map_err(Error::ReservePmemMemory)?; |
| 1057 | arena |
Iliyan Malchev | ed14986 | 2020-04-17 23:57:47 +0000 | [diff] [blame] | 1058 | .add_fd_offset_protection(0, arena_size, &fd, 0, protection) |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1059 | .map_err(Error::ReservePmemMemory)?; |
| 1060 | arena |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1061 | }; |
| 1062 | |
| 1063 | let mapping_address = resources |
Xiong Zhang | 383b3b5 | 2019-10-30 14:59:26 +0800 | [diff] [blame] | 1064 | .mmio_allocator(MmioType::High) |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1065 | .allocate_with_align( |
Stephen Barber | dc7c07b | 2019-12-20 12:43:35 -0800 | [diff] [blame] | 1066 | arena_size, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1067 | Alloc::PmemDevice(index), |
| 1068 | format!("pmem_disk_image_{}", index), |
| 1069 | // Linux kernel requires pmem namespaces to be 128 MiB aligned. |
| 1070 | 128 * 1024 * 1024, /* 128 MiB */ |
| 1071 | ) |
| 1072 | .map_err(Error::AllocatePmemDeviceAddress)?; |
| 1073 | |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1074 | let slot = vm |
Gurchetan Singh | 173fe62 | 2020-05-21 18:05:06 -0700 | [diff] [blame] | 1075 | .add_memory_region( |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1076 | GuestAddress(mapping_address), |
Gurchetan Singh | 173fe62 | 2020-05-21 18:05:06 -0700 | [diff] [blame] | 1077 | Box::new(arena), |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1078 | /* read_only = */ disk.read_only, |
| 1079 | /* log_dirty_pages = */ false, |
| 1080 | ) |
| 1081 | .map_err(Error::AddPmemDeviceMemory)?; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1082 | |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1083 | let dev = virtio::Pmem::new( |
| 1084 | fd, |
| 1085 | GuestAddress(mapping_address), |
| 1086 | slot, |
| 1087 | arena_size, |
| 1088 | Some(pmem_device_socket), |
| 1089 | ) |
| 1090 | .map_err(Error::PmemDeviceNew)?; |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1091 | |
| 1092 | Ok(VirtioDeviceStub { |
| 1093 | dev: Box::new(dev) as Box<dyn VirtioDevice>, |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 1094 | jail: simple_jail(&cfg, "pmem_device")?, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1095 | }) |
| 1096 | } |
| 1097 | |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 1098 | fn create_console_device(cfg: &Config, param: &SerialParameters) -> DeviceResult { |
| 1099 | let mut keep_fds = Vec::new(); |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 1100 | let evt = Event::new().map_err(Error::CreateEvent)?; |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 1101 | let dev = param |
| 1102 | .create_serial_device::<Console>(&evt, &mut keep_fds) |
| 1103 | .map_err(Error::CreateConsole)?; |
| 1104 | |
Nicholas Verne | 71e73d8 | 2020-07-08 17:19:55 +1000 | [diff] [blame] | 1105 | let jail = match simple_jail(&cfg, "serial")? { |
| 1106 | Some(mut jail) => { |
| 1107 | // Create a tmpfs in the device's root directory so that we can bind mount the |
| 1108 | // log socket directory into it. |
| 1109 | // The size=67108864 is size=64*1024*1024 or size=64MB. |
| 1110 | jail.mount_with_data( |
| 1111 | Path::new("none"), |
| 1112 | Path::new("/"), |
| 1113 | "tmpfs", |
| 1114 | (libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_NOSUID) as usize, |
| 1115 | "size=67108864", |
| 1116 | )?; |
| 1117 | add_crosvm_user_to_jail(&mut jail, "serial")?; |
| 1118 | let res = param.add_bind_mounts(&mut jail); |
| 1119 | if res.is_err() { |
| 1120 | error!("failed to add bind mounts for console device"); |
| 1121 | } |
| 1122 | Some(jail) |
| 1123 | } |
| 1124 | None => None, |
| 1125 | }; |
| 1126 | |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 1127 | Ok(VirtioDeviceStub { |
| 1128 | dev: Box::new(dev), |
Nicholas Verne | 71e73d8 | 2020-07-08 17:19:55 +1000 | [diff] [blame] | 1129 | jail, // TODO(dverkamp): use a separate policy for console? |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 1130 | }) |
| 1131 | } |
| 1132 | |
Dmitry Torokhov | ee42b8c | 2019-05-27 11:14:20 -0700 | [diff] [blame] | 1133 | // gpu_device_socket is not used when GPU support is disabled. |
| 1134 | #[cfg_attr(not(feature = "gpu"), allow(unused_variables))] |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1135 | fn create_virtio_devices( |
| 1136 | cfg: &Config, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1137 | mem: &GuestMemory, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1138 | vm: &mut impl Vm, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1139 | resources: &mut SystemAllocator, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 1140 | _exit_evt: &Event, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1141 | wayland_device_socket: VmMemoryControlRequestSocket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1142 | gpu_device_socket: VmMemoryControlRequestSocket, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1143 | balloon_device_socket: BalloonControlResponseSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1144 | disk_device_sockets: &mut Vec<DiskControlResponseSocket>, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1145 | pmem_device_sockets: &mut Vec<VmMsyncRequestSocket>, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 1146 | map_request: Arc<Mutex<Option<ExternalMapping>>>, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1147 | ) -> DeviceResult<Vec<VirtioDeviceStub>> { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1148 | let mut devs = Vec::new(); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1149 | |
Daniel Verkamp | a7b6a1c | 2020-03-09 13:16:46 -0700 | [diff] [blame] | 1150 | for (_, param) in cfg |
| 1151 | .serial_parameters |
| 1152 | .iter() |
| 1153 | .filter(|(_k, v)| v.hardware == SerialHardware::VirtioConsole) |
| 1154 | { |
| 1155 | let dev = create_console_device(cfg, param)?; |
| 1156 | devs.push(dev); |
| 1157 | } |
| 1158 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1159 | for disk in &cfg.disks { |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1160 | let disk_device_socket = disk_device_sockets.remove(0); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1161 | devs.push(create_block_device(cfg, disk, disk_device_socket)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1162 | } |
| 1163 | |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1164 | for (index, pmem_disk) in cfg.pmem_devices.iter().enumerate() { |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1165 | let pmem_device_socket = pmem_device_sockets.remove(0); |
| 1166 | devs.push(create_pmem_device( |
| 1167 | cfg, |
| 1168 | vm, |
| 1169 | resources, |
| 1170 | pmem_disk, |
| 1171 | index, |
| 1172 | pmem_device_socket, |
| 1173 | )?); |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1174 | } |
| 1175 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1176 | devs.push(create_rng_device(cfg)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1177 | |
David Tolnay | de6b29a | 2018-12-20 11:49:46 -0800 | [diff] [blame] | 1178 | #[cfg(feature = "tpm")] |
| 1179 | { |
David Tolnay | 43f8e21 | 2019-02-13 17:28:16 -0800 | [diff] [blame] | 1180 | if cfg.software_tpm { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1181 | devs.push(create_tpm_device(cfg)?); |
David Tolnay | 43f8e21 | 2019-02-13 17:28:16 -0800 | [diff] [blame] | 1182 | } |
David Tolnay | de6b29a | 2018-12-20 11:49:46 -0800 | [diff] [blame] | 1183 | } |
| 1184 | |
Jorge E. Moreira | 99d3f08 | 2019-03-07 10:59:54 -0800 | [diff] [blame] | 1185 | if let Some(single_touch_spec) = &cfg.virtio_single_touch { |
| 1186 | devs.push(create_single_touch_device(cfg, single_touch_spec)?); |
| 1187 | } |
| 1188 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 1189 | if let Some(trackpad_spec) = &cfg.virtio_trackpad { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1190 | devs.push(create_trackpad_device(cfg, trackpad_spec)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1191 | } |
| 1192 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 1193 | if let Some(mouse_socket) = &cfg.virtio_mouse { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1194 | devs.push(create_mouse_device(cfg, mouse_socket)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1195 | } |
| 1196 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 1197 | if let Some(keyboard_socket) = &cfg.virtio_keyboard { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1198 | devs.push(create_keyboard_device(cfg, keyboard_socket)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1199 | } |
| 1200 | |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 1201 | for dev_path in &cfg.virtio_input_evdevs { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1202 | devs.push(create_vinput_device(cfg, dev_path)?); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1203 | } |
| 1204 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1205 | devs.push(create_balloon_device(cfg, balloon_device_socket)?); |
Dylan Reid | 295ccac | 2017-11-06 14:06:24 -0800 | [diff] [blame] | 1206 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1207 | // We checked above that if the IP is defined, then the netmask is, too. |
Jianxun Zhang | 8f4d768 | 2019-02-21 12:55:31 -0800 | [diff] [blame] | 1208 | for tap_fd in &cfg.tap_fd { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1209 | devs.push(create_tap_net_device(cfg, *tap_fd)?); |
Jorge E. Moreira | b795280 | 2019-02-12 16:43:05 -0800 | [diff] [blame] | 1210 | } |
| 1211 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1212 | if let (Some(host_ip), Some(netmask), Some(mac_address)) = |
| 1213 | (cfg.host_ip, cfg.netmask, cfg.mac_address) |
| 1214 | { |
| 1215 | devs.push(create_net_device(cfg, host_ip, netmask, mac_address, mem)?); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1216 | } |
| 1217 | |
David Tolnay | fa70171 | 2019-02-13 16:42:54 -0800 | [diff] [blame] | 1218 | #[cfg_attr(not(feature = "gpu"), allow(unused_mut))] |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 1219 | let mut resource_bridges = Vec::<virtio::resource_bridge::ResourceResponseSocket>::new(); |
| 1220 | |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 1221 | if !cfg.wayland_socket_paths.is_empty() { |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 1222 | #[cfg_attr(not(feature = "gpu"), allow(unused_mut))] |
| 1223 | let mut wl_resource_bridge = None::<virtio::resource_bridge::ResourceRequestSocket>; |
| 1224 | |
| 1225 | #[cfg(feature = "gpu")] |
| 1226 | { |
Jason Macnak | cc7070b | 2019-11-06 14:48:12 -0800 | [diff] [blame] | 1227 | if cfg.gpu_parameters.is_some() { |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 1228 | let (wl_socket, gpu_socket) = |
| 1229 | virtio::resource_bridge::pair().map_err(Error::CreateSocket)?; |
| 1230 | resource_bridges.push(gpu_socket); |
| 1231 | wl_resource_bridge = Some(wl_socket); |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | devs.push(create_wayland_device( |
| 1236 | cfg, |
Chirantan Ekbote | dd11d43 | 2019-06-11 21:50:46 +0900 | [diff] [blame] | 1237 | wayland_device_socket, |
| 1238 | wl_resource_bridge, |
| 1239 | )?); |
| 1240 | } |
David Tolnay | fa70171 | 2019-02-13 16:42:54 -0800 | [diff] [blame] | 1241 | |
Keiichi Watanabe | 57df6a0 | 2019-12-06 22:24:40 +0900 | [diff] [blame] | 1242 | #[cfg(feature = "video-decoder")] |
| 1243 | { |
| 1244 | if cfg.video_dec { |
| 1245 | register_video_device( |
| 1246 | &mut devs, |
| 1247 | &mut resource_bridges, |
| 1248 | cfg, |
| 1249 | devices::virtio::VideoDeviceType::Decoder, |
| 1250 | )?; |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | #[cfg(feature = "video-encoder")] |
| 1255 | { |
| 1256 | if cfg.video_enc { |
| 1257 | register_video_device( |
| 1258 | &mut devs, |
| 1259 | &mut resource_bridges, |
| 1260 | cfg, |
| 1261 | devices::virtio::VideoDeviceType::Encoder, |
| 1262 | )?; |
| 1263 | } |
| 1264 | } |
| 1265 | |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 1266 | #[cfg(feature = "gpu")] |
| 1267 | { |
Noah Gold | dc7f52b | 2020-02-01 13:01:58 -0800 | [diff] [blame] | 1268 | if let Some(gpu_parameters) = &cfg.gpu_parameters { |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1269 | let mut event_devices = Vec::new(); |
| 1270 | if cfg.display_window_mouse { |
| 1271 | let (event_device_socket, virtio_dev_socket) = |
| 1272 | UnixStream::pair().map_err(Error::CreateSocket)?; |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 1273 | let (single_touch_width, single_touch_height) = cfg |
| 1274 | .virtio_single_touch |
| 1275 | .as_ref() |
| 1276 | .map(|single_touch_spec| single_touch_spec.get_size()) |
Noah Gold | dc7f52b | 2020-02-01 13:01:58 -0800 | [diff] [blame] | 1277 | .unwrap_or((gpu_parameters.display_width, gpu_parameters.display_height)); |
Kaiyi Li | bccb4eb | 2020-02-06 17:53:11 -0800 | [diff] [blame] | 1278 | let dev = virtio::new_single_touch( |
| 1279 | virtio_dev_socket, |
| 1280 | single_touch_width, |
| 1281 | single_touch_height, |
| 1282 | ) |
| 1283 | .map_err(Error::InputDeviceNew)?; |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1284 | devs.push(VirtioDeviceStub { |
| 1285 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 1286 | jail: simple_jail(&cfg, "input_device")?, |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1287 | }); |
| 1288 | event_devices.push(EventDevice::touchscreen(event_device_socket)); |
| 1289 | } |
| 1290 | if cfg.display_window_keyboard { |
| 1291 | let (event_device_socket, virtio_dev_socket) = |
| 1292 | UnixStream::pair().map_err(Error::CreateSocket)?; |
| 1293 | let dev = virtio::new_keyboard(virtio_dev_socket).map_err(Error::InputDeviceNew)?; |
| 1294 | devs.push(VirtioDeviceStub { |
| 1295 | dev: Box::new(dev), |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 1296 | jail: simple_jail(&cfg, "input_device")?, |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1297 | }); |
| 1298 | event_devices.push(EventDevice::keyboard(event_device_socket)); |
| 1299 | } |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 1300 | devs.push(create_gpu_device( |
| 1301 | cfg, |
| 1302 | _exit_evt, |
| 1303 | gpu_device_socket, |
| 1304 | resource_bridges, |
Ryo Hashimoto | 0b788de | 2019-12-10 17:14:13 +0900 | [diff] [blame] | 1305 | // Use the unnamed socket for GPU display screens. |
| 1306 | cfg.wayland_socket_paths.get(""), |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 1307 | cfg.x_display.clone(), |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1308 | event_devices, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 1309 | map_request, |
Zach Reizner | 0f2cfb0 | 2019-06-19 17:46:03 -0700 | [diff] [blame] | 1310 | )?); |
Zach Reizner | 3a8100a | 2017-09-13 19:15:43 -0700 | [diff] [blame] | 1311 | } |
| 1312 | } |
| 1313 | |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 1314 | if let Some(cid) = cfg.cid { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1315 | devs.push(create_vhost_vsock_device(cfg, cid, mem)?); |
Zach Reizner | aa57566 | 2018-08-15 10:46:32 -0700 | [diff] [blame] | 1316 | } |
| 1317 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 1318 | for shared_dir in &cfg.shared_dirs { |
| 1319 | let SharedDir { |
| 1320 | src, |
| 1321 | tag, |
| 1322 | kind, |
| 1323 | uid_map, |
| 1324 | gid_map, |
| 1325 | cfg: fs_cfg, |
| 1326 | } = shared_dir; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1327 | |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 1328 | let dev = match kind { |
| 1329 | SharedDirKind::FS => create_fs_device(cfg, uid_map, gid_map, src, tag, fs_cfg.clone())?, |
Chirantan Ekbote | c6b73e3 | 2020-02-20 15:53:06 +0900 | [diff] [blame] | 1330 | SharedDirKind::P9 => create_9p_device(cfg, uid_map, gid_map, src, tag)?, |
Chirantan Ekbote | bd4723b | 2019-07-17 10:50:30 +0900 | [diff] [blame] | 1331 | }; |
| 1332 | devs.push(dev); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1333 | } |
| 1334 | |
| 1335 | Ok(devs) |
| 1336 | } |
| 1337 | |
| 1338 | fn create_devices( |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1339 | cfg: &Config, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1340 | mem: &GuestMemory, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1341 | vm: &mut impl Vm, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1342 | resources: &mut SystemAllocator, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 1343 | exit_evt: &Event, |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 1344 | control_sockets: &mut Vec<TaggedControlSocket>, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1345 | wayland_device_socket: VmMemoryControlRequestSocket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1346 | gpu_device_socket: VmMemoryControlRequestSocket, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 1347 | balloon_device_socket: BalloonControlResponseSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1348 | disk_device_sockets: &mut Vec<DiskControlResponseSocket>, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1349 | pmem_device_sockets: &mut Vec<VmMsyncRequestSocket>, |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1350 | usb_provider: HostBackendDeviceProvider, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 1351 | map_request: Arc<Mutex<Option<ExternalMapping>>>, |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 1352 | ) -> DeviceResult<Vec<(Box<dyn PciDevice>, Option<Minijail>)>> { |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1353 | let stubs = create_virtio_devices( |
| 1354 | &cfg, |
| 1355 | mem, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1356 | vm, |
| 1357 | resources, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1358 | exit_evt, |
| 1359 | wayland_device_socket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1360 | gpu_device_socket, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1361 | balloon_device_socket, |
| 1362 | disk_device_sockets, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1363 | pmem_device_sockets, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 1364 | map_request, |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1365 | )?; |
| 1366 | |
| 1367 | let mut pci_devices = Vec::new(); |
| 1368 | |
| 1369 | for stub in stubs { |
Daniel Verkamp | bb712d6 | 2019-11-19 09:47:33 -0800 | [diff] [blame] | 1370 | let (msi_host_socket, msi_device_socket) = |
| 1371 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
| 1372 | control_sockets.push(TaggedControlSocket::VmIrq(msi_host_socket)); |
| 1373 | let dev = VirtioPciDevice::new(mem.clone(), stub.dev, msi_device_socket) |
| 1374 | .map_err(Error::VirtioPciDev)?; |
David Tolnay | fdac5ed | 2019-03-08 16:56:14 -0800 | [diff] [blame] | 1375 | let dev = Box::new(dev) as Box<dyn PciDevice>; |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1376 | pci_devices.push((dev, stub.jail)); |
| 1377 | } |
| 1378 | |
Andrew Scull | 1590e6f | 2020-03-18 18:00:47 +0000 | [diff] [blame] | 1379 | #[cfg(feature = "audio")] |
Judy Hsiao | d5c1e96 | 2020-02-04 12:30:01 +0800 | [diff] [blame] | 1380 | for ac97_param in &cfg.ac97_parameters { |
| 1381 | let dev = Ac97Dev::try_new(mem.clone(), ac97_param.clone()).map_err(Error::CreateAc97)?; |
paulhsia | ce17e6e | 2020-08-28 18:37:45 +0800 | [diff] [blame] | 1382 | let jail = simple_jail(&cfg, dev.minijail_policy())?; |
| 1383 | pci_devices.push((Box::new(dev), jail)); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1384 | } |
Andrew Scull | 1590e6f | 2020-03-18 18:00:47 +0000 | [diff] [blame] | 1385 | |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1386 | // Create xhci controller. |
| 1387 | let usb_controller = Box::new(XhciController::new(mem.clone(), usb_provider)); |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 1388 | pci_devices.push((usb_controller, simple_jail(&cfg, "xhci")?)); |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1389 | |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1390 | if !cfg.vfio.is_empty() { |
Xiong Zhang | ea6cf66 | 2019-11-11 18:32:02 +0800 | [diff] [blame] | 1391 | let vfio_container = Arc::new(Mutex::new( |
| 1392 | VfioContainer::new().map_err(Error::CreateVfioDevice)?, |
| 1393 | )); |
| 1394 | |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1395 | for vfio_path in &cfg.vfio { |
Daniel Verkamp | 10154a9 | 2020-09-28 17:44:40 -0700 | [diff] [blame] | 1396 | // create MSI, MSI-X, and Mem request sockets for each vfio device |
| 1397 | let (vfio_host_socket_msi, vfio_device_socket_msi) = |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1398 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
Daniel Verkamp | 10154a9 | 2020-09-28 17:44:40 -0700 | [diff] [blame] | 1399 | control_sockets.push(TaggedControlSocket::VmIrq(vfio_host_socket_msi)); |
| 1400 | |
| 1401 | let (vfio_host_socket_msix, vfio_device_socket_msix) = |
| 1402 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
| 1403 | control_sockets.push(TaggedControlSocket::VmIrq(vfio_host_socket_msix)); |
Xiong Zhang | 4b5bb3a | 2019-04-23 17:15:21 +0800 | [diff] [blame] | 1404 | |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1405 | let (vfio_host_socket_mem, vfio_device_socket_mem) = |
| 1406 | msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>() |
| 1407 | .map_err(Error::CreateSocket)?; |
| 1408 | control_sockets.push(TaggedControlSocket::VmMemory(vfio_host_socket_mem)); |
Xiong Zhang | 85abeff | 2019-04-23 17:15:24 +0800 | [diff] [blame] | 1409 | |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1410 | let vfiodevice = VfioDevice::new(vfio_path.as_path(), vm, mem, vfio_container.clone()) |
| 1411 | .map_err(Error::CreateVfioDevice)?; |
| 1412 | let vfiopcidevice = Box::new(VfioPciDevice::new( |
| 1413 | vfiodevice, |
Daniel Verkamp | 10154a9 | 2020-09-28 17:44:40 -0700 | [diff] [blame] | 1414 | vfio_device_socket_msi, |
| 1415 | vfio_device_socket_msix, |
Xiong Zhang | 8bb4faa | 2019-11-12 10:06:13 +0800 | [diff] [blame] | 1416 | vfio_device_socket_mem, |
| 1417 | )); |
| 1418 | pci_devices.push((vfiopcidevice, simple_jail(&cfg, "vfio_device")?)); |
| 1419 | } |
Xiong Zhang | 17b0daf | 2019-04-23 17:14:50 +0800 | [diff] [blame] | 1420 | } |
| 1421 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1422 | Ok(pci_devices) |
| 1423 | } |
| 1424 | |
| 1425 | #[derive(Copy, Clone)] |
Chirantan Ekbote | 1a2683b | 2019-11-26 16:28:23 +0900 | [diff] [blame] | 1426 | #[cfg_attr(not(feature = "tpm"), allow(dead_code))] |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1427 | struct Ids { |
| 1428 | uid: uid_t, |
| 1429 | gid: gid_t, |
| 1430 | } |
| 1431 | |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1432 | // Set the uid/gid for the jailed process and give a basic id map. This is |
| 1433 | // required for bind mounts to work. |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1434 | fn add_crosvm_user_to_jail(jail: &mut Minijail, feature: &str) -> Result<Ids> { |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1435 | let crosvm_user_group = CStr::from_bytes_with_nul(b"crosvm\0").unwrap(); |
| 1436 | |
| 1437 | let crosvm_uid = match get_user_id(&crosvm_user_group) { |
| 1438 | Ok(u) => u, |
| 1439 | Err(e) => { |
| 1440 | warn!("falling back to current user id for {}: {}", feature, e); |
| 1441 | geteuid() |
| 1442 | } |
| 1443 | }; |
| 1444 | |
| 1445 | let crosvm_gid = match get_group_id(&crosvm_user_group) { |
| 1446 | Ok(u) => u, |
| 1447 | Err(e) => { |
| 1448 | warn!("falling back to current group id for {}: {}", feature, e); |
| 1449 | getegid() |
| 1450 | } |
| 1451 | }; |
| 1452 | |
| 1453 | jail.change_uid(crosvm_uid); |
| 1454 | jail.change_gid(crosvm_gid); |
| 1455 | jail.uidmap(&format!("{0} {0} 1", crosvm_uid)) |
| 1456 | .map_err(Error::SettingUidMap)?; |
| 1457 | jail.gidmap(&format!("{0} {0} 1", crosvm_gid)) |
| 1458 | .map_err(Error::SettingGidMap)?; |
| 1459 | |
David Tolnay | 41a6f84 | 2019-03-01 16:18:44 -0800 | [diff] [blame] | 1460 | Ok(Ids { |
| 1461 | uid: crosvm_uid, |
| 1462 | gid: crosvm_gid, |
| 1463 | }) |
David Tolnay | 48c4829 | 2019-03-01 16:54:25 -0800 | [diff] [blame] | 1464 | } |
| 1465 | |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1466 | fn raw_fd_from_path(path: &Path) -> Result<RawFd> { |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1467 | if !path.is_file() { |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1468 | return Err(Error::InvalidFdPath); |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1469 | } |
| 1470 | let raw_fd = path |
| 1471 | .file_name() |
| 1472 | .and_then(|fd_osstr| fd_osstr.to_str()) |
| 1473 | .and_then(|fd_str| fd_str.parse::<c_int>().ok()) |
| 1474 | .ok_or(Error::InvalidFdPath)?; |
David Tolnay | fd0971d | 2019-03-04 17:15:57 -0800 | [diff] [blame] | 1475 | validate_raw_fd(raw_fd).map_err(Error::ValidateRawFd) |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1476 | } |
| 1477 | |
Zach Reizner | 65b98f1 | 2019-11-22 17:34:58 -0800 | [diff] [blame] | 1478 | trait IntoUnixStream { |
| 1479 | fn into_unix_stream(self) -> Result<UnixStream>; |
| 1480 | } |
| 1481 | |
| 1482 | impl<'a> IntoUnixStream for &'a Path { |
| 1483 | fn into_unix_stream(self) -> Result<UnixStream> { |
| 1484 | if self.parent() == Some(Path::new("/proc/self/fd")) { |
| 1485 | // Safe because we will validate |raw_fd|. |
| 1486 | unsafe { Ok(UnixStream::from_raw_fd(raw_fd_from_path(self)?)) } |
| 1487 | } else { |
| 1488 | UnixStream::connect(self).map_err(Error::InputEventsOpen) |
| 1489 | } |
| 1490 | } |
| 1491 | } |
| 1492 | impl<'a> IntoUnixStream for &'a PathBuf { |
| 1493 | fn into_unix_stream(self) -> Result<UnixStream> { |
| 1494 | self.as_path().into_unix_stream() |
| 1495 | } |
| 1496 | } |
| 1497 | |
| 1498 | impl IntoUnixStream for UnixStream { |
| 1499 | fn into_unix_stream(self) -> Result<UnixStream> { |
| 1500 | Ok(self) |
Jorge E. Moreira | dffec50 | 2019-01-14 18:44:49 -0800 | [diff] [blame] | 1501 | } |
| 1502 | } |
| 1503 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1504 | fn setup_vcpu_signal_handler<T: Vcpu>(use_hypervisor_signals: bool) -> Result<()> { |
| 1505 | if use_hypervisor_signals { |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1506 | unsafe { |
| 1507 | extern "C" fn handle_signal() {} |
| 1508 | // Our signal handler does nothing and is trivially async signal safe. |
| 1509 | register_rt_signal_handler(SIGRTMIN() + 0, handle_signal) |
| 1510 | .map_err(Error::RegisterSignalHandler)?; |
| 1511 | } |
| 1512 | block_signal(SIGRTMIN() + 0).map_err(Error::BlockSignal)?; |
| 1513 | } else { |
| 1514 | unsafe { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1515 | extern "C" fn handle_signal<T: Vcpu>() { |
| 1516 | T::set_local_immediate_exit(true); |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1517 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1518 | register_rt_signal_handler(SIGRTMIN() + 0, handle_signal::<T>) |
Matt Delco | 84cf9c0 | 2019-10-07 22:38:13 -0700 | [diff] [blame] | 1519 | .map_err(Error::RegisterSignalHandler)?; |
| 1520 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1521 | } |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1522 | Ok(()) |
| 1523 | } |
| 1524 | |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1525 | #[derive(Default)] |
| 1526 | struct VcpuRunMode { |
| 1527 | mtx: Mutex<VmRunMode>, |
| 1528 | cvar: Condvar, |
| 1529 | } |
| 1530 | |
| 1531 | impl VcpuRunMode { |
| 1532 | fn set_and_notify(&self, new_mode: VmRunMode) { |
| 1533 | *self.mtx.lock() = new_mode; |
| 1534 | self.cvar.notify_all(); |
| 1535 | } |
| 1536 | } |
| 1537 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1538 | // Sets up a vcpu and converts it into a runnable vcpu. |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1539 | fn runnable_vcpu<V>( |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1540 | cpu_id: usize, |
| 1541 | vcpu: Option<V>, |
| 1542 | vm: impl VmArch<Vcpu = V>, |
| 1543 | irq_chip: &mut impl IrqChipArch<V>, |
| 1544 | vcpu_count: usize, |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 1545 | run_rt: bool, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1546 | vcpu_affinity: Vec<usize>, |
| 1547 | has_bios: bool, |
| 1548 | use_hypervisor_signals: bool, |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1549 | ) -> Result<(V, VcpuRunHandle)> |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1550 | where |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1551 | V: VcpuArch, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1552 | { |
| 1553 | let mut vcpu = if let Some(v) = vcpu { |
| 1554 | v |
| 1555 | } else { |
| 1556 | // If vcpu is None, it means this arch/hypervisor requires create_vcpu to be called from the |
| 1557 | // vcpu thread. |
| 1558 | vm.create_vcpu(cpu_id).map_err(Error::CreateVcpu)? |
| 1559 | }; |
Dylan Reid | bb30b2f | 2019-10-22 18:30:36 +0300 | [diff] [blame] | 1560 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1561 | irq_chip |
| 1562 | .add_vcpu(cpu_id, vcpu.try_clone().map_err(Error::CloneVcpu)?) |
| 1563 | .map_err(Error::AddIrqChipVcpu)?; |
| 1564 | |
Daniel Verkamp | caf9ced | 2020-09-29 15:35:02 -0700 | [diff] [blame] | 1565 | if !vcpu_affinity.is_empty() { |
| 1566 | if let Err(e) = set_cpu_affinity(vcpu_affinity) { |
| 1567 | error!("Failed to set CPU affinity: {}", e); |
| 1568 | } |
| 1569 | } |
| 1570 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1571 | Arch::configure_vcpu( |
| 1572 | vm.get_memory(), |
| 1573 | vm.get_hypervisor(), |
| 1574 | irq_chip, |
| 1575 | &mut vcpu, |
| 1576 | cpu_id, |
| 1577 | vcpu_count, |
| 1578 | has_bios, |
| 1579 | ) |
| 1580 | .map_err(Error::ConfigureVcpu)?; |
| 1581 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1582 | #[cfg(feature = "chromeos")] |
| 1583 | if let Err(e) = base::sched::enable_core_scheduling() { |
| 1584 | error!("Failed to enable core scheduling: {}", e); |
| 1585 | } |
| 1586 | |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 1587 | if run_rt { |
| 1588 | const DEFAULT_VCPU_RT_LEVEL: u16 = 6; |
| 1589 | if let Err(e) = set_rt_prio_limit(u64::from(DEFAULT_VCPU_RT_LEVEL)) |
| 1590 | .and_then(|_| set_rt_round_robin(i32::from(DEFAULT_VCPU_RT_LEVEL))) |
| 1591 | { |
| 1592 | warn!("Failed to set vcpu to real time: {}", e); |
| 1593 | } |
| 1594 | } |
| 1595 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1596 | if use_hypervisor_signals { |
| 1597 | let mut v = get_blocked_signals().map_err(Error::GetSignalMask)?; |
| 1598 | v.retain(|&x| x != SIGRTMIN() + 0); |
| 1599 | vcpu.set_signal_mask(&v).map_err(Error::SettingSignalMask)?; |
| 1600 | } |
| 1601 | |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1602 | let vcpu_run_handle = vcpu |
| 1603 | .take_run_handle(Some(SIGRTMIN() + 0)) |
| 1604 | .map_err(Error::RunnableVcpu)?; |
| 1605 | |
| 1606 | Ok((vcpu, vcpu_run_handle)) |
Dylan Reid | bb30b2f | 2019-10-22 18:30:36 +0300 | [diff] [blame] | 1607 | } |
| 1608 | |
Zhuocheng Ding | db4c70d | 2019-12-02 15:50:24 +0800 | [diff] [blame] | 1609 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1610 | fn inject_interrupt<T: VcpuX86_64>( |
| 1611 | irq_chip: &mut impl IrqChipX86_64<T>, |
| 1612 | vcpu: &impl VcpuX86_64, |
| 1613 | vcpu_id: usize, |
| 1614 | ) { |
| 1615 | if !irq_chip.interrupt_requested(vcpu_id) || !vcpu.ready_for_interrupt() { |
| 1616 | return; |
| 1617 | } |
| 1618 | |
| 1619 | let vector = irq_chip |
| 1620 | .get_external_interrupt(vcpu_id) |
| 1621 | .unwrap_or_else(|e| { |
| 1622 | error!("get_external_interrupt failed on vcpu {}: {}", vcpu_id, e); |
| 1623 | None |
| 1624 | }); |
| 1625 | if let Some(vector) = vector { |
| 1626 | if let Err(e) = vcpu.interrupt(vector as u32) { |
| 1627 | error!( |
| 1628 | "Failed to inject interrupt {} to vcpu {}: {}", |
| 1629 | vector, vcpu_id, e |
| 1630 | ); |
Zhuocheng Ding | db4c70d | 2019-12-02 15:50:24 +0800 | [diff] [blame] | 1631 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1632 | } |
| 1633 | |
| 1634 | // The second interrupt request should be handled immediately, so ask vCPU to exit as soon as |
| 1635 | // possible. |
| 1636 | if irq_chip.interrupt_requested(vcpu_id) { |
| 1637 | vcpu.request_interrupt_window(); |
Zhuocheng Ding | db4c70d | 2019-12-02 15:50:24 +0800 | [diff] [blame] | 1638 | } |
| 1639 | } |
| 1640 | |
| 1641 | #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1642 | fn inject_interrupt<T: Vcpu>(_irq_chip: &mut impl IrqChip<T>, _vcpu: &impl Vcpu, _vcpu_id: usize) {} |
Zhuocheng Ding | db4c70d | 2019-12-02 15:50:24 +0800 | [diff] [blame] | 1643 | |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1644 | fn run_vcpu<V>( |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1645 | cpu_id: usize, |
| 1646 | vcpu: Option<V>, |
| 1647 | vm: impl VmArch<Vcpu = V> + 'static, |
| 1648 | mut irq_chip: impl IrqChipArch<V> + 'static, |
| 1649 | vcpu_count: usize, |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 1650 | run_rt: bool, |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1651 | vcpu_affinity: Vec<usize>, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1652 | start_barrier: Arc<Barrier>, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1653 | has_bios: bool, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1654 | io_bus: devices::Bus, |
| 1655 | mmio_bus: devices::Bus, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 1656 | exit_evt: Event, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1657 | requires_pvclock_ctrl: bool, |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1658 | run_mode_arc: Arc<VcpuRunMode>, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1659 | use_hypervisor_signals: bool, |
| 1660 | ) -> Result<JoinHandle<()>> |
| 1661 | where |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1662 | V: VcpuArch + 'static, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1663 | { |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1664 | thread::Builder::new() |
| 1665 | .name(format!("crosvm_vcpu{}", cpu_id)) |
| 1666 | .spawn(move || { |
Zach Reizner | 9588531 | 2020-01-29 18:06:01 -0800 | [diff] [blame] | 1667 | // The VCPU thread must trigger the `exit_evt` in all paths, and a `ScopedEvent`'s Drop |
| 1668 | // implementation accomplishes that. |
| 1669 | let _scoped_exit_evt = ScopedEvent::from(exit_evt); |
| 1670 | |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1671 | let runnable_vcpu = runnable_vcpu( |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1672 | cpu_id, |
| 1673 | vcpu, |
| 1674 | vm, |
| 1675 | &mut irq_chip, |
| 1676 | vcpu_count, |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 1677 | run_rt, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1678 | vcpu_affinity, |
| 1679 | has_bios, |
| 1680 | use_hypervisor_signals, |
| 1681 | ); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1682 | |
Zach Reizner | 8fb5211 | 2017-12-13 16:04:39 -0800 | [diff] [blame] | 1683 | start_barrier.wait(); |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1684 | |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1685 | let (vcpu, vcpu_run_handle) = match runnable_vcpu { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1686 | Ok(v) => v, |
| 1687 | Err(e) => { |
| 1688 | error!("failed to start vcpu {}: {}", cpu_id, e); |
| 1689 | return; |
| 1690 | } |
| 1691 | }; |
Mark Ryan | 6ed5aea | 2018-04-20 13:52:35 +0100 | [diff] [blame] | 1692 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1693 | loop { |
| 1694 | let mut interrupted_by_signal = false; |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1695 | match vcpu.run(&vcpu_run_handle) { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1696 | Ok(VcpuExit::IoIn { port, mut size }) => { |
| 1697 | let mut data = [0; 8]; |
| 1698 | if size > data.len() { |
| 1699 | error!("unsupported IoIn size of {} bytes", size); |
| 1700 | size = data.len(); |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1701 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1702 | io_bus.read(port as u64, &mut data[..size]); |
| 1703 | if let Err(e) = vcpu.set_data(&data[..size]) { |
| 1704 | error!("failed to set return data for IoIn: {}", e); |
| 1705 | } |
| 1706 | } |
| 1707 | Ok(VcpuExit::IoOut { |
| 1708 | port, |
| 1709 | mut size, |
| 1710 | data, |
| 1711 | }) => { |
| 1712 | if size > data.len() { |
| 1713 | error!("unsupported IoOut size of {} bytes", size); |
| 1714 | size = data.len(); |
| 1715 | } |
| 1716 | io_bus.write(port as u64, &data[..size]); |
| 1717 | } |
| 1718 | Ok(VcpuExit::MmioRead { address, size }) => { |
| 1719 | let mut data = [0; 8]; |
| 1720 | mmio_bus.read(address, &mut data[..size]); |
| 1721 | // Setting data for mmio can not fail. |
| 1722 | let _ = vcpu.set_data(&data[..size]); |
| 1723 | } |
| 1724 | Ok(VcpuExit::MmioWrite { |
| 1725 | address, |
| 1726 | size, |
| 1727 | data, |
| 1728 | }) => { |
| 1729 | mmio_bus.write(address, &data[..size]); |
| 1730 | } |
| 1731 | Ok(VcpuExit::IoapicEoi { vector }) => { |
| 1732 | if let Err(e) = irq_chip.broadcast_eoi(vector) { |
| 1733 | error!( |
| 1734 | "failed to broadcast eoi {} on vcpu {}: {}", |
| 1735 | vector, cpu_id, e |
| 1736 | ); |
| 1737 | } |
| 1738 | } |
| 1739 | Ok(VcpuExit::Hlt) => break, |
| 1740 | Ok(VcpuExit::Shutdown) => break, |
| 1741 | Ok(VcpuExit::FailEntry { |
| 1742 | hardware_entry_failure_reason, |
| 1743 | }) => { |
| 1744 | error!("vcpu hw run failure: {:#x}", hardware_entry_failure_reason); |
| 1745 | break; |
| 1746 | } |
| 1747 | Ok(VcpuExit::SystemEvent(_, _)) => break, |
| 1748 | Ok(r) => warn!("unexpected vcpu exit: {:?}", r), |
| 1749 | Err(e) => match e.errno() { |
| 1750 | libc::EINTR => interrupted_by_signal = true, |
| 1751 | libc::EAGAIN => {} |
| 1752 | _ => { |
| 1753 | error!("vcpu hit unknown error: {}", e); |
| 1754 | break; |
| 1755 | } |
| 1756 | }, |
| 1757 | } |
| 1758 | |
| 1759 | if interrupted_by_signal { |
| 1760 | if use_hypervisor_signals { |
| 1761 | // Try to clear the signal that we use to kick VCPU if it is pending before |
| 1762 | // attempting to handle pause requests. |
| 1763 | if let Err(e) = clear_signal(SIGRTMIN() + 0) { |
| 1764 | error!("failed to clear pending signal: {}", e); |
| 1765 | break; |
| 1766 | } |
| 1767 | } else { |
| 1768 | vcpu.set_immediate_exit(false); |
| 1769 | } |
| 1770 | let mut run_mode_lock = run_mode_arc.mtx.lock(); |
| 1771 | loop { |
| 1772 | match *run_mode_lock { |
| 1773 | VmRunMode::Running => break, |
| 1774 | VmRunMode::Suspending => { |
| 1775 | // On KVM implementations that use a paravirtualized clock (e.g. |
| 1776 | // x86), a flag must be set to indicate to the guest kernel that a |
| 1777 | // VCPU was suspended. The guest kernel will use this flag to |
| 1778 | // prevent the soft lockup detection from triggering when this VCPU |
| 1779 | // resumes, which could happen days later in realtime. |
| 1780 | if requires_pvclock_ctrl { |
| 1781 | if let Err(e) = vcpu.pvclock_ctrl() { |
| 1782 | error!( |
| 1783 | "failed to tell hypervisor vcpu {} is suspending: {}", |
| 1784 | cpu_id, e |
| 1785 | ); |
Zach Reizner | 795355a | 2019-01-16 17:37:57 -0800 | [diff] [blame] | 1786 | } |
| 1787 | } |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1788 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1789 | VmRunMode::Exiting => return, |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 1790 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1791 | // Give ownership of our exclusive lock to the condition variable that will |
| 1792 | // block. When the condition variable is notified, `wait` will unblock and |
| 1793 | // return a new exclusive lock. |
| 1794 | run_mode_lock = run_mode_arc.cvar.wait(run_mode_lock); |
Zhuocheng Ding | db4c70d | 2019-12-02 15:50:24 +0800 | [diff] [blame] | 1795 | } |
David Tolnay | 8f3a232 | 2018-11-30 17:11:35 -0800 | [diff] [blame] | 1796 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1797 | |
Zach Reizner | 2c770e6 | 2020-09-30 16:49:59 -0700 | [diff] [blame] | 1798 | inject_interrupt(&mut irq_chip, &vcpu, cpu_id); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1799 | } |
David Tolnay | 2bac1e7 | 2018-12-12 14:33:42 -0800 | [diff] [blame] | 1800 | }) |
| 1801 | .map_err(Error::SpawnVcpu) |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 1802 | } |
| 1803 | |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 1804 | // Reads the contents of a file and converts the space-separated fields into a Vec of i64s. |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1805 | // Returns an error if any of the fields fail to parse. |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 1806 | fn file_fields_to_i64<P: AsRef<Path>>(path: P) -> io::Result<Vec<i64>> { |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1807 | let mut file = File::open(path)?; |
| 1808 | |
| 1809 | let mut buf = [0u8; 32]; |
| 1810 | let count = file.read(&mut buf)?; |
| 1811 | |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1812 | let content = |
| 1813 | str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; |
| 1814 | content |
| 1815 | .trim() |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1816 | .split_whitespace() |
| 1817 | .map(|x| { |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 1818 | x.parse::<i64>() |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1819 | .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) |
| 1820 | }) |
| 1821 | .collect() |
| 1822 | } |
| 1823 | |
| 1824 | // Reads the contents of a file and converts them into a u64, and if there |
| 1825 | // are multiple fields it only returns the first one. |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 1826 | fn file_to_i64<P: AsRef<Path>>(path: P) -> io::Result<i64> { |
| 1827 | file_fields_to_i64(path)? |
Sonny Rao | d5f6608 | 2019-04-24 12:24:38 -0700 | [diff] [blame] | 1828 | .into_iter() |
| 1829 | .next() |
| 1830 | .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "empty file")) |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 1831 | } |
| 1832 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1833 | fn create_kvm(mem: GuestMemory) -> base::Result<KvmVm> { |
| 1834 | let kvm = Kvm::new()?; |
| 1835 | let vm = KvmVm::new(&kvm, mem)?; |
| 1836 | Ok(vm) |
| 1837 | } |
| 1838 | |
| 1839 | fn create_kvm_kernel_irq_chip( |
| 1840 | vm: &KvmVm, |
| 1841 | vcpu_count: usize, |
| 1842 | _ioapic_device_socket: VmIrqRequestSocket, |
| 1843 | ) -> base::Result<impl IrqChipArch<KvmVcpu>> { |
| 1844 | let irq_chip = KvmKernelIrqChip::new(vm.try_clone()?, vcpu_count)?; |
| 1845 | Ok(irq_chip) |
| 1846 | } |
| 1847 | |
| 1848 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 1849 | fn create_kvm_split_irq_chip( |
| 1850 | vm: &KvmVm, |
| 1851 | vcpu_count: usize, |
| 1852 | ioapic_device_socket: VmIrqRequestSocket, |
| 1853 | ) -> base::Result<impl IrqChipArch<KvmVcpu>> { |
| 1854 | let irq_chip = KvmSplitIrqChip::new(vm.try_clone()?, vcpu_count, ioapic_device_socket)?; |
| 1855 | Ok(irq_chip) |
| 1856 | } |
| 1857 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1858 | pub fn run_config(cfg: Config) -> Result<()> { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 1859 | if cfg.split_irqchip { |
| 1860 | #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] |
| 1861 | { |
| 1862 | unimplemented!("KVM split irqchip mode only supported on x86 processors") |
| 1863 | } |
| 1864 | |
| 1865 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 1866 | { |
| 1867 | run_vm(cfg, create_kvm, create_kvm_split_irq_chip) |
| 1868 | } |
| 1869 | } else { |
| 1870 | run_vm(cfg, create_kvm, create_kvm_kernel_irq_chip) |
| 1871 | } |
| 1872 | } |
| 1873 | |
| 1874 | fn run_vm<V, I, FV, FI>(cfg: Config, create_vm: FV, create_irq_chip: FI) -> Result<()> |
| 1875 | where |
| 1876 | V: VmArch + 'static, |
| 1877 | I: IrqChipArch<V::Vcpu> + 'static, |
| 1878 | FV: FnOnce(GuestMemory) -> base::Result<V>, |
| 1879 | FI: FnOnce( |
| 1880 | &V, |
| 1881 | usize, // vcpu_count |
| 1882 | VmIrqRequestSocket, // ioapic_device_socket |
| 1883 | ) -> base::Result<I>, |
| 1884 | { |
Lepton Wu | 9105e9f | 2019-03-14 11:38:31 -0700 | [diff] [blame] | 1885 | if cfg.sandbox { |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1886 | // Printing something to the syslog before entering minijail so that libc's syslogger has a |
| 1887 | // chance to open files necessary for its operation, like `/etc/localtime`. After jailing, |
| 1888 | // access to those files will not be possible. |
| 1889 | info!("crosvm entering multiprocess mode"); |
| 1890 | } |
| 1891 | |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 1892 | let (usb_control_socket, usb_provider) = |
David Tolnay | 5fb3f51 | 2019-04-12 19:22:33 -0700 | [diff] [blame] | 1893 | HostBackendDeviceProvider::new().map_err(Error::CreateUsbProvider)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1894 | // Masking signals is inherently dangerous, since this can persist across clones/execs. Do this |
| 1895 | // before any jailed devices have been spawned, so that we can catch any of them that fail very |
| 1896 | // quickly. |
| 1897 | let sigchld_fd = SignalFd::new(libc::SIGCHLD).map_err(Error::CreateSignalFd)?; |
| 1898 | |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1899 | let initrd_image = if let Some(initrd_path) = &cfg.initrd_path { |
| 1900 | Some(File::open(initrd_path).map_err(|e| Error::OpenInitrd(initrd_path.clone(), e))?) |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 1901 | } else { |
| 1902 | None |
| 1903 | }; |
| 1904 | |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 1905 | let vm_image = match cfg.executable_path { |
| 1906 | Some(Executable::Kernel(ref kernel_path)) => VmImage::Kernel( |
| 1907 | File::open(kernel_path).map_err(|e| Error::OpenKernel(kernel_path.to_path_buf(), e))?, |
| 1908 | ), |
| 1909 | Some(Executable::Bios(ref bios_path)) => VmImage::Bios( |
| 1910 | File::open(bios_path).map_err(|e| Error::OpenBios(bios_path.to_path_buf(), e))?, |
| 1911 | ), |
| 1912 | _ => panic!("Did not receive a bios or kernel, should be impossible."), |
| 1913 | }; |
| 1914 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1915 | let components = VmComponents { |
Daniel Verkamp | 6a84706 | 2019-11-26 13:16:35 -0800 | [diff] [blame] | 1916 | memory_size: cfg |
| 1917 | .memory |
| 1918 | .unwrap_or(256) |
| 1919 | .checked_mul(1024 * 1024) |
| 1920 | .ok_or(Error::MemoryTooLarge)?, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1921 | vcpu_count: cfg.vcpu_count.unwrap_or(1), |
Daniel Verkamp | 107edb3 | 2019-04-05 09:58:48 -0700 | [diff] [blame] | 1922 | vcpu_affinity: cfg.vcpu_affinity.clone(), |
Cody Schuffelen | 6d1ab50 | 2019-05-21 12:12:38 -0700 | [diff] [blame] | 1923 | vm_image, |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 1924 | android_fstab: cfg |
| 1925 | .android_fstab |
| 1926 | .as_ref() |
David Tolnay | 2b089fc | 2019-03-04 15:33:22 -0800 | [diff] [blame] | 1927 | .map(|x| File::open(x).map_err(|e| Error::OpenAndroidFstab(x.to_path_buf(), e))) |
Tristan Muntsinger | 4133b01 | 2018-12-21 16:01:56 -0800 | [diff] [blame] | 1928 | .map_or(Ok(None), |v| v.map(Some))?, |
Kansho Nishida | 282115b | 2019-12-18 13:13:14 +0900 | [diff] [blame] | 1929 | pstore: cfg.pstore.clone(), |
Daniel Verkamp | e403f5c | 2018-12-11 16:29:26 -0800 | [diff] [blame] | 1930 | initrd_image, |
Daniel Verkamp | aac2813 | 2018-10-15 14:58:48 -0700 | [diff] [blame] | 1931 | extra_kernel_params: cfg.params.clone(), |
| 1932 | wayland_dmabuf: cfg.wayland_dmabuf, |
Tomasz Jeznach | 4264464 | 2020-05-20 23:27:59 -0700 | [diff] [blame] | 1933 | acpi_sdts: cfg |
| 1934 | .acpi_tables |
| 1935 | .iter() |
| 1936 | .map(|path| SDT::from_file(path).map_err(|e| Error::OpenAcpiTable(path.clone(), e))) |
| 1937 | .collect::<Result<Vec<SDT>>>()?, |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 1938 | rt_cpus: cfg.rt_cpus.clone(), |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1939 | }; |
| 1940 | |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1941 | let control_server_socket = match &cfg.socket_path { |
| 1942 | Some(path) => Some(UnlinkUnixSeqpacketListener( |
| 1943 | UnixSeqpacketListener::bind(path).map_err(Error::CreateSocket)?, |
| 1944 | )), |
| 1945 | None => None, |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1946 | }; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 1947 | |
| 1948 | let mut control_sockets = Vec::new(); |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1949 | let (wayland_host_socket, wayland_device_socket) = |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 1950 | msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?; |
| 1951 | control_sockets.push(TaggedControlSocket::VmMemory(wayland_host_socket)); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1952 | // Balloon gets a special socket so balloon requests can be forwarded from the main process. |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 1953 | let (balloon_host_socket, balloon_device_socket) = |
Charles William Dick | 664cc3c | 2020-01-10 14:31:52 +0900 | [diff] [blame] | 1954 | msg_socket::pair::<BalloonControlCommand, BalloonControlResult>() |
| 1955 | .map_err(Error::CreateSocket)?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 1956 | |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1957 | // Create one control socket per disk. |
| 1958 | let mut disk_device_sockets = Vec::new(); |
| 1959 | let mut disk_host_sockets = Vec::new(); |
| 1960 | let disk_count = cfg.disks.len(); |
| 1961 | for _ in 0..disk_count { |
| 1962 | let (disk_host_socket, disk_device_socket) = |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 1963 | msg_socket::pair::<DiskControlCommand, DiskControlResult>() |
| 1964 | .map_err(Error::CreateSocket)?; |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1965 | disk_host_sockets.push(disk_host_socket); |
Jakub Staron | e7c5905 | 2019-04-09 12:31:14 -0700 | [diff] [blame] | 1966 | disk_device_sockets.push(disk_device_socket); |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 1967 | } |
| 1968 | |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 1969 | let mut pmem_device_sockets = Vec::new(); |
| 1970 | let pmem_count = cfg.pmem_devices.len(); |
| 1971 | for _ in 0..pmem_count { |
| 1972 | let (pmem_host_socket, pmem_device_socket) = |
| 1973 | msg_socket::pair::<VmMsyncResponse, VmMsyncRequest>().map_err(Error::CreateSocket)?; |
| 1974 | pmem_device_sockets.push(pmem_device_socket); |
| 1975 | control_sockets.push(TaggedControlSocket::VmMsync(pmem_host_socket)); |
| 1976 | } |
| 1977 | |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 1978 | let (gpu_host_socket, gpu_device_socket) = |
| 1979 | msg_socket::pair::<VmMemoryResponse, VmMemoryRequest>().map_err(Error::CreateSocket)?; |
| 1980 | control_sockets.push(TaggedControlSocket::VmMemory(gpu_host_socket)); |
| 1981 | |
Zhuocheng Ding | f2e90bf | 2019-12-02 15:50:20 +0800 | [diff] [blame] | 1982 | let (ioapic_host_socket, ioapic_device_socket) = |
| 1983 | msg_socket::pair::<VmIrqResponse, VmIrqRequest>().map_err(Error::CreateSocket)?; |
| 1984 | control_sockets.push(TaggedControlSocket::VmIrq(ioapic_host_socket)); |
| 1985 | |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 1986 | let map_request: Arc<Mutex<Option<ExternalMapping>>> = Arc::new(Mutex::new(None)); |
| 1987 | |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1988 | let linux = Arch::build_vm( |
| 1989 | components, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1990 | &cfg.serial_parameters, |
Matt Delco | 45caf91 | 2019-11-13 08:11:09 -0800 | [diff] [blame] | 1991 | simple_jail(&cfg, "serial")?, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1992 | |mem, vm, sys_allocator, exit_evt| { |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 1993 | create_devices( |
| 1994 | &cfg, |
Jakub Staron | a3411ea | 2019-04-24 10:55:25 -0700 | [diff] [blame] | 1995 | mem, |
| 1996 | vm, |
| 1997 | sys_allocator, |
| 1998 | exit_evt, |
Xiong Zhang | a5d248c | 2019-09-17 14:17:19 -0700 | [diff] [blame] | 1999 | &mut control_sockets, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 2000 | wayland_device_socket, |
Gurchetan Singh | 96beafc | 2019-05-15 09:46:52 -0700 | [diff] [blame] | 2001 | gpu_device_socket, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 2002 | balloon_device_socket, |
| 2003 | &mut disk_device_sockets, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 2004 | &mut pmem_device_sockets, |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 2005 | usb_provider, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 2006 | Arc::clone(&map_request), |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 2007 | ) |
| 2008 | }, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2009 | create_vm, |
| 2010 | |vm, vcpu_count| create_irq_chip(vm, vcpu_count, ioapic_device_socket), |
Trent Begin | 17ccaad | 2019-04-17 13:51:25 -0600 | [diff] [blame] | 2011 | ) |
David Tolnay | be03426 | 2019-03-04 17:48:36 -0800 | [diff] [blame] | 2012 | .map_err(Error::BuildVm)?; |
Lepton Wu | 6089388 | 2018-11-21 11:06:18 -0800 | [diff] [blame] | 2013 | |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 2014 | run_control( |
| 2015 | linux, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2016 | control_server_socket, |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 2017 | control_sockets, |
| 2018 | balloon_host_socket, |
| 2019 | &disk_host_sockets, |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 2020 | usb_control_socket, |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 2021 | sigchld_fd, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2022 | cfg.sandbox, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 2023 | Arc::clone(&map_request), |
Daniel Verkamp | 92f73d7 | 2018-12-04 13:17:46 -0800 | [diff] [blame] | 2024 | ) |
Dylan Reid | 0ed91ab | 2018-05-31 15:42:18 -0700 | [diff] [blame] | 2025 | } |
| 2026 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2027 | fn run_control<V: VmArch + 'static, I: IrqChipArch<V::Vcpu> + 'static>( |
| 2028 | mut linux: RunnableLinuxVm<V, I>, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2029 | control_server_socket: Option<UnlinkUnixSeqpacketListener>, |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2030 | mut control_sockets: Vec<TaggedControlSocket>, |
Jakub Staron | 1f828d7 | 2019-04-11 12:49:29 -0700 | [diff] [blame] | 2031 | balloon_host_socket: BalloonControlRequestSocket, |
Jakub Staron | ecf81e0 | 2019-04-11 11:43:39 -0700 | [diff] [blame] | 2032 | disk_host_sockets: &[DiskControlRequestSocket], |
Jingkui Wang | 100e6e4 | 2019-03-08 20:41:57 -0800 | [diff] [blame] | 2033 | usb_control_socket: UsbControlSocket, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2034 | sigchld_fd: SignalFd, |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 2035 | sandbox: bool, |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 2036 | map_request: Arc<Mutex<Option<ExternalMapping>>>, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2037 | ) -> Result<()> { |
David Tolnay | 5bbbf61 | 2018-12-01 17:49:30 -0800 | [diff] [blame] | 2038 | const LOWMEM_AVAILABLE: &str = "/sys/kernel/mm/chromeos-low_mem/available"; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2039 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2040 | #[derive(PollToken)] |
| 2041 | enum Token { |
| 2042 | Exit, |
Chuanxiao Dong | 546f01c | 2020-02-12 21:58:47 +0800 | [diff] [blame] | 2043 | Suspend, |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2044 | ChildSignal, |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2045 | IrqFd { gsi: usize }, |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2046 | BalanceMemory, |
| 2047 | BalloonResult, |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2048 | VmControlServer, |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2049 | VmControl { index: usize }, |
| 2050 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2051 | |
Zach Reizner | 19ad1f3 | 2019-12-12 18:58:50 -0800 | [diff] [blame] | 2052 | stdin() |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2053 | .set_raw_mode() |
| 2054 | .expect("failed to set terminal raw mode"); |
| 2055 | |
Zach Reizner | b2110be | 2019-07-23 15:55:03 -0700 | [diff] [blame] | 2056 | let poll_ctx = PollContext::build_with(&[ |
| 2057 | (&linux.exit_evt, Token::Exit), |
Chuanxiao Dong | 546f01c | 2020-02-12 21:58:47 +0800 | [diff] [blame] | 2058 | (&linux.suspend_evt, Token::Suspend), |
Zach Reizner | b2110be | 2019-07-23 15:55:03 -0700 | [diff] [blame] | 2059 | (&sigchld_fd, Token::ChildSignal), |
| 2060 | ]) |
| 2061 | .map_err(Error::PollContextAdd)?; |
| 2062 | |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2063 | if let Some(socket_server) = &control_server_socket { |
| 2064 | poll_ctx |
| 2065 | .add(socket_server, Token::VmControlServer) |
| 2066 | .map_err(Error::PollContextAdd)?; |
| 2067 | } |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 2068 | for (index, socket) in control_sockets.iter().enumerate() { |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2069 | poll_ctx |
| 2070 | .add(socket.as_ref(), Token::VmControl { index }) |
| 2071 | .map_err(Error::PollContextAdd)?; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2072 | } |
| 2073 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2074 | let events = linux |
| 2075 | .irq_chip |
| 2076 | .irq_event_tokens() |
| 2077 | .map_err(Error::PollContextAdd)?; |
| 2078 | |
| 2079 | for (gsi, evt) in events { |
| 2080 | poll_ctx |
| 2081 | .add(&evt, Token::IrqFd { gsi: gsi as usize }) |
| 2082 | .map_err(Error::PollContextAdd)?; |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2083 | } |
| 2084 | |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2085 | // Balance available memory between guest and host every second. |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 2086 | let mut balancemem_timer = Timer::new().map_err(Error::CreateTimer)?; |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2087 | if Path::new(LOWMEM_AVAILABLE).exists() { |
| 2088 | // Create timer request balloon stats every 1s. |
| 2089 | poll_ctx |
| 2090 | .add(&balancemem_timer, Token::BalanceMemory) |
| 2091 | .map_err(Error::PollContextAdd)?; |
| 2092 | let balancemem_dur = Duration::from_secs(1); |
| 2093 | let balancemem_int = Duration::from_secs(1); |
| 2094 | balancemem_timer |
| 2095 | .reset(balancemem_dur, Some(balancemem_int)) |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 2096 | .map_err(Error::ResetTimer)?; |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2097 | |
| 2098 | // Listen for balloon statistics from the guest so we can balance. |
| 2099 | poll_ctx |
| 2100 | .add(&balloon_host_socket, Token::BalloonResult) |
| 2101 | .map_err(Error::PollContextAdd)?; |
| 2102 | } else { |
| 2103 | warn!("Unable to open low mem available, maybe not a chrome os kernel"); |
| 2104 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2105 | |
Lepton Wu | 20333e4 | 2019-03-14 10:48:03 -0700 | [diff] [blame] | 2106 | if sandbox { |
| 2107 | // Before starting VCPUs, in case we started with some capabilities, drop them all. |
| 2108 | drop_capabilities().map_err(Error::DropCapabilities)?; |
| 2109 | } |
Dmitry Torokhov | 7100607 | 2019-03-06 10:56:51 -0800 | [diff] [blame] | 2110 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2111 | let mut vcpu_handles = Vec::with_capacity(linux.vcpu_count); |
| 2112 | let vcpu_thread_barrier = Arc::new(Barrier::new(linux.vcpu_count + 1)); |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 2113 | let run_mode_arc = Arc::new(VcpuRunMode::default()); |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2114 | let use_hypervisor_signals = !linux |
| 2115 | .vm |
| 2116 | .get_hypervisor() |
| 2117 | .check_capability(&HypervisorCap::ImmediateExit); |
| 2118 | setup_vcpu_signal_handler::<V::Vcpu>(use_hypervisor_signals)?; |
| 2119 | |
| 2120 | let vcpus: Vec<Option<V::Vcpu>> = match linux.vcpus.take() { |
| 2121 | Some(vec) => vec.into_iter().map(|vcpu| Some(vcpu)).collect(), |
| 2122 | None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(), |
| 2123 | }; |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 2124 | for (cpu_id, vcpu) in vcpus.into_iter().enumerate() { |
Daniel Verkamp | c677fb4 | 2020-09-08 13:47:49 -0700 | [diff] [blame] | 2125 | let vcpu_affinity = match linux.vcpu_affinity.clone() { |
| 2126 | Some(VcpuAffinity::Global(v)) => v, |
| 2127 | Some(VcpuAffinity::PerVcpu(mut m)) => m.remove(&cpu_id).unwrap_or_default(), |
| 2128 | None => Default::default(), |
| 2129 | }; |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2130 | let handle = run_vcpu( |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2131 | cpu_id, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2132 | vcpu, |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 2133 | linux.vm.try_clone().map_err(Error::CloneEvent)?, |
| 2134 | linux.irq_chip.try_clone().map_err(Error::CloneEvent)?, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2135 | linux.vcpu_count, |
Kansho Nishida | ab205af | 2020-08-13 18:17:50 +0900 | [diff] [blame] | 2136 | linux.rt_cpus.contains(&cpu_id), |
Daniel Verkamp | c677fb4 | 2020-09-08 13:47:49 -0700 | [diff] [blame] | 2137 | vcpu_affinity, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2138 | vcpu_thread_barrier.clone(), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2139 | linux.has_bios, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2140 | linux.io_bus.clone(), |
| 2141 | linux.mmio_bus.clone(), |
Michael Hoyle | 685316f | 2020-09-16 15:29:20 -0700 | [diff] [blame^] | 2142 | linux.exit_evt.try_clone().map_err(Error::CloneEvent)?, |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2143 | linux.vm.check_capability(VmCap::PvClockSuspend), |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 2144 | run_mode_arc.clone(), |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2145 | use_hypervisor_signals, |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2146 | )?; |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 2147 | vcpu_handles.push(handle); |
| 2148 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2149 | |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 2150 | vcpu_thread_barrier.wait(); |
| 2151 | |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2152 | 'poll: loop { |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2153 | let events = { |
| 2154 | match poll_ctx.wait() { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2155 | Ok(v) => v, |
| 2156 | Err(e) => { |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 2157 | error!("failed to poll: {}", e); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2158 | break; |
| 2159 | } |
| 2160 | } |
| 2161 | }; |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2162 | |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2163 | if let Err(e) = linux.irq_chip.process_delayed_irq_events() { |
| 2164 | warn!("can't deliver delayed irqs: {}", e); |
| 2165 | } |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2166 | |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2167 | let mut vm_control_indices_to_remove = Vec::new(); |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2168 | for event in events.iter_readable() { |
| 2169 | match event.token() { |
| 2170 | Token::Exit => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2171 | info!("vcpu requested shutdown"); |
| 2172 | break 'poll; |
| 2173 | } |
Chuanxiao Dong | 546f01c | 2020-02-12 21:58:47 +0800 | [diff] [blame] | 2174 | Token::Suspend => { |
| 2175 | info!("VM requested suspend"); |
| 2176 | linux.suspend_evt.read().unwrap(); |
| 2177 | run_mode_arc.set_and_notify(VmRunMode::Suspending); |
| 2178 | for handle in &vcpu_handles { |
| 2179 | let _ = handle.kill(SIGRTMIN() + 0); |
| 2180 | } |
| 2181 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2182 | Token::ChildSignal => { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2183 | // Print all available siginfo structs, then exit the loop. |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 2184 | while let Some(siginfo) = sigchld_fd.read().map_err(Error::SignalFd)? { |
Zach Reizner | 3ba0098 | 2019-01-23 19:04:43 -0800 | [diff] [blame] | 2185 | let pid = siginfo.ssi_pid; |
| 2186 | let pid_label = match linux.pid_debug_label_map.get(&pid) { |
| 2187 | Some(label) => format!("{} (pid {})", label, pid), |
| 2188 | None => format!("pid {}", pid), |
| 2189 | }; |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 2190 | error!( |
| 2191 | "child {} died: signo {}, status {}, code {}", |
Zach Reizner | 3ba0098 | 2019-01-23 19:04:43 -0800 | [diff] [blame] | 2192 | pid_label, siginfo.ssi_signo, siginfo.ssi_status, siginfo.ssi_code |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 2193 | ); |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2194 | } |
David Tolnay | f503276 | 2018-12-03 10:46:45 -0800 | [diff] [blame] | 2195 | break 'poll; |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2196 | } |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2197 | Token::IrqFd { gsi } => { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2198 | if let Err(e) = linux.irq_chip.service_irq_event(gsi as u32) { |
| 2199 | error!("failed to signal irq {}: {}", gsi, e); |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2200 | } |
| 2201 | } |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2202 | Token::BalanceMemory => { |
Michael Hoyle | 08d86a4 | 2020-08-19 14:45:21 -0700 | [diff] [blame] | 2203 | balancemem_timer.wait().map_err(Error::Timer)?; |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2204 | let command = BalloonControlCommand::Stats {}; |
| 2205 | if let Err(e) = balloon_host_socket.send(&command) { |
| 2206 | warn!("failed to send stats request to balloon device: {}", e); |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2207 | } |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2208 | } |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2209 | Token::BalloonResult => { |
| 2210 | match balloon_host_socket.recv() { |
| 2211 | Ok(BalloonControlResult::Stats { |
| 2212 | stats, |
| 2213 | balloon_actual: balloon_actual_u, |
| 2214 | }) => { |
| 2215 | // Available memory is reported in MB, and we need bytes. |
| 2216 | let host_available = file_to_i64(LOWMEM_AVAILABLE) |
| 2217 | .map_err(Error::ReadMemAvailable)? |
| 2218 | << 20; |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2219 | let guest_free_u = if let Some(free) = stats.free_memory { |
| 2220 | free |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2221 | } else { |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2222 | warn!("guest free_memory stat is missing"); |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2223 | continue; |
| 2224 | }; |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2225 | let guest_cached_u = if let Some(cached) = stats.disk_caches { |
| 2226 | cached |
| 2227 | } else { |
| 2228 | warn!("guest disk_caches stat is missing"); |
| 2229 | continue; |
| 2230 | }; |
| 2231 | if guest_free_u > i64::max_value() as u64 { |
| 2232 | warn!("guest free memory is too large"); |
| 2233 | continue; |
| 2234 | } |
| 2235 | if guest_cached_u > i64::max_value() as u64 { |
| 2236 | warn!("guest cached memory is too large"); |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2237 | continue; |
| 2238 | } |
| 2239 | if balloon_actual_u > i64::max_value() as u64 { |
| 2240 | warn!("actual balloon size is too large"); |
| 2241 | continue; |
| 2242 | } |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2243 | // Tell the guest to change the balloon size if the target balloon size |
| 2244 | // is more than 5% different from the current balloon size. |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2245 | const RESIZE_PERCENT: i64 = 5; |
| 2246 | let balloon_actual = balloon_actual_u as i64; |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2247 | let guest_free = guest_free_u as i64; |
| 2248 | let guest_cached = guest_cached_u as i64; |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2249 | // Compute how much memory the guest should have available after we |
| 2250 | // rebalance. |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2251 | let guest_available_target = host_available; |
| 2252 | let guest_available_delta = |
| 2253 | guest_available_target - guest_free - guest_cached; |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2254 | // How much do we have to change the balloon to balance. |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2255 | let balloon_target = max(balloon_actual - guest_available_delta, 0); |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2256 | // Compute the change in balloon size in percent. If the balloon size |
| 2257 | // is 0, use 1 so we don't overflow from the infinity % increase. |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2258 | let balloon_change_percent = (balloon_actual - balloon_target).abs() |
| 2259 | * 100 |
| 2260 | / max(balloon_actual, 1); |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2261 | |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2262 | if balloon_change_percent >= RESIZE_PERCENT { |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2263 | info!("resizing balloon: host avail {}, guest free {} cached {} (target {}), balloon actual {} (target {})", |
Daniel Verkamp | 1cd8099 | 2020-07-27 12:41:50 -0700 | [diff] [blame] | 2264 | host_available, |
Suleiman Souhlal | 14fa6bd | 2020-08-18 13:01:15 +0900 | [diff] [blame] | 2265 | guest_free, |
| 2266 | guest_cached, |
Daniel Verkamp | 1cd8099 | 2020-07-27 12:41:50 -0700 | [diff] [blame] | 2267 | guest_available_target, |
| 2268 | balloon_actual, |
| 2269 | balloon_target, |
| 2270 | ); |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2271 | let command = BalloonControlCommand::Adjust { |
| 2272 | num_bytes: balloon_target as u64, |
| 2273 | }; |
| 2274 | if let Err(e) = balloon_host_socket.send(&command) { |
| 2275 | warn!("failed to send memory value to balloon device: {}", e); |
| 2276 | } |
| 2277 | } |
| 2278 | } |
| 2279 | Err(e) => { |
| 2280 | error!("failed to recv BalloonControlResult: {}", e); |
| 2281 | } |
| 2282 | }; |
Chirantan Ekbote | 448516e | 2018-07-24 16:07:42 -0700 | [diff] [blame] | 2283 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2284 | Token::VmControlServer => { |
| 2285 | if let Some(socket_server) = &control_server_socket { |
| 2286 | match socket_server.accept() { |
| 2287 | Ok(socket) => { |
| 2288 | poll_ctx |
| 2289 | .add( |
| 2290 | &socket, |
| 2291 | Token::VmControl { |
| 2292 | index: control_sockets.len(), |
| 2293 | }, |
| 2294 | ) |
| 2295 | .map_err(Error::PollContextAdd)?; |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2296 | control_sockets |
| 2297 | .push(TaggedControlSocket::Vm(MsgSocket::new(socket))); |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2298 | } |
| 2299 | Err(e) => error!("failed to accept socket: {}", e), |
| 2300 | } |
| 2301 | } |
| 2302 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2303 | Token::VmControl { index } => { |
Daniel Verkamp | 37c4a78 | 2019-01-04 10:44:17 -0800 | [diff] [blame] | 2304 | if let Some(socket) = control_sockets.get(index) { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2305 | match socket { |
| 2306 | TaggedControlSocket::Vm(socket) => match socket.recv() { |
| 2307 | Ok(request) => { |
| 2308 | let mut run_mode_opt = None; |
| 2309 | let response = request.execute( |
| 2310 | &mut run_mode_opt, |
| 2311 | &balloon_host_socket, |
| 2312 | disk_host_sockets, |
| 2313 | &usb_control_socket, |
| 2314 | ); |
| 2315 | if let Err(e) = socket.send(&response) { |
| 2316 | error!("failed to send VmResponse: {}", e); |
| 2317 | } |
| 2318 | if let Some(run_mode) = run_mode_opt { |
| 2319 | info!("control socket changed run mode to {}", run_mode); |
| 2320 | match run_mode { |
| 2321 | VmRunMode::Exiting => { |
| 2322 | break 'poll; |
| 2323 | } |
Chuanxiao Dong | 546f01c | 2020-02-12 21:58:47 +0800 | [diff] [blame] | 2324 | VmRunMode::Running => { |
| 2325 | if let VmRunMode::Suspending = |
| 2326 | *run_mode_arc.mtx.lock() |
| 2327 | { |
| 2328 | linux.io_bus.notify_resume(); |
| 2329 | } |
| 2330 | run_mode_arc.set_and_notify(VmRunMode::Running); |
| 2331 | for handle in &vcpu_handles { |
| 2332 | let _ = handle.kill(SIGRTMIN() + 0); |
| 2333 | } |
| 2334 | } |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2335 | other => { |
| 2336 | run_mode_arc.set_and_notify(other); |
| 2337 | for handle in &vcpu_handles { |
| 2338 | let _ = handle.kill(SIGRTMIN() + 0); |
| 2339 | } |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 2340 | } |
| 2341 | } |
| 2342 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2343 | } |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2344 | Err(e) => { |
Zach Reizner | 297ae77 | 2020-02-21 14:45:14 -0800 | [diff] [blame] | 2345 | if let MsgError::RecvZero = e { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2346 | vm_control_indices_to_remove.push(index); |
| 2347 | } else { |
| 2348 | error!("failed to recv VmRequest: {}", e); |
| 2349 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2350 | } |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2351 | }, |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 2352 | TaggedControlSocket::VmMemory(socket) => match socket.recv() { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2353 | Ok(request) => { |
Lingfeng Yang | d6ac1ab | 2020-01-31 13:55:35 -0800 | [diff] [blame] | 2354 | let response = request.execute( |
| 2355 | &mut linux.vm, |
| 2356 | &mut linux.resources, |
| 2357 | Arc::clone(&map_request), |
| 2358 | ); |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2359 | if let Err(e) = socket.send(&response) { |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 2360 | error!("failed to send VmMemoryControlResponse: {}", e); |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2361 | } |
| 2362 | } |
| 2363 | Err(e) => { |
Zach Reizner | 297ae77 | 2020-02-21 14:45:14 -0800 | [diff] [blame] | 2364 | if let MsgError::RecvZero = e { |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2365 | vm_control_indices_to_remove.push(index); |
| 2366 | } else { |
Gurchetan Singh | 53edb81 | 2019-05-22 08:57:16 -0700 | [diff] [blame] | 2367 | error!("failed to recv VmMemoryControlRequest: {}", e); |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2368 | } |
| 2369 | } |
| 2370 | }, |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 2371 | TaggedControlSocket::VmIrq(socket) => match socket.recv() { |
| 2372 | Ok(request) => { |
Steven Richman | f32d0b4 | 2020-06-20 21:45:32 -0700 | [diff] [blame] | 2373 | let response = { |
| 2374 | let irq_chip = &mut linux.irq_chip; |
| 2375 | request.execute( |
| 2376 | |setup| match setup { |
| 2377 | IrqSetup::Event(irq, ev) => { |
| 2378 | irq_chip.register_irq_event(irq, ev, None) |
| 2379 | } |
| 2380 | IrqSetup::Route(route) => irq_chip.route_irq(route), |
| 2381 | }, |
| 2382 | &mut linux.resources, |
| 2383 | ) |
| 2384 | }; |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 2385 | if let Err(e) = socket.send(&response) { |
| 2386 | error!("failed to send VmIrqResponse: {}", e); |
| 2387 | } |
| 2388 | } |
| 2389 | Err(e) => { |
Zach Reizner | 297ae77 | 2020-02-21 14:45:14 -0800 | [diff] [blame] | 2390 | if let MsgError::RecvZero = e { |
Xiong Zhang | 2515b75 | 2019-09-19 10:29:02 +0800 | [diff] [blame] | 2391 | vm_control_indices_to_remove.push(index); |
| 2392 | } else { |
| 2393 | error!("failed to recv VmIrqRequest: {}", e); |
| 2394 | } |
| 2395 | } |
| 2396 | }, |
Daniel Verkamp | e1980a9 | 2020-02-07 11:00:55 -0800 | [diff] [blame] | 2397 | TaggedControlSocket::VmMsync(socket) => match socket.recv() { |
| 2398 | Ok(request) => { |
| 2399 | let response = request.execute(&mut linux.vm); |
| 2400 | if let Err(e) = socket.send(&response) { |
| 2401 | error!("failed to send VmMsyncResponse: {}", e); |
| 2402 | } |
| 2403 | } |
| 2404 | Err(e) => { |
| 2405 | if let MsgError::BadRecvSize { actual: 0, .. } = e { |
| 2406 | vm_control_indices_to_remove.push(index); |
| 2407 | } else { |
| 2408 | error!("failed to recv VmMsyncRequest: {}", e); |
| 2409 | } |
| 2410 | } |
| 2411 | }, |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2412 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2413 | } |
| 2414 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2415 | } |
| 2416 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2417 | |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2418 | for event in events.iter_hungup() { |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2419 | match event.token() { |
| 2420 | Token::Exit => {} |
Chuanxiao Dong | 546f01c | 2020-02-12 21:58:47 +0800 | [diff] [blame] | 2421 | Token::Suspend => {} |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2422 | Token::ChildSignal => {} |
Zhuocheng Ding | b9f4c9b | 2019-12-02 15:50:28 +0800 | [diff] [blame] | 2423 | Token::IrqFd { gsi: _ } => {} |
Charles William Dick | 0bf8a55 | 2019-10-29 15:36:01 +0900 | [diff] [blame] | 2424 | Token::BalanceMemory => {} |
| 2425 | Token::BalloonResult => {} |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2426 | Token::VmControlServer => {} |
| 2427 | Token::VmControl { index } => { |
| 2428 | // It's possible more data is readable and buffered while the socket is hungup, |
| 2429 | // so don't delete the socket from the poll context until we're sure all the |
| 2430 | // data is read. |
Jakub Staron | d99cd0a | 2019-04-11 14:09:39 -0700 | [diff] [blame] | 2431 | match control_sockets |
| 2432 | .get(index) |
| 2433 | .map(|s| s.as_ref().get_readable_bytes()) |
| 2434 | { |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2435 | Some(Ok(0)) | Some(Err(_)) => vm_control_indices_to_remove.push(index), |
| 2436 | Some(Ok(x)) => info!("control index {} has {} bytes readable", index, x), |
| 2437 | _ => {} |
Zach Reizner | 55a9e50 | 2018-10-03 10:22:32 -0700 | [diff] [blame] | 2438 | } |
Zach Reizner | 5bed0d2 | 2018-03-28 02:31:11 -0700 | [diff] [blame] | 2439 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2440 | } |
| 2441 | } |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2442 | |
| 2443 | // Sort in reverse so the highest indexes are removed first. This removal algorithm |
Zide Chen | 8958407 | 2019-11-14 10:33:51 -0800 | [diff] [blame] | 2444 | // preserves correct indexes as each element is removed. |
Daniel Verkamp | 8c2f000 | 2020-08-31 15:13:35 -0700 | [diff] [blame] | 2445 | vm_control_indices_to_remove.sort_unstable_by_key(|&k| Reverse(k)); |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2446 | vm_control_indices_to_remove.dedup(); |
| 2447 | for index in vm_control_indices_to_remove { |
Zide Chen | 8958407 | 2019-11-14 10:33:51 -0800 | [diff] [blame] | 2448 | // Delete the socket from the `poll_ctx` synchronously. Otherwise, the kernel will do |
| 2449 | // this automatically when the FD inserted into the `poll_ctx` is closed after this |
| 2450 | // if-block, but this removal can be deferred unpredictably. In some instances where the |
| 2451 | // system is under heavy load, we can even get events returned by `poll_ctx` for an FD |
| 2452 | // that has already been closed. Because the token associated with that spurious event |
| 2453 | // now belongs to a different socket, the control loop will start to interact with |
| 2454 | // sockets that might not be ready to use. This can cause incorrect hangup detection or |
| 2455 | // blocking on a socket that will never be ready. See also: crbug.com/1019986 |
| 2456 | if let Some(socket) = control_sockets.get(index) { |
| 2457 | poll_ctx.delete(socket).map_err(Error::PollContextDelete)?; |
| 2458 | } |
| 2459 | |
| 2460 | // This line implicitly drops the socket at `index` when it gets returned by |
| 2461 | // `swap_remove`. After this line, the socket at `index` is not the one from |
| 2462 | // `vm_control_indices_to_remove`. Because of this socket's change in index, we need to |
| 2463 | // use `poll_ctx.modify` to change the associated index in its `Token::VmControl`. |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2464 | control_sockets.swap_remove(index); |
| 2465 | if let Some(socket) = control_sockets.get(index) { |
| 2466 | poll_ctx |
Xiong Zhang | 44bb3dd | 2019-04-23 17:09:50 +0800 | [diff] [blame] | 2467 | .modify( |
| 2468 | socket, |
| 2469 | WatchingEvents::empty().set_read(), |
| 2470 | Token::VmControl { index }, |
| 2471 | ) |
Zach Reizner | a60744b | 2019-02-13 17:33:32 -0800 | [diff] [blame] | 2472 | .map_err(Error::PollContextAdd)?; |
| 2473 | } |
| 2474 | } |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2475 | } |
| 2476 | |
Zach Reizner | 6a8fdd9 | 2019-01-16 14:38:41 -0800 | [diff] [blame] | 2477 | // VCPU threads MUST see the VmRunMode flag, otherwise they may re-enter the VM. |
| 2478 | run_mode_arc.set_and_notify(VmRunMode::Exiting); |
Dylan Reid | 059a188 | 2018-07-23 17:58:09 -0700 | [diff] [blame] | 2479 | for handle in vcpu_handles { |
Dmitry Torokhov | cd40533 | 2018-02-16 16:25:54 -0800 | [diff] [blame] | 2480 | match handle.kill(SIGRTMIN() + 0) { |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2481 | Ok(_) => { |
| 2482 | if let Err(e) = handle.join() { |
| 2483 | error!("failed to join vcpu thread: {:?}", e); |
| 2484 | } |
| 2485 | } |
David Tolnay | b4bd00f | 2019-02-12 17:51:26 -0800 | [diff] [blame] | 2486 | Err(e) => error!("failed to kill vcpu thread: {}", e), |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2487 | } |
| 2488 | } |
| 2489 | |
Daniel Verkamp | 94c3527 | 2019-09-12 13:31:30 -0700 | [diff] [blame] | 2490 | // Explicitly drop the VM structure here to allow the devices to clean up before the |
| 2491 | // control sockets are closed when this function exits. |
| 2492 | mem::drop(linux); |
| 2493 | |
Zach Reizner | 19ad1f3 | 2019-12-12 18:58:50 -0800 | [diff] [blame] | 2494 | stdin() |
Zach Reizner | 39aa26b | 2017-12-12 18:03:23 -0800 | [diff] [blame] | 2495 | .set_canon_mode() |
| 2496 | .expect("failed to restore canonical mode for terminal"); |
| 2497 | |
| 2498 | Ok(()) |
| 2499 | } |