blob: c02edabaced56c02771a8b770c52d868c5250876 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Functions for running instances of `crosvm`.
16
Andrew Walbrandae07162021-03-12 17:05:20 +000017use crate::aidl::VirtualMachineCallbacks;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000018use crate::Cid;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use anyhow::{bail, Error};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000021use log::{debug, error, info};
Andrew Walbrandae07162021-03-12 17:05:20 +000022use shared_child::SharedChild;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use std::fs::{remove_dir_all, File};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000024use std::io;
Andrew Walbranf8d94112021-09-07 11:45:36 +000025use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000026use std::num::NonZeroU32;
Andrew Walbran02b8ec02021-06-22 13:07:02 +000027use std::os::unix::io::{AsRawFd, RawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000028use std::path::PathBuf;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000029use std::process::{Command, ExitStatus};
Inseob Kim7f61fe72021-08-20 20:50:47 +090030use std::sync::{Arc, Mutex};
Andrew Walbrandae07162021-03-12 17:05:20 +000031use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090032use vsock::VsockStream;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000033use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
Inseob Kimc7d28c72021-10-25 14:28:10 +000034use android_system_virtualmachineservice::binder::Strong;
35use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000036
37const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
38
Andrew Walbranc92d35f2022-01-12 12:45:19 +000039/// The exit status which crosvm returns when a VM requests a reboot.
40const CROSVM_REBOOT_STATUS: i32 = 32;
41
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000042/// Configuration for a VM to run with crosvm.
43#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000044pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000045 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000046 pub bootloader: Option<File>,
47 pub kernel: Option<File>,
48 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000049 pub disks: Vec<DiskFile>,
50 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000051 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000052 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090053 pub cpus: Option<NonZeroU32>,
54 pub cpu_affinity: Option<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090055 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000056 pub log_fd: Option<File>,
57 pub indirect_files: Vec<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058}
59
60/// A disk image to pass to crosvm for a VM.
61#[derive(Debug)]
62pub struct DiskFile {
63 pub image: File,
64 pub writable: bool,
65}
66
Andrew Walbran6b650662021-09-07 13:13:23 +000067/// The lifecycle state which the payload in the VM has reported itself to be in.
68///
69/// Note that the order of enum variants is significant; only forward transitions are allowed by
70/// [`VmInstance::update_payload_state`].
71#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
72pub enum PayloadState {
73 Starting,
74 Started,
75 Ready,
76 Finished,
77}
78
Andrew Walbranf8d94112021-09-07 11:45:36 +000079/// The current state of the VM itself.
80#[derive(Debug)]
81pub enum VmState {
82 /// The VM has not yet tried to start.
83 NotStarted {
84 ///The configuration needed to start the VM, if it has not yet been started.
85 config: CrosvmConfig,
86 },
87 /// The VM has been started.
88 Running {
89 /// The crosvm child process.
90 child: Arc<SharedChild>,
91 },
92 /// The VM died or was killed.
93 Dead,
94 /// The VM failed to start.
95 Failed,
96}
97
98impl VmState {
99 /// Tries to start the VM, if it is in the `NotStarted` state.
100 ///
101 /// Returns an error if the VM is in the wrong state, or fails to start.
102 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
103 let state = mem::replace(self, VmState::Failed);
104 if let VmState::NotStarted { config } = state {
105 // If this fails and returns an error, `self` will be left in the `Failed` state.
106 let child = Arc::new(run_vm(config)?);
107
108 let child_clone = child.clone();
109 thread::spawn(move || {
110 instance.monitor(child_clone);
111 });
112
113 // If it started correctly, update the state.
114 *self = VmState::Running { child };
115 Ok(())
116 } else {
117 *self = state;
118 bail!("VM already started or failed")
119 }
120 }
121}
122
123/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000124#[derive(Debug)]
125pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 /// The current state of the VM.
127 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000128 /// The CID assigned to the VM for vsock communication.
129 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000130 /// Whether the VM is a protected VM.
131 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000132 /// Directory of temporary files used by the VM while it is running.
133 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000134 /// The UID of the process which requested the VM.
135 pub requester_uid: u32,
136 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000137 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000138 /// The PID of the process which requested the VM. Note that this process may no longer exist
139 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000140 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000141 /// Callbacks to clients of the VM.
142 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900143 /// Input/output stream of the payload run in the VM.
144 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000145 /// VirtualMachineService binder object for the VM.
146 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000147 /// The latest lifecycle state which the payload reported itself to be in.
148 payload_state: Mutex<PayloadState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000149}
150
151impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000152 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
153 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000154 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000155 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000156 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000157 requester_sid: String,
158 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000159 ) -> Result<VmInstance, Error> {
160 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000161 let cid = config.cid;
162 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000163 Ok(VmInstance {
164 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000165 cid,
166 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000167 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000168 requester_uid,
169 requester_sid,
170 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000171 callbacks: Default::default(),
172 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000173 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000174 payload_state: Mutex::new(PayloadState::Starting),
175 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000176 }
177
Andrew Walbranf8d94112021-09-07 11:45:36 +0000178 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
179 /// the `VmInstance` is dropped.
180 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
181 self.vm_state.lock().unwrap().start(self.clone())
182 }
183
184 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
185 /// calls any callbacks.
186 ///
187 /// This takes a separate reference to the `SharedChild` rather than using the one in
188 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
189 fn monitor(&self, child: Arc<SharedChild>) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000190 let result = child.wait();
191 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900192 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
193 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000194 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000195
196 let mut vm_state = self.vm_state.lock().unwrap();
197 *vm_state = VmState::Dead;
198 // Ensure that the mutex is released before calling the callbacks.
199 drop(vm_state);
200
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000201 self.callbacks.callback_on_died(self.cid, death_reason(&result));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000202
203 // Delete temporary files.
204 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000205 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000206 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000207 }
208
Andrew Walbran6b650662021-09-07 13:13:23 +0000209 /// Returns the last reported state of the VM payload.
210 pub fn payload_state(&self) -> PayloadState {
211 *self.payload_state.lock().unwrap()
212 }
213
214 /// Updates the payload state to the given value, if it is a valid state transition.
215 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
216 let mut state_locked = self.payload_state.lock().unwrap();
217 // Only allow forward transitions, e.g. from starting to started or finished, not back in
218 // the other direction.
219 if new_state > *state_locked {
220 *state_locked = new_state;
221 Ok(())
222 } else {
223 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
224 }
225 }
226
Andrew Walbranf8d94112021-09-07 11:45:36 +0000227 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000228 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000229 let vm_state = &*self.vm_state.lock().unwrap();
230 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900231 let id = child.id();
232 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 // TODO: Talk to crosvm to shutdown cleanly.
234 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900235 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000236 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000237 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000238 }
239}
240
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000241fn death_reason(result: &Result<ExitStatus, io::Error>) -> DeathReason {
242 if let Ok(status) = result {
243 match status.code() {
244 None => DeathReason::KILLED,
245 Some(0) => DeathReason::SHUTDOWN,
246 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
247 Some(_) => DeathReason::UNKNOWN,
248 }
249 } else {
250 DeathReason::INFRASTRUCTURE_ERROR
251 }
252}
253
Andrew Walbrand3a84182021-09-07 14:48:52 +0000254/// Starts an instance of `crosvm` to manage a new VM.
255fn run_vm(config: CrosvmConfig) -> Result<SharedChild, Error> {
256 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000257
258 let mut command = Command::new(CROSVM_PATH);
259 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000260 command
261 .arg("--extended-status")
262 .arg("run")
263 .arg("--disable-sandbox")
264 .arg("--cid")
265 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000266
Andrew Walbranf8650422021-06-09 15:54:09 +0000267 if config.protected {
Andrew Walbranb6547b42022-02-04 12:01:38 +0000268 // TODO: Go back to "--protected-vm" once pVM firmware is fixed.
269 command.arg("--protected-vm-without-firmware");
Andrew Walbranf8650422021-06-09 15:54:09 +0000270 }
271
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000272 if let Some(memory_mib) = config.memory_mib {
273 command.arg("--mem").arg(memory_mib.to_string());
274 }
275
Jiyong Park032615f2022-01-10 13:55:34 +0900276 if let Some(cpus) = config.cpus {
277 command.arg("--cpus").arg(cpus.to_string());
278 }
279
280 if let Some(cpu_affinity) = config.cpu_affinity {
281 command.arg("--cpu-affinity").arg(cpu_affinity);
282 }
283
Jiyong Parkfa91d702021-10-18 23:51:39 +0900284 // Keep track of what file descriptors should be mapped to the crosvm process.
285 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
286
Jiyong Park747d6362021-10-19 17:12:52 +0900287 // Setup the serial devices.
288 // 1. uart device: used as the output device by bootloaders and as early console by linux
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900289 // 2. virtio-console device: used as the console device where kmsg is redirected to
290 // 3. virtio-console device: used as the androidboot.console device (not used currently)
291 // 4. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900292 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900293 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
294 // written there is discarded.
295 let mut format_serial_arg = |fd: &Option<File>| {
296 let path = fd.as_ref().map(|fd| add_preserved_fd(&mut preserved_fds, fd));
297 let type_arg = path.as_ref().map_or("type=sink", |_| "type=file");
298 let path_arg = path.as_ref().map_or(String::new(), |path| format!(",path={}", path));
299 format!("{}{}", type_arg, path_arg)
300 };
301 let console_arg = format_serial_arg(&config.console_fd);
302 let log_arg = format_serial_arg(&config.log_fd);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900303
Jiyong Park747d6362021-10-19 17:12:52 +0900304 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
305 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
306 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
307 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900308 // /dev/ttyS0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900309 command.arg(format!("--serial={},hardware=serial", &console_arg));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900310 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900311 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900312 // /dev/hvc1 (not used currently)
313 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
314 // /dev/hvc2
315 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000316
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000317 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000318 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000319 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000320
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000321 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000322 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000323 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000324
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000325 if let Some(params) = &config.params {
326 command.arg("--params").arg(params);
327 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000328
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000329 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000330 command
331 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000332 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000333 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000334
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000335 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000336 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000337 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000338
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000339 debug!("Preserving FDs {:?}", preserved_fds);
340 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000341
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000342 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000343 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900344 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000345 Ok(result)
346}
347
348/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000349fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000350 if config.bootloader.is_none() && config.kernel.is_none() {
351 bail!("VM must have either a bootloader or a kernel image.");
352 }
353 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
354 bail!("Can't have both bootloader and kernel/initrd image.");
355 }
356 Ok(())
357}
358
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000359/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
360/// "/proc/self/fd/N" where N is the file descriptor.
361fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000362 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000363 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000364 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000365}