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