blob: 2c50fedf2df15f63f0c378a3a9225a10a425010f [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 Walbrand15c5632022-02-03 13:38:31 +000039/// The exit status which crosvm returns when it has an error starting a VM.
40const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000041/// The exit status which crosvm returns when a VM requests a reboot.
42const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000043/// The exit status which crosvm returns when it crashes due to an error.
44const CROSVM_CRASH_STATUS: i32 = 33;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000045
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000046/// Configuration for a VM to run with crosvm.
47#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000048pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000049 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000050 pub bootloader: Option<File>,
51 pub kernel: Option<File>,
52 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000053 pub disks: Vec<DiskFile>,
54 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000055 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000056 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090057 pub cpus: Option<NonZeroU32>,
58 pub cpu_affinity: Option<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090059 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000060 pub log_fd: Option<File>,
61 pub indirect_files: Vec<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000062}
63
64/// A disk image to pass to crosvm for a VM.
65#[derive(Debug)]
66pub struct DiskFile {
67 pub image: File,
68 pub writable: bool,
69}
70
Andrew Walbran6b650662021-09-07 13:13:23 +000071/// The lifecycle state which the payload in the VM has reported itself to be in.
72///
73/// Note that the order of enum variants is significant; only forward transitions are allowed by
74/// [`VmInstance::update_payload_state`].
75#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
76pub enum PayloadState {
77 Starting,
78 Started,
79 Ready,
80 Finished,
81}
82
Andrew Walbranf8d94112021-09-07 11:45:36 +000083/// The current state of the VM itself.
84#[derive(Debug)]
85pub enum VmState {
86 /// The VM has not yet tried to start.
87 NotStarted {
88 ///The configuration needed to start the VM, if it has not yet been started.
89 config: CrosvmConfig,
90 },
91 /// The VM has been started.
92 Running {
93 /// The crosvm child process.
94 child: Arc<SharedChild>,
95 },
96 /// The VM died or was killed.
97 Dead,
98 /// The VM failed to start.
99 Failed,
100}
101
102impl VmState {
103 /// Tries to start the VM, if it is in the `NotStarted` state.
104 ///
105 /// Returns an error if the VM is in the wrong state, or fails to start.
106 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
107 let state = mem::replace(self, VmState::Failed);
108 if let VmState::NotStarted { config } = state {
109 // If this fails and returns an error, `self` will be left in the `Failed` state.
110 let child = Arc::new(run_vm(config)?);
111
112 let child_clone = child.clone();
113 thread::spawn(move || {
114 instance.monitor(child_clone);
115 });
116
117 // If it started correctly, update the state.
118 *self = VmState::Running { child };
119 Ok(())
120 } else {
121 *self = state;
122 bail!("VM already started or failed")
123 }
124 }
125}
126
127/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000128#[derive(Debug)]
129pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000130 /// The current state of the VM.
131 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132 /// The CID assigned to the VM for vsock communication.
133 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000134 /// Whether the VM is a protected VM.
135 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000136 /// Directory of temporary files used by the VM while it is running.
137 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000138 /// The UID of the process which requested the VM.
139 pub requester_uid: u32,
140 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000141 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000142 /// The PID of the process which requested the VM. Note that this process may no longer exist
143 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000144 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000145 /// Callbacks to clients of the VM.
146 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900147 /// Input/output stream of the payload run in the VM.
148 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000149 /// VirtualMachineService binder object for the VM.
150 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000151 /// The latest lifecycle state which the payload reported itself to be in.
152 payload_state: Mutex<PayloadState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000153}
154
155impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000156 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
157 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000158 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000159 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000160 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000161 requester_sid: String,
162 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000163 ) -> Result<VmInstance, Error> {
164 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000165 let cid = config.cid;
166 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000167 Ok(VmInstance {
168 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000169 cid,
170 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000171 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000172 requester_uid,
173 requester_sid,
174 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000175 callbacks: Default::default(),
176 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000177 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000178 payload_state: Mutex::new(PayloadState::Starting),
179 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000180 }
181
Andrew Walbranf8d94112021-09-07 11:45:36 +0000182 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
183 /// the `VmInstance` is dropped.
184 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
185 self.vm_state.lock().unwrap().start(self.clone())
186 }
187
188 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
189 /// calls any callbacks.
190 ///
191 /// This takes a separate reference to the `SharedChild` rather than using the one in
192 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
193 fn monitor(&self, child: Arc<SharedChild>) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000194 let result = child.wait();
195 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900196 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
197 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000198 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000199
200 let mut vm_state = self.vm_state.lock().unwrap();
201 *vm_state = VmState::Dead;
202 // Ensure that the mutex is released before calling the callbacks.
203 drop(vm_state);
204
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000205 self.callbacks.callback_on_died(self.cid, death_reason(&result));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000206
207 // Delete temporary files.
208 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000209 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000210 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000211 }
212
Andrew Walbran6b650662021-09-07 13:13:23 +0000213 /// Returns the last reported state of the VM payload.
214 pub fn payload_state(&self) -> PayloadState {
215 *self.payload_state.lock().unwrap()
216 }
217
218 /// Updates the payload state to the given value, if it is a valid state transition.
219 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
220 let mut state_locked = self.payload_state.lock().unwrap();
221 // Only allow forward transitions, e.g. from starting to started or finished, not back in
222 // the other direction.
223 if new_state > *state_locked {
224 *state_locked = new_state;
225 Ok(())
226 } else {
227 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
228 }
229 }
230
Andrew Walbranf8d94112021-09-07 11:45:36 +0000231 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000232 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000233 let vm_state = &*self.vm_state.lock().unwrap();
234 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900235 let id = child.id();
236 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 // TODO: Talk to crosvm to shutdown cleanly.
238 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900239 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000240 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000241 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000242 }
243}
244
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000245fn death_reason(result: &Result<ExitStatus, io::Error>) -> DeathReason {
246 if let Ok(status) = result {
247 match status.code() {
248 None => DeathReason::KILLED,
249 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000250 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000251 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000252 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000253 Some(_) => DeathReason::UNKNOWN,
254 }
255 } else {
256 DeathReason::INFRASTRUCTURE_ERROR
257 }
258}
259
Andrew Walbrand3a84182021-09-07 14:48:52 +0000260/// Starts an instance of `crosvm` to manage a new VM.
261fn run_vm(config: CrosvmConfig) -> Result<SharedChild, Error> {
262 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000263
264 let mut command = Command::new(CROSVM_PATH);
265 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000266 command
267 .arg("--extended-status")
268 .arg("run")
269 .arg("--disable-sandbox")
270 .arg("--cid")
271 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000272
Andrew Walbranf8650422021-06-09 15:54:09 +0000273 if config.protected {
274 command.arg("--protected-vm");
275 }
276
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000277 if let Some(memory_mib) = config.memory_mib {
278 command.arg("--mem").arg(memory_mib.to_string());
279 }
280
Jiyong Park032615f2022-01-10 13:55:34 +0900281 if let Some(cpus) = config.cpus {
282 command.arg("--cpus").arg(cpus.to_string());
283 }
284
285 if let Some(cpu_affinity) = config.cpu_affinity {
286 command.arg("--cpu-affinity").arg(cpu_affinity);
287 }
288
Jiyong Parkfa91d702021-10-18 23:51:39 +0900289 // Keep track of what file descriptors should be mapped to the crosvm process.
290 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
291
Jiyong Park747d6362021-10-19 17:12:52 +0900292 // Setup the serial devices.
293 // 1. uart device: used as the output device by bootloaders and as early console by linux
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900294 // 2. virtio-console device: used as the console device where kmsg is redirected to
295 // 3. virtio-console device: used as the androidboot.console device (not used currently)
296 // 4. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900297 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900298 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
299 // written there is discarded.
300 let mut format_serial_arg = |fd: &Option<File>| {
301 let path = fd.as_ref().map(|fd| add_preserved_fd(&mut preserved_fds, fd));
302 let type_arg = path.as_ref().map_or("type=sink", |_| "type=file");
303 let path_arg = path.as_ref().map_or(String::new(), |path| format!(",path={}", path));
304 format!("{}{}", type_arg, path_arg)
305 };
306 let console_arg = format_serial_arg(&config.console_fd);
307 let log_arg = format_serial_arg(&config.log_fd);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900308
Jiyong Park747d6362021-10-19 17:12:52 +0900309 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
310 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
311 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
312 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900313 // /dev/ttyS0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900314 command.arg(format!("--serial={},hardware=serial", &console_arg));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900315 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900316 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900317 // /dev/hvc1 (not used currently)
318 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
319 // /dev/hvc2
320 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000321
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000322 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000323 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000324 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000325
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000326 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000327 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000328 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000329
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000330 if let Some(params) = &config.params {
331 command.arg("--params").arg(params);
332 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000333
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000334 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000335 command
336 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000337 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000338 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000339
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000340 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000341 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000342 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000343
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000344 debug!("Preserving FDs {:?}", preserved_fds);
345 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000346
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000347 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000348 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900349 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000350 Ok(result)
351}
352
353/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000354fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000355 if config.bootloader.is_none() && config.kernel.is_none() {
356 bail!("VM must have either a bootloader or a kernel image.");
357 }
358 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
359 bail!("Can't have both bootloader and kernel/initrd image.");
360 }
361 Ok(())
362}
363
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000364/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
365/// "/proc/self/fd/N" where N is the file descriptor.
366fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000367 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000368 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000369 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000370}