blob: 68324c50f34dadc04726f144f32143af80495096 [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
David Brazdil41d1a872022-10-05 14:44:19 +010017use crate::aidl::{Cid, VirtualMachineCallbacks};
Seungjae Yoob4c07ba2022-08-12 04:44:52 +000018use crate::atom::write_vm_exited_stats;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090019use anyhow::{anyhow, bail, Context, Error, Result};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090021use lazy_static::lazy_static;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090022use libc::{sysconf, _SC_CLK_TCK};
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};
Jiyong Park2d736562022-10-24 22:40:12 +090026use regex::{Captures, Regex};
Andrew Walbrandae07162021-03-12 17:05:20 +000027use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090028use std::borrow::Cow;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090029use std::cmp::max;
30use std::fs::{read_to_string, remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000031use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000032use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000033use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000034use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Jiyong Park1612b902022-08-22 14:47:39 +090035use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000036use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090037use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090038use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000039use std::thread;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000040use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
David Brazdil528e0472022-10-10 15:06:02 +010041use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010042use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090044use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000045
Keir Fraser13a956a2022-07-14 14:20:46 +000046/// external/crosvm
47use base::UnixSeqpacketListener;
48
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000049const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
50
Jiyong Parkdcf17412022-02-08 15:07:23 +090051/// Version of the platform that crosvm currently implements. The format follows SemVer. This
52/// should be updated when there is a platform change in the crosvm side. Having this value here is
53/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
54/// APEX.
55const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
56
Andrew Walbrand15c5632022-02-03 13:38:31 +000057/// The exit status which crosvm returns when it has an error starting a VM.
58const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000059/// The exit status which crosvm returns when a VM requests a reboot.
60const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000061/// The exit status which crosvm returns when it crashes due to an error.
62const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000063/// The exit status which crosvm returns when vcpu is stalled.
64const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000065
Seungjae Yoo6d265d92022-11-15 10:51:33 +090066const MILLIS_PER_SEC: i64 = 1000;
67
Jiyong Parke6ed0f92022-06-22 00:13:00 +090068lazy_static! {
69 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
70 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010071 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090072 // Nested virtualization is slow, so we need a longer timeout.
73 Duration::from_secs(100)
74 } else {
75 Duration::from_secs(10)
76 };
77}
78
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000079/// Configuration for a VM to run with crosvm.
80#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000081pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000082 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000083 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000084 pub bootloader: Option<File>,
85 pub kernel: Option<File>,
86 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087 pub disks: Vec<DiskFile>,
88 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000089 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000090 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090091 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090092 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090093 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000094 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090095 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000096 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090097 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090098 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000099}
100
101/// A disk image to pass to crosvm for a VM.
102#[derive(Debug)]
103pub struct DiskFile {
104 pub image: File,
105 pub writable: bool,
106}
107
Andrew Walbran6b650662021-09-07 13:13:23 +0000108/// The lifecycle state which the payload in the VM has reported itself to be in.
109///
110/// Note that the order of enum variants is significant; only forward transitions are allowed by
111/// [`VmInstance::update_payload_state`].
112#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
113pub enum PayloadState {
114 Starting,
115 Started,
116 Ready,
117 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900118 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000119}
120
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121/// The current state of the VM itself.
122#[derive(Debug)]
123pub enum VmState {
124 /// The VM has not yet tried to start.
125 NotStarted {
126 ///The configuration needed to start the VM, if it has not yet been started.
127 config: CrosvmConfig,
128 },
129 /// The VM has been started.
130 Running {
131 /// The crosvm child process.
132 child: Arc<SharedChild>,
133 },
134 /// The VM died or was killed.
135 Dead,
136 /// The VM failed to start.
137 Failed,
138}
139
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900140/// RSS values of VM and CrosVM process itself.
141#[derive(Copy, Clone, Debug, Default)]
142pub struct Rss {
143 pub vm: i64,
144 pub crosvm: i64,
145}
146
147/// Metrics regarding the VM.
148#[derive(Debug, Default)]
149pub struct VmMetric {
150 /// Recorded timestamp when the VM is started.
151 pub start_timestamp: Option<SystemTime>,
152 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
153 pub cpu_guest_time: Option<i64>,
154 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
155 pub rss: Option<Rss>,
156}
157
Andrew Walbranf8d94112021-09-07 11:45:36 +0000158impl VmState {
159 /// Tries to start the VM, if it is in the `NotStarted` state.
160 ///
161 /// Returns an error if the VM is in the wrong state, or fails to start.
162 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
163 let state = mem::replace(self, VmState::Failed);
164 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900165 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000166 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
167
Andrew Walbranf8d94112021-09-07 11:45:36 +0000168 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000169 let child =
170 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000171
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900172 let instance_monitor_status = instance.clone();
173 let child_monitor_status = child.clone();
174 thread::spawn(move || {
175 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
176 });
177
Andrew Walbranf8d94112021-09-07 11:45:36 +0000178 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900179 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000180 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900181 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000182 });
183
Jiyong Parka4eebde2022-07-12 18:01:12 +0900184 if detect_hangup {
185 let child_clone = child.clone();
186 thread::spawn(move || {
187 instance.monitor_payload_hangup(child_clone);
188 });
189 }
190
Andrew Walbranf8d94112021-09-07 11:45:36 +0000191 // If it started correctly, update the state.
192 *self = VmState::Running { child };
193 Ok(())
194 } else {
195 *self = state;
196 bail!("VM already started or failed")
197 }
198 }
199}
200
201/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000202#[derive(Debug)]
203pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000204 /// The current state of the VM.
205 pub vm_state: Mutex<VmState>,
David Brazdil528e0472022-10-10 15:06:02 +0100206 /// Handle to global resources allocated for this VM.
207 #[allow(dead_code)] // The handle is never read, we only need to hold it.
208 vm_context: Strong<dyn IGlobalVmContext>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000209 /// The CID assigned to the VM for vsock communication.
210 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000211 /// The name of the VM.
212 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000213 /// Whether the VM is a protected VM.
214 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000215 /// Directory of temporary files used by the VM while it is running.
216 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000217 /// The UID of the process which requested the VM.
218 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000219 /// The PID of the process which requested the VM. Note that this process may no longer exist
220 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000221 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000222 /// Callbacks to clients of the VM.
223 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000224 /// VirtualMachineService binder object for the VM.
225 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900226 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
227 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000228 /// The latest lifecycle state which the payload reported itself to be in.
229 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900230 /// Represents the condition that payload_state was updated
231 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000232}
233
234impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000235 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
236 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000237 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000238 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000239 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000240 requester_debug_pid: i32,
David Brazdil528e0472022-10-10 15:06:02 +0100241 vm_context: Strong<dyn IGlobalVmContext>,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000242 ) -> Result<VmInstance, Error> {
243 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000244 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000245 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000246 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000247 Ok(VmInstance {
248 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100249 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000250 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000251 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000252 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000253 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000254 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000255 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000256 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000257 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900258 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000259 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900260 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000261 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000262 }
263
Andrew Walbranf8d94112021-09-07 11:45:36 +0000264 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
265 /// the `VmInstance` is dropped.
266 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900267 let mut vm_metric = self.vm_metric.lock().unwrap();
268 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000269 self.vm_state.lock().unwrap().start(self.clone())
270 }
271
Jiyong Parka4eebde2022-07-12 18:01:12 +0900272 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
273 /// handles the event by updating the state, noityfing the event to clients by calling
274 /// callbacks, and removing temporary files for the VM.
275 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000276 let result = child.wait();
277 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900278 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000279 Ok(status) => {
280 info!("crosvm({}) exited with status {}", child.id(), status);
281 if let Some(exit_status_code) = status.code() {
282 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
283 info!("detected vcpu stall on crosvm");
284 }
285 }
286 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000287 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000288
289 let mut vm_state = self.vm_state.lock().unwrap();
290 *vm_state = VmState::Dead;
291 // Ensure that the mutex is released before calling the callbacks.
292 drop(vm_state);
293
Jiyong Parka4eebde2022-07-12 18:01:12 +0900294 // Read the pipe to see if any failure reason is written
295 let mut failure_reason = String::new();
296 match failure_pipe_read.read_to_string(&mut failure_reason) {
297 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
298 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
299 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900300 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000301
Jiyong Parka4eebde2022-07-12 18:01:12 +0900302 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
303 // detected on the VM side (otherwise, it isn't a hangup), but in the
304 // monitor_payload_hangup function below which updates the payload state to Hangup.
305 let failure_reason =
306 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
307 Cow::from("HANGUP")
308 } else {
309 Cow::from(failure_reason)
310 };
311
Jiyong Parke558ab12022-07-07 20:18:55 +0900312 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000313
314 let death_reason = death_reason(&result, &failure_reason);
315 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900316
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900317 let vm_metric = self.vm_metric.lock().unwrap();
318 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000319
320 // Delete temporary files.
321 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000322 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000323 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000324 }
325
Jiyong Parka4eebde2022-07-12 18:01:12 +0900326 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
327 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
328 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
329 debug!("Starting to monitor hangup for Microdroid({})", child.id());
330 let (_, result) = self
331 .payload_state_updated
332 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
333 *s < PayloadState::Started
334 })
335 .unwrap();
336 let child_still_running = child.try_wait().ok() == Some(None);
337 if result.timed_out() && child_still_running {
338 error!(
339 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
340 child.id(),
341 BOOT_HANGUP_TIMEOUT.as_secs()
342 );
343 self.update_payload_state(PayloadState::Hangup).unwrap();
344 if let Err(e) = self.kill() {
345 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
346 }
347 }
348 }
349
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900350 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
351 let pid = child.id();
352
353 loop {
354 {
355 // Check VM state
356 let vm_state = &*self.vm_state.lock().unwrap();
357 if let VmState::Dead = vm_state {
358 break;
359 }
360
361 let mut vm_metric = self.vm_metric.lock().unwrap();
362
363 // Get CPU Information
364 // TODO: Collect it once right before VM dies using SIGCHLD
365 if let Ok(guest_time) = get_guest_time(pid) {
366 vm_metric.cpu_guest_time = Some(guest_time);
367 } else {
368 error!("Failed to parse /proc/[pid]/stat");
369 }
370
371 // Get Memory Information
372 if let Ok(rss) = get_rss(pid) {
373 vm_metric.rss = match &vm_metric.rss {
374 Some(x) => Some(Rss::extract_max(x, &rss)),
375 None => Some(rss),
376 }
377 } else {
378 error!("Failed to parse /proc/[pid]/smaps");
379 }
380 }
381
382 thread::sleep(Duration::from_secs(1));
383 }
384 }
385
Andrew Walbran6b650662021-09-07 13:13:23 +0000386 /// Returns the last reported state of the VM payload.
387 pub fn payload_state(&self) -> PayloadState {
388 *self.payload_state.lock().unwrap()
389 }
390
391 /// Updates the payload state to the given value, if it is a valid state transition.
392 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
393 let mut state_locked = self.payload_state.lock().unwrap();
394 // Only allow forward transitions, e.g. from starting to started or finished, not back in
395 // the other direction.
396 if new_state > *state_locked {
397 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900398 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000399 Ok(())
400 } else {
401 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
402 }
403 }
404
Andrew Walbranf8d94112021-09-07 11:45:36 +0000405 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900406 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000407 let vm_state = &*self.vm_state.lock().unwrap();
408 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900409 let id = child.id();
410 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000411 // TODO: Talk to crosvm to shutdown cleanly.
412 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900413 bail!("Error killing crosvm({}) instance: {}", id, e);
414 } else {
415 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000416 }
Inseob Kima446f802022-07-11 19:46:37 +0900417 } else {
418 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000419 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000420 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900421
422 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
423 /// to read the ramdump.
424 fn handle_ramdump(&self) -> Result<(), Error> {
425 let ramdump_path = self.temporary_directory.join("ramdump");
426 if std::fs::metadata(&ramdump_path)?.len() > 0 {
427 let ramdump = File::open(&ramdump_path)
428 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
429 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900430
431 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900432 }
433 Ok(())
434 }
Jiyong Park1612b902022-08-22 14:47:39 +0900435
436 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
437 let mut input = File::open(ramdump_path)
438 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
439
440 let pid = std::process::id() as i32;
441 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
442 .context("Failed to connect to tombstoned")?;
443 let mut output = conn
444 .text_output
445 .as_ref()
446 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
447
448 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
449 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
450
451 conn.notify_completion()?;
452 Ok(())
453 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000454}
455
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900456impl Rss {
457 fn extract_max(x: &Rss, y: &Rss) -> Rss {
458 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
459 }
460}
461
462// Get guest time from /proc/[crosvm pid]/stat
463fn get_guest_time(pid: u32) -> Result<i64> {
464 let file = read_to_string(format!("/proc/{}/stat", pid))?;
465 let data_list: Vec<_> = file.split_whitespace().collect();
466
467 // Information about guest_time is at 43th place of the file split with the whitespace.
468 // Example of /proc/[pid]/stat :
469 // 6603 (kworker/104:1H-kblockd) I 2 0 0 0 -1 69238880 0 0 0 0 0 88 0 0 0 -20 1 0 1845 0 0
470 // 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 0 0 0 17 104 0 0 0 0 0 0 0 0 0 0 0 0 0
471 if data_list.len() < 43 {
472 bail!("Failed to parse command result for getting guest time : {}", file);
473 }
474
475 let guest_time_ticks = data_list[42].parse::<i64>()?;
476 // SAFETY : It just returns an integer about CPU tick information.
477 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
478 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
479}
480
481// Get rss from /proc/[crosvm pid]/smaps
482fn get_rss(pid: u32) -> Result<Rss> {
483 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
484 let lines: Vec<_> = file.split('\n').collect();
485
486 let mut rss_vm_total = 0i64;
487 let mut rss_crosvm_total = 0i64;
488 let mut is_vm = false;
489 for line in lines {
490 if line.contains("crosvm_guest") {
491 is_vm = true;
492 } else if line.contains("Rss:") {
493 let data_list: Vec<_> = line.split_whitespace().collect();
494 if data_list.len() < 2 {
495 bail!("Failed to parse command result for getting rss :\n{}", line);
496 }
497 let rss = data_list[1].parse::<i64>()?;
498
499 if is_vm {
500 rss_vm_total += rss;
501 is_vm = false;
502 }
503 rss_crosvm_total += rss;
504 }
505 }
506
507 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
508}
509
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100510fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
511 if let Some(position) = failure_reason.find('|') {
512 // Separator indicates extra context information is present after the failure name.
513 error!("Failure info: {}", &failure_reason[(position + 1)..]);
514 failure_reason = &failure_reason[..position];
515 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000516 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000517 match failure_reason {
518 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
519 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
520 }
521 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
522 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
523 }
524 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
525 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
526 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
527 }
Inseob Kim272f5722022-06-13 17:14:51 +0900528 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
529 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
530 }
531 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
532 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
533 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
534 }
535 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
536 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
537 }
538 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
539 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
540 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900541 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000542 _ => {}
543 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000544 match status.code() {
545 None => DeathReason::KILLED,
546 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000547 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000548 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000549 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000550 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000551 Some(_) => DeathReason::UNKNOWN,
552 }
553 } else {
554 DeathReason::INFRASTRUCTURE_ERROR
555 }
556}
557
Andrew Walbrand3a84182021-09-07 14:48:52 +0000558/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000559fn run_vm(
560 config: CrosvmConfig,
561 temporary_directory: &Path,
562 failure_pipe_write: File,
563) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000564 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000565
566 let mut command = Command::new(CROSVM_PATH);
567 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000568 command
569 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900570 // Configure the logger for the crosvm process to silence logs from the disk crate which
571 // don't provide much information to us (but do spamming us).
572 .arg("--log-level")
573 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000574 .arg("run")
575 .arg("--disable-sandbox")
Keir Fraser72762722022-09-30 16:12:06 +0000576 .arg("--no-balloon")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000577 .arg("--cid")
578 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000579
Andrew Walbranf8650422021-06-09 15:54:09 +0000580 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000581 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000582
583 // 3 virtio-console devices + vsock = 4.
584 let virtio_pci_device_count = 4 + config.disks.len();
585 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
586 // enough.
587 let swiotlb_size_mib = 2 * virtio_pci_device_count;
588 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000589 }
590
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000591 if let Some(memory_mib) = config.memory_mib {
592 command.arg("--mem").arg(memory_mib.to_string());
593 }
594
Jiyong Park032615f2022-01-10 13:55:34 +0900595 if let Some(cpus) = config.cpus {
596 command.arg("--cpus").arg(cpus.to_string());
597 }
598
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900599 if !config.task_profiles.is_empty() {
600 command.arg("--task-profiles").arg(config.task_profiles.join(","));
601 }
602
Jiyong Parkfa91d702021-10-18 23:51:39 +0900603 // Keep track of what file descriptors should be mapped to the crosvm process.
604 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
605
Jiyong Park747d6362021-10-19 17:12:52 +0900606 // Setup the serial devices.
607 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000608 // 2. uart device: used to report the reason for the VM failing.
609 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900610 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000611 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900612 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900613 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
614 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000615 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
616 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
617 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900618 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900619
Jiyong Park747d6362021-10-19 17:12:52 +0900620 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
621 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
622 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
623 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900624 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000625 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
626 // /dev/ttyS1
627 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900628 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900629 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900630 // /dev/hvc1
631 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900632 // /dev/hvc2
633 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000634
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000635 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000636 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000637 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000638
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000639 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000640 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000641 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000642
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000643 if let Some(params) = &config.params {
644 command.arg("--params").arg(params);
645 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000646
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000647 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000648 command
649 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000650 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000651 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000652
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000653 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000654 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000655 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000656
Keir Fraser13a956a2022-07-14 14:20:46 +0000657 let control_server_socket =
658 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
659 .context("failed to create control server")?;
660 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
661
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000662 debug!("Preserving FDs {:?}", preserved_fds);
663 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000664
Jaewan Kimb2814062022-11-14 13:21:40 +0900665 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900666 print_crosvm_args(&command);
667
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000668 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900669 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000670 Ok(result)
671}
672
673/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000674fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000675 if config.bootloader.is_none() && config.kernel.is_none() {
676 bail!("VM must have either a bootloader or a kernel image.");
677 }
678 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
679 bail!("Can't have both bootloader and kernel/initrd image.");
680 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900681 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
682 if !config.platform_version.matches(&version) {
683 bail!(
684 "Incompatible platform version. The config is compatible with platform version(s) \
685 {}, but the actual platform version is {}",
686 config.platform_version,
687 version
688 );
689 }
690
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000691 Ok(())
692}
693
Jiyong Park2d736562022-10-24 22:40:12 +0900694/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
695/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
696/// unmodified.
697fn print_crosvm_args(command: &Command) {
698 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
699 info!(
700 "Running crosvm with args: {:?}",
701 command
702 .get_args()
703 .map(|s| s.to_string_lossy())
704 .map(|s| {
705 re.replace_all(&s, |caps: &Captures| {
706 let path = &caps[0];
707 if let Ok(realpath) = std::fs::canonicalize(path) {
708 format!("{} ({})", path, realpath.to_string_lossy())
709 } else {
710 path.to_owned()
711 }
712 })
713 .into_owned()
714 })
715 .collect::<Vec<_>>()
716 );
717}
718
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000719/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
720/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000721fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000722 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000723 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000724 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000725}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000726
727/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
728/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
729fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
730 if let Some(file) = file {
731 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
732 } else {
733 "type=sink".to_string()
734 }
735}
736
737/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
738fn create_pipe() -> Result<(File, File), Error> {
739 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
740 // SAFETY: We are the sole owners of these fds as they were just created.
741 let read_fd = unsafe { File::from_raw_fd(raw_read) };
742 let write_fd = unsafe { File::from_raw_fd(raw_write) };
743 Ok((read_fd, write_fd))
744}