blob: 82a9e78c1368e20af23b4a46a41bd8a6a50ed928 [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;
Seungjae Yoob4c07ba2022-08-12 04:44:52 +000018use crate::atom::write_vm_exited_stats;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000019use crate::Cid;
Jiyong Park1612b902022-08-22 14:47:39 +090020use anyhow::{anyhow, bail, Context, Error};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000021use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090022use lazy_static::lazy_static;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000023use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090024use semver::{Version, VersionReq};
Andrew Walbranb27681f2022-02-23 15:11:52 +000025use nix::{fcntl::OFlag, unistd::pipe2};
Andrew Walbrandae07162021-03-12 17:05:20 +000026use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090027use std::borrow::Cow;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000028use std::fs::{remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000029use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000030use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000031use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000032use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Jiyong Park1612b902022-08-22 14:47:39 +090033use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000034use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090035use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090036use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000037use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090038use vsock::VsockStream;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000039use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
Alan Stokes0e82b502022-08-08 14:44:48 +010040use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090042use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000043
44const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
45
Jiyong Parkdcf17412022-02-08 15:07:23 +090046/// Version of the platform that crosvm currently implements. The format follows SemVer. This
47/// should be updated when there is a platform change in the crosvm side. Having this value here is
48/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
49/// APEX.
50const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
51
Andrew Walbrand15c5632022-02-03 13:38:31 +000052/// The exit status which crosvm returns when it has an error starting a VM.
53const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000054/// The exit status which crosvm returns when a VM requests a reboot.
55const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000056/// The exit status which crosvm returns when it crashes due to an error.
57const CROSVM_CRASH_STATUS: i32 = 33;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000058
Jiyong Parke6ed0f92022-06-22 00:13:00 +090059lazy_static! {
60 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
61 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010062 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090063 // Nested virtualization is slow, so we need a longer timeout.
64 Duration::from_secs(100)
65 } else {
66 Duration::from_secs(10)
67 };
68}
69
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000070/// Configuration for a VM to run with crosvm.
71#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000072pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000074 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000075 pub bootloader: Option<File>,
76 pub kernel: Option<File>,
77 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 pub disks: Vec<DiskFile>,
79 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000080 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000081 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090082 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090083 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090084 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000085 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090086 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000087 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090088 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090089 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090}
91
92/// A disk image to pass to crosvm for a VM.
93#[derive(Debug)]
94pub struct DiskFile {
95 pub image: File,
96 pub writable: bool,
97}
98
Andrew Walbran6b650662021-09-07 13:13:23 +000099/// The lifecycle state which the payload in the VM has reported itself to be in.
100///
101/// Note that the order of enum variants is significant; only forward transitions are allowed by
102/// [`VmInstance::update_payload_state`].
103#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
104pub enum PayloadState {
105 Starting,
106 Started,
107 Ready,
108 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900109 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000110}
111
Andrew Walbranf8d94112021-09-07 11:45:36 +0000112/// The current state of the VM itself.
113#[derive(Debug)]
114pub enum VmState {
115 /// The VM has not yet tried to start.
116 NotStarted {
117 ///The configuration needed to start the VM, if it has not yet been started.
118 config: CrosvmConfig,
119 },
120 /// The VM has been started.
121 Running {
122 /// The crosvm child process.
123 child: Arc<SharedChild>,
124 },
125 /// The VM died or was killed.
126 Dead,
127 /// The VM failed to start.
128 Failed,
129}
130
131impl VmState {
132 /// Tries to start the VM, if it is in the `NotStarted` state.
133 ///
134 /// Returns an error if the VM is in the wrong state, or fails to start.
135 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
136 let state = mem::replace(self, VmState::Failed);
137 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900138 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000139 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
140
Andrew Walbranf8d94112021-09-07 11:45:36 +0000141 // If this fails and returns an error, `self` will be left in the `Failed` state.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000142 let child = Arc::new(run_vm(config, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000143
144 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900145 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000146 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900147 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000148 });
149
Jiyong Parka4eebde2022-07-12 18:01:12 +0900150 if detect_hangup {
151 let child_clone = child.clone();
152 thread::spawn(move || {
153 instance.monitor_payload_hangup(child_clone);
154 });
155 }
156
Andrew Walbranf8d94112021-09-07 11:45:36 +0000157 // If it started correctly, update the state.
158 *self = VmState::Running { child };
159 Ok(())
160 } else {
161 *self = state;
162 bail!("VM already started or failed")
163 }
164 }
165}
166
167/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000168#[derive(Debug)]
169pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000170 /// The current state of the VM.
171 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000172 /// The CID assigned to the VM for vsock communication.
173 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000174 /// The name of the VM.
175 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000176 /// Whether the VM is a protected VM.
177 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000178 /// Directory of temporary files used by the VM while it is running.
179 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000180 /// The UID of the process which requested the VM.
181 pub requester_uid: u32,
182 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000183 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000184 /// The PID of the process which requested the VM. Note that this process may no longer exist
185 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000186 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000187 /// Callbacks to clients of the VM.
188 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900189 /// Input/output stream of the payload run in the VM.
190 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000191 /// VirtualMachineService binder object for the VM.
192 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900193 /// Recorded timestamp when the VM is started.
194 pub vm_start_timestamp: Mutex<Option<SystemTime>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000195 /// The latest lifecycle state which the payload reported itself to be in.
196 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900197 /// Represents the condition that payload_state was updated
198 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000199}
200
201impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000202 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
203 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000204 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000205 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000206 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000207 requester_sid: String,
208 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000209 ) -> Result<VmInstance, Error> {
210 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000211 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000212 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000213 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000214 Ok(VmInstance {
215 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000216 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000217 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000218 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000219 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000220 requester_uid,
221 requester_sid,
222 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 callbacks: Default::default(),
224 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000225 vm_service: Mutex::new(None),
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900226 vm_start_timestamp: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000227 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900228 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000229 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000230 }
231
Andrew Walbranf8d94112021-09-07 11:45:36 +0000232 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
233 /// the `VmInstance` is dropped.
234 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900235 *self.vm_start_timestamp.lock().unwrap() = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000236 self.vm_state.lock().unwrap().start(self.clone())
237 }
238
Jiyong Parka4eebde2022-07-12 18:01:12 +0900239 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
240 /// handles the event by updating the state, noityfing the event to clients by calling
241 /// callbacks, and removing temporary files for the VM.
242 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000243 let result = child.wait();
244 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900245 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
246 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000247 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000248
249 let mut vm_state = self.vm_state.lock().unwrap();
250 *vm_state = VmState::Dead;
251 // Ensure that the mutex is released before calling the callbacks.
252 drop(vm_state);
253
Jiyong Parka4eebde2022-07-12 18:01:12 +0900254 // Read the pipe to see if any failure reason is written
255 let mut failure_reason = String::new();
256 match failure_pipe_read.read_to_string(&mut failure_reason) {
257 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
258 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
259 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900260 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000261
Jiyong Parka4eebde2022-07-12 18:01:12 +0900262 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
263 // detected on the VM side (otherwise, it isn't a hangup), but in the
264 // monitor_payload_hangup function below which updates the payload state to Hangup.
265 let failure_reason =
266 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
267 Cow::from("HANGUP")
268 } else {
269 Cow::from(failure_reason)
270 };
271
Jiyong Parke558ab12022-07-07 20:18:55 +0900272 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000273
274 let death_reason = death_reason(&result, &failure_reason);
275 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900276
277 let vm_start_timestamp = self.vm_start_timestamp.lock().unwrap();
278 write_vm_exited_stats(
279 self.requester_uid as i32,
280 &self.name,
281 death_reason,
282 *vm_start_timestamp,
283 );
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000284
285 // Delete temporary files.
286 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000287 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000288 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000289 }
290
Jiyong Parka4eebde2022-07-12 18:01:12 +0900291 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
292 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
293 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
294 debug!("Starting to monitor hangup for Microdroid({})", child.id());
295 let (_, result) = self
296 .payload_state_updated
297 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
298 *s < PayloadState::Started
299 })
300 .unwrap();
301 let child_still_running = child.try_wait().ok() == Some(None);
302 if result.timed_out() && child_still_running {
303 error!(
304 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
305 child.id(),
306 BOOT_HANGUP_TIMEOUT.as_secs()
307 );
308 self.update_payload_state(PayloadState::Hangup).unwrap();
309 if let Err(e) = self.kill() {
310 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
311 }
312 }
313 }
314
Andrew Walbran6b650662021-09-07 13:13:23 +0000315 /// Returns the last reported state of the VM payload.
316 pub fn payload_state(&self) -> PayloadState {
317 *self.payload_state.lock().unwrap()
318 }
319
320 /// Updates the payload state to the given value, if it is a valid state transition.
321 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
322 let mut state_locked = self.payload_state.lock().unwrap();
323 // Only allow forward transitions, e.g. from starting to started or finished, not back in
324 // the other direction.
325 if new_state > *state_locked {
326 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900327 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000328 Ok(())
329 } else {
330 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
331 }
332 }
333
Andrew Walbranf8d94112021-09-07 11:45:36 +0000334 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900335 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000336 let vm_state = &*self.vm_state.lock().unwrap();
337 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900338 let id = child.id();
339 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000340 // TODO: Talk to crosvm to shutdown cleanly.
341 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900342 bail!("Error killing crosvm({}) instance: {}", id, e);
343 } else {
344 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000345 }
Inseob Kima446f802022-07-11 19:46:37 +0900346 } else {
347 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000348 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000349 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900350
351 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
352 /// to read the ramdump.
353 fn handle_ramdump(&self) -> Result<(), Error> {
354 let ramdump_path = self.temporary_directory.join("ramdump");
355 if std::fs::metadata(&ramdump_path)?.len() > 0 {
356 let ramdump = File::open(&ramdump_path)
357 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
358 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900359
360 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900361 }
362 Ok(())
363 }
Jiyong Park1612b902022-08-22 14:47:39 +0900364
365 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
366 let mut input = File::open(ramdump_path)
367 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
368
369 let pid = std::process::id() as i32;
370 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
371 .context("Failed to connect to tombstoned")?;
372 let mut output = conn
373 .text_output
374 .as_ref()
375 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
376
377 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
378 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
379
380 conn.notify_completion()?;
381 Ok(())
382 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000383}
384
Andrew Walbranb27681f2022-02-23 15:11:52 +0000385fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000386 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000387 match failure_reason {
388 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
389 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
390 }
391 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
392 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
393 }
394 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
395 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
396 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
397 }
Inseob Kim272f5722022-06-13 17:14:51 +0900398 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
399 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
400 }
401 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
402 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
403 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
404 }
405 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
406 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
407 }
408 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
409 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
410 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900411 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000412 _ => {}
413 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000414 match status.code() {
415 None => DeathReason::KILLED,
416 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000417 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000418 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000419 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000420 Some(_) => DeathReason::UNKNOWN,
421 }
422 } else {
423 DeathReason::INFRASTRUCTURE_ERROR
424 }
425}
426
Andrew Walbrand3a84182021-09-07 14:48:52 +0000427/// Starts an instance of `crosvm` to manage a new VM.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000428fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000429 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000430
431 let mut command = Command::new(CROSVM_PATH);
432 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000433 command
434 .arg("--extended-status")
435 .arg("run")
436 .arg("--disable-sandbox")
437 .arg("--cid")
438 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000439
Andrew Walbranf8650422021-06-09 15:54:09 +0000440 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000441 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000442
443 // 3 virtio-console devices + vsock = 4.
444 let virtio_pci_device_count = 4 + config.disks.len();
445 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
446 // enough.
447 let swiotlb_size_mib = 2 * virtio_pci_device_count;
448 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000449 }
450
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000451 if let Some(memory_mib) = config.memory_mib {
452 command.arg("--mem").arg(memory_mib.to_string());
453 }
454
Jiyong Park032615f2022-01-10 13:55:34 +0900455 if let Some(cpus) = config.cpus {
456 command.arg("--cpus").arg(cpus.to_string());
457 }
458
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900459 if !config.task_profiles.is_empty() {
460 command.arg("--task-profiles").arg(config.task_profiles.join(","));
461 }
462
Jiyong Parkfa91d702021-10-18 23:51:39 +0900463 // Keep track of what file descriptors should be mapped to the crosvm process.
464 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
465
Jiyong Park747d6362021-10-19 17:12:52 +0900466 // Setup the serial devices.
467 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000468 // 2. uart device: used to report the reason for the VM failing.
469 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900470 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000471 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900472 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900473 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
474 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000475 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
476 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
477 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900478 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900479
Jiyong Park747d6362021-10-19 17:12:52 +0900480 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
481 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
482 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
483 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900484 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000485 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
486 // /dev/ttyS1
487 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900488 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900489 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900490 // /dev/hvc1
491 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900492 // /dev/hvc2
493 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000494
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000495 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000496 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000497 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000498
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000499 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000500 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000501 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000502
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000503 if let Some(params) = &config.params {
504 command.arg("--params").arg(params);
505 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000506
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000507 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000508 command
509 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000510 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000511 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000512
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000513 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000514 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000515 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000516
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000517 debug!("Preserving FDs {:?}", preserved_fds);
518 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000519
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000520 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000521 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900522 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000523 Ok(result)
524}
525
526/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000527fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000528 if config.bootloader.is_none() && config.kernel.is_none() {
529 bail!("VM must have either a bootloader or a kernel image.");
530 }
531 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
532 bail!("Can't have both bootloader and kernel/initrd image.");
533 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900534 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
535 if !config.platform_version.matches(&version) {
536 bail!(
537 "Incompatible platform version. The config is compatible with platform version(s) \
538 {}, but the actual platform version is {}",
539 config.platform_version,
540 version
541 );
542 }
543
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000544 Ok(())
545}
546
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000547/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
548/// "/proc/self/fd/N" where N is the file descriptor.
549fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000550 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000551 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000552 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000553}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000554
555/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
556/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
557fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
558 if let Some(file) = file {
559 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
560 } else {
561 "type=sink".to_string()
562 }
563}
564
565/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
566fn create_pipe() -> Result<(File, File), Error> {
567 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
568 // SAFETY: We are the sole owners of these fds as they were just created.
569 let read_fd = unsafe { File::from_raw_fd(raw_read) };
570 let write_fd = unsafe { File::from_raw_fd(raw_write) };
571 Ok((read_fd, write_fd))
572}