blob: 0b1429c6841863ff2fad9a304c52d91d7eda76bd [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 Walbranf8d94112021-09-07 11:45:36 +000024use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000025use std::num::NonZeroU32;
Andrew Walbran02b8ec02021-06-22 13:07:02 +000026use std::os::unix::io::{AsRawFd, RawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000027use std::path::PathBuf;
Andrew Walbrandae07162021-03-12 17:05:20 +000028use std::process::Command;
Inseob Kim7f61fe72021-08-20 20:50:47 +090029use std::sync::{Arc, Mutex};
Andrew Walbrandae07162021-03-12 17:05:20 +000030use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090031use vsock::VsockStream;
Inseob Kimc7d28c72021-10-25 14:28:10 +000032use android_system_virtualmachineservice::binder::Strong;
33use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000034
35const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
36
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000037/// Configuration for a VM to run with crosvm.
38#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000039pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000040 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000041 pub bootloader: Option<File>,
42 pub kernel: Option<File>,
43 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000044 pub disks: Vec<DiskFile>,
45 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000046 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000047 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090048 pub cpus: Option<NonZeroU32>,
49 pub cpu_affinity: Option<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090050 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000051 pub log_fd: Option<File>,
52 pub indirect_files: Vec<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000053}
54
55/// A disk image to pass to crosvm for a VM.
56#[derive(Debug)]
57pub struct DiskFile {
58 pub image: File,
59 pub writable: bool,
60}
61
Andrew Walbran6b650662021-09-07 13:13:23 +000062/// The lifecycle state which the payload in the VM has reported itself to be in.
63///
64/// Note that the order of enum variants is significant; only forward transitions are allowed by
65/// [`VmInstance::update_payload_state`].
66#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
67pub enum PayloadState {
68 Starting,
69 Started,
70 Ready,
71 Finished,
72}
73
Andrew Walbranf8d94112021-09-07 11:45:36 +000074/// The current state of the VM itself.
75#[derive(Debug)]
76pub enum VmState {
77 /// The VM has not yet tried to start.
78 NotStarted {
79 ///The configuration needed to start the VM, if it has not yet been started.
80 config: CrosvmConfig,
81 },
82 /// The VM has been started.
83 Running {
84 /// The crosvm child process.
85 child: Arc<SharedChild>,
86 },
87 /// The VM died or was killed.
88 Dead,
89 /// The VM failed to start.
90 Failed,
91}
92
93impl VmState {
94 /// Tries to start the VM, if it is in the `NotStarted` state.
95 ///
96 /// Returns an error if the VM is in the wrong state, or fails to start.
97 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
98 let state = mem::replace(self, VmState::Failed);
99 if let VmState::NotStarted { config } = state {
100 // If this fails and returns an error, `self` will be left in the `Failed` state.
101 let child = Arc::new(run_vm(config)?);
102
103 let child_clone = child.clone();
104 thread::spawn(move || {
105 instance.monitor(child_clone);
106 });
107
108 // If it started correctly, update the state.
109 *self = VmState::Running { child };
110 Ok(())
111 } else {
112 *self = state;
113 bail!("VM already started or failed")
114 }
115 }
116}
117
118/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000119#[derive(Debug)]
120pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121 /// The current state of the VM.
122 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123 /// The CID assigned to the VM for vsock communication.
124 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000125 /// Whether the VM is a protected VM.
126 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000127 /// Directory of temporary files used by the VM while it is running.
128 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000129 /// The UID of the process which requested the VM.
130 pub requester_uid: u32,
131 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000132 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000133 /// The PID of the process which requested the VM. Note that this process may no longer exist
134 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000135 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000136 /// Callbacks to clients of the VM.
137 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900138 /// Input/output stream of the payload run in the VM.
139 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000140 /// VirtualMachineService binder object for the VM.
141 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000142 /// The latest lifecycle state which the payload reported itself to be in.
143 payload_state: Mutex<PayloadState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000144}
145
146impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000147 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
148 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000149 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000150 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000151 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000152 requester_sid: String,
153 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000154 ) -> Result<VmInstance, Error> {
155 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000156 let cid = config.cid;
157 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000158 Ok(VmInstance {
159 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000160 cid,
161 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000162 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000163 requester_uid,
164 requester_sid,
165 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000166 callbacks: Default::default(),
167 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000168 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000169 payload_state: Mutex::new(PayloadState::Starting),
170 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000171 }
172
Andrew Walbranf8d94112021-09-07 11:45:36 +0000173 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
174 /// the `VmInstance` is dropped.
175 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
176 self.vm_state.lock().unwrap().start(self.clone())
177 }
178
179 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
180 /// calls any callbacks.
181 ///
182 /// This takes a separate reference to the `SharedChild` rather than using the one in
183 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
184 fn monitor(&self, child: Arc<SharedChild>) {
185 match child.wait() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900186 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
187 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000188 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000189
190 let mut vm_state = self.vm_state.lock().unwrap();
191 *vm_state = VmState::Dead;
192 // Ensure that the mutex is released before calling the callbacks.
193 drop(vm_state);
194
Andrew Walbrandae07162021-03-12 17:05:20 +0000195 self.callbacks.callback_on_died(self.cid);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000196
197 // Delete temporary files.
198 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000199 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000200 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000201 }
202
Andrew Walbran6b650662021-09-07 13:13:23 +0000203 /// Returns the last reported state of the VM payload.
204 pub fn payload_state(&self) -> PayloadState {
205 *self.payload_state.lock().unwrap()
206 }
207
208 /// Updates the payload state to the given value, if it is a valid state transition.
209 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
210 let mut state_locked = self.payload_state.lock().unwrap();
211 // Only allow forward transitions, e.g. from starting to started or finished, not back in
212 // the other direction.
213 if new_state > *state_locked {
214 *state_locked = new_state;
215 Ok(())
216 } else {
217 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
218 }
219 }
220
Andrew Walbranf8d94112021-09-07 11:45:36 +0000221 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000222 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 let vm_state = &*self.vm_state.lock().unwrap();
224 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900225 let id = child.id();
226 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000227 // TODO: Talk to crosvm to shutdown cleanly.
228 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900229 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000230 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000231 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000232 }
233}
234
Andrew Walbrand3a84182021-09-07 14:48:52 +0000235/// Starts an instance of `crosvm` to manage a new VM.
236fn run_vm(config: CrosvmConfig) -> Result<SharedChild, Error> {
237 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000238
239 let mut command = Command::new(CROSVM_PATH);
240 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000241 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000242
Andrew Walbranf8650422021-06-09 15:54:09 +0000243 if config.protected {
244 command.arg("--protected-vm");
245 }
246
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000247 if let Some(memory_mib) = config.memory_mib {
248 command.arg("--mem").arg(memory_mib.to_string());
249 }
250
Jiyong Park032615f2022-01-10 13:55:34 +0900251 if let Some(cpus) = config.cpus {
252 command.arg("--cpus").arg(cpus.to_string());
253 }
254
255 if let Some(cpu_affinity) = config.cpu_affinity {
256 command.arg("--cpu-affinity").arg(cpu_affinity);
257 }
258
Jiyong Parkfa91d702021-10-18 23:51:39 +0900259 // Keep track of what file descriptors should be mapped to the crosvm process.
260 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
261
Jiyong Park747d6362021-10-19 17:12:52 +0900262 // Setup the serial devices.
263 // 1. uart device: used as the output device by bootloaders and as early console by linux
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900264 // 2. virtio-console device: used as the console device where kmsg is redirected to
265 // 3. virtio-console device: used as the androidboot.console device (not used currently)
266 // 4. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900267 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900268 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
269 // written there is discarded.
270 let mut format_serial_arg = |fd: &Option<File>| {
271 let path = fd.as_ref().map(|fd| add_preserved_fd(&mut preserved_fds, fd));
272 let type_arg = path.as_ref().map_or("type=sink", |_| "type=file");
273 let path_arg = path.as_ref().map_or(String::new(), |path| format!(",path={}", path));
274 format!("{}{}", type_arg, path_arg)
275 };
276 let console_arg = format_serial_arg(&config.console_fd);
277 let log_arg = format_serial_arg(&config.log_fd);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900278
Jiyong Park747d6362021-10-19 17:12:52 +0900279 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
280 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
281 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
282 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900283 // /dev/ttyS0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900284 command.arg(format!("--serial={},hardware=serial", &console_arg));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900285 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900286 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900287 // /dev/hvc1 (not used currently)
288 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
289 // /dev/hvc2
290 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000291
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000292 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000293 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000294 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000295
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000296 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000297 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000298 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000299
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000300 if let Some(params) = &config.params {
301 command.arg("--params").arg(params);
302 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000303
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000304 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000305 command
306 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000307 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000308 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000309
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000310 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000311 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000312 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000313
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000314 debug!("Preserving FDs {:?}", preserved_fds);
315 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000316
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000317 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000318 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900319 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000320 Ok(result)
321}
322
323/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000324fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000325 if config.bootloader.is_none() && config.kernel.is_none() {
326 bail!("VM must have either a bootloader or a kernel image.");
327 }
328 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
329 bail!("Can't have both bootloader and kernel/initrd image.");
330 }
331 Ok(())
332}
333
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000334/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
335/// "/proc/self/fd/N" where N is the file descriptor.
336fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000337 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000338 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000339 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000340}