blob: 49ae7c299f327a8b2b82dd85687f35b72f9eb7d0 [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};
Keir Fraserf25cb922022-11-23 14:26:00 +000027use rustutils::system_properties;
Andrew Walbrandae07162021-03-12 17:05:20 +000028use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090029use std::borrow::Cow;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090030use std::cmp::max;
31use std::fs::{read_to_string, remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000032use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000033use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000034use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000035use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Seungjae Yoo93430e82022-12-05 16:37:42 +090036use std::os::unix::process::ExitStatusExt;
Jiyong Park1612b902022-08-22 14:47:39 +090037use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000038use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090039use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090040use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000041use std::thread;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000042use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
David Brazdil528e0472022-10-10 15:06:02 +010043use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010044use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000045use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090046use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
David Brazdil73988ea2022-11-11 15:10:32 +000047use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000048
Keir Fraser13a956a2022-07-14 14:20:46 +000049/// external/crosvm
50use base::UnixSeqpacketListener;
51
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000052const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
53
Jiyong Parkdcf17412022-02-08 15:07:23 +090054/// Version of the platform that crosvm currently implements. The format follows SemVer. This
55/// should be updated when there is a platform change in the crosvm side. Having this value here is
56/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
57/// APEX.
58const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
59
Andrew Walbrand15c5632022-02-03 13:38:31 +000060/// The exit status which crosvm returns when it has an error starting a VM.
61const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000062/// The exit status which crosvm returns when a VM requests a reboot.
63const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000064/// The exit status which crosvm returns when it crashes due to an error.
65const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000066/// The exit status which crosvm returns when vcpu is stalled.
67const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000068
Seungjae Yoo6d265d92022-11-15 10:51:33 +090069const MILLIS_PER_SEC: i64 = 1000;
70
Jiyong Parke6ed0f92022-06-22 00:13:00 +090071lazy_static! {
72 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
73 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010074 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090075 // Nested virtualization is slow, so we need a longer timeout.
76 Duration::from_secs(100)
77 } else {
78 Duration::from_secs(10)
79 };
80}
81
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000082/// Configuration for a VM to run with crosvm.
83#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000084pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000085 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000086 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000087 pub bootloader: Option<File>,
88 pub kernel: Option<File>,
89 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090 pub disks: Vec<DiskFile>,
91 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000092 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000093 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090094 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090095 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090096 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000097 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090098 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000099 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900100 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900101 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102}
103
104/// A disk image to pass to crosvm for a VM.
105#[derive(Debug)]
106pub struct DiskFile {
107 pub image: File,
108 pub writable: bool,
109}
110
Andrew Walbran6b650662021-09-07 13:13:23 +0000111/// The lifecycle state which the payload in the VM has reported itself to be in.
112///
113/// Note that the order of enum variants is significant; only forward transitions are allowed by
114/// [`VmInstance::update_payload_state`].
115#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
116pub enum PayloadState {
117 Starting,
118 Started,
119 Ready,
120 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900121 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000122}
123
Andrew Walbranf8d94112021-09-07 11:45:36 +0000124/// The current state of the VM itself.
125#[derive(Debug)]
126pub enum VmState {
127 /// The VM has not yet tried to start.
128 NotStarted {
129 ///The configuration needed to start the VM, if it has not yet been started.
130 config: CrosvmConfig,
131 },
132 /// The VM has been started.
133 Running {
134 /// The crosvm child process.
135 child: Arc<SharedChild>,
136 },
137 /// The VM died or was killed.
138 Dead,
139 /// The VM failed to start.
140 Failed,
141}
142
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900143/// RSS values of VM and CrosVM process itself.
144#[derive(Copy, Clone, Debug, Default)]
145pub struct Rss {
146 pub vm: i64,
147 pub crosvm: i64,
148}
149
150/// Metrics regarding the VM.
151#[derive(Debug, Default)]
152pub struct VmMetric {
153 /// Recorded timestamp when the VM is started.
154 pub start_timestamp: Option<SystemTime>,
155 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
156 pub cpu_guest_time: Option<i64>,
157 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
158 pub rss: Option<Rss>,
159}
160
Andrew Walbranf8d94112021-09-07 11:45:36 +0000161impl VmState {
162 /// Tries to start the VM, if it is in the `NotStarted` state.
163 ///
164 /// Returns an error if the VM is in the wrong state, or fails to start.
165 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
166 let state = mem::replace(self, VmState::Failed);
167 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900168 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000169 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
170
Andrew Walbranf8d94112021-09-07 11:45:36 +0000171 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000172 let child =
173 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000174
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900175 let instance_monitor_status = instance.clone();
176 let child_monitor_status = child.clone();
177 thread::spawn(move || {
178 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
179 });
180
Andrew Walbranf8d94112021-09-07 11:45:36 +0000181 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900182 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000183 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900184 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000185 });
186
Jiyong Parka4eebde2022-07-12 18:01:12 +0900187 if detect_hangup {
188 let child_clone = child.clone();
189 thread::spawn(move || {
190 instance.monitor_payload_hangup(child_clone);
191 });
192 }
193
Andrew Walbranf8d94112021-09-07 11:45:36 +0000194 // If it started correctly, update the state.
195 *self = VmState::Running { child };
196 Ok(())
197 } else {
198 *self = state;
199 bail!("VM already started or failed")
200 }
201 }
202}
203
David Brazdil8cf8f482022-11-23 14:21:26 +0000204/// Internal struct that holds the handles to globally unique resources of a VM.
205#[derive(Debug)]
206pub struct VmContext {
207 #[allow(dead_code)] // Keeps the global context alive
208 global_context: Strong<dyn IGlobalVmContext>,
209 #[allow(dead_code)] // Keeps the server alive
210 vm_server: RpcServer,
211}
212
213impl VmContext {
214 /// Construct new VmContext.
215 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
216 VmContext { global_context, vm_server }
217 }
218}
219
Andrew Walbranf8d94112021-09-07 11:45:36 +0000220/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000221#[derive(Debug)]
222pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 /// The current state of the VM.
224 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000225 /// Global resources allocated for this VM.
226 #[allow(dead_code)] // Keeps the context alive
227 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000228 /// The CID assigned to the VM for vsock communication.
229 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000230 /// The name of the VM.
231 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000232 /// Whether the VM is a protected VM.
233 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 /// Directory of temporary files used by the VM while it is running.
235 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000236 /// The UID of the process which requested the VM.
237 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000238 /// The PID of the process which requested the VM. Note that this process may no longer exist
239 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000240 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000241 /// Callbacks to clients of the VM.
242 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000243 /// VirtualMachineService binder object for the VM.
244 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900245 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
246 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000247 /// The latest lifecycle state which the payload reported itself to be in.
248 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900249 /// Represents the condition that payload_state was updated
250 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000251}
252
253impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000254 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
255 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000256 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000257 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000258 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000259 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000260 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000261 ) -> Result<VmInstance, Error> {
262 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000263 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000264 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000265 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000266 Ok(VmInstance {
267 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100268 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000269 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000270 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000271 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000272 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000273 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000274 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000275 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000276 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900277 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000278 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900279 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000280 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000281 }
282
Andrew Walbranf8d94112021-09-07 11:45:36 +0000283 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
284 /// the `VmInstance` is dropped.
285 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900286 let mut vm_metric = self.vm_metric.lock().unwrap();
287 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000288 self.vm_state.lock().unwrap().start(self.clone())
289 }
290
Jiyong Parka4eebde2022-07-12 18:01:12 +0900291 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
292 /// handles the event by updating the state, noityfing the event to clients by calling
293 /// callbacks, and removing temporary files for the VM.
294 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000295 let result = child.wait();
296 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900297 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000298 Ok(status) => {
299 info!("crosvm({}) exited with status {}", child.id(), status);
300 if let Some(exit_status_code) = status.code() {
301 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
302 info!("detected vcpu stall on crosvm");
303 }
304 }
305 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000306 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000307
308 let mut vm_state = self.vm_state.lock().unwrap();
309 *vm_state = VmState::Dead;
310 // Ensure that the mutex is released before calling the callbacks.
311 drop(vm_state);
312
Jiyong Parka4eebde2022-07-12 18:01:12 +0900313 // Read the pipe to see if any failure reason is written
314 let mut failure_reason = String::new();
315 match failure_pipe_read.read_to_string(&mut failure_reason) {
316 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
317 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
318 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900319 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000320
Jiyong Parka4eebde2022-07-12 18:01:12 +0900321 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
322 // detected on the VM side (otherwise, it isn't a hangup), but in the
323 // monitor_payload_hangup function below which updates the payload state to Hangup.
324 let failure_reason =
325 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
326 Cow::from("HANGUP")
327 } else {
328 Cow::from(failure_reason)
329 };
330
Jiyong Parke558ab12022-07-07 20:18:55 +0900331 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000332
333 let death_reason = death_reason(&result, &failure_reason);
Seungjae Yoo93430e82022-12-05 16:37:42 +0900334 let exit_signal = exit_signal(&result);
335
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000336 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900337
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900338 let vm_metric = self.vm_metric.lock().unwrap();
Seungjae Yoo93430e82022-12-05 16:37:42 +0900339 write_vm_exited_stats(
340 self.requester_uid as i32,
341 &self.name,
342 death_reason,
343 exit_signal,
344 &*vm_metric,
345 );
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000346
347 // Delete temporary files.
348 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000349 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000350 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000351 }
352
Jiyong Parka4eebde2022-07-12 18:01:12 +0900353 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
354 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
355 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
356 debug!("Starting to monitor hangup for Microdroid({})", child.id());
357 let (_, result) = self
358 .payload_state_updated
359 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
360 *s < PayloadState::Started
361 })
362 .unwrap();
363 let child_still_running = child.try_wait().ok() == Some(None);
364 if result.timed_out() && child_still_running {
365 error!(
366 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
367 child.id(),
368 BOOT_HANGUP_TIMEOUT.as_secs()
369 );
370 self.update_payload_state(PayloadState::Hangup).unwrap();
371 if let Err(e) = self.kill() {
372 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
373 }
374 }
375 }
376
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900377 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
378 let pid = child.id();
379
380 loop {
381 {
382 // Check VM state
383 let vm_state = &*self.vm_state.lock().unwrap();
384 if let VmState::Dead = vm_state {
385 break;
386 }
387
388 let mut vm_metric = self.vm_metric.lock().unwrap();
389
390 // Get CPU Information
391 // TODO: Collect it once right before VM dies using SIGCHLD
392 if let Ok(guest_time) = get_guest_time(pid) {
393 vm_metric.cpu_guest_time = Some(guest_time);
394 } else {
395 error!("Failed to parse /proc/[pid]/stat");
396 }
397
398 // Get Memory Information
399 if let Ok(rss) = get_rss(pid) {
400 vm_metric.rss = match &vm_metric.rss {
401 Some(x) => Some(Rss::extract_max(x, &rss)),
402 None => Some(rss),
403 }
404 } else {
405 error!("Failed to parse /proc/[pid]/smaps");
406 }
407 }
408
409 thread::sleep(Duration::from_secs(1));
410 }
411 }
412
Andrew Walbran6b650662021-09-07 13:13:23 +0000413 /// Returns the last reported state of the VM payload.
414 pub fn payload_state(&self) -> PayloadState {
415 *self.payload_state.lock().unwrap()
416 }
417
418 /// Updates the payload state to the given value, if it is a valid state transition.
419 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
420 let mut state_locked = self.payload_state.lock().unwrap();
421 // Only allow forward transitions, e.g. from starting to started or finished, not back in
422 // the other direction.
423 if new_state > *state_locked {
424 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900425 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000426 Ok(())
427 } else {
428 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
429 }
430 }
431
Andrew Walbranf8d94112021-09-07 11:45:36 +0000432 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900433 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000434 let vm_state = &*self.vm_state.lock().unwrap();
435 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900436 let id = child.id();
437 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000438 // TODO: Talk to crosvm to shutdown cleanly.
439 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900440 bail!("Error killing crosvm({}) instance: {}", id, e);
441 } else {
442 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000443 }
Inseob Kima446f802022-07-11 19:46:37 +0900444 } else {
445 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000446 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000447 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900448
449 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
450 /// to read the ramdump.
451 fn handle_ramdump(&self) -> Result<(), Error> {
452 let ramdump_path = self.temporary_directory.join("ramdump");
453 if std::fs::metadata(&ramdump_path)?.len() > 0 {
454 let ramdump = File::open(&ramdump_path)
455 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
456 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900457
458 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900459 }
460 Ok(())
461 }
Jiyong Park1612b902022-08-22 14:47:39 +0900462
463 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
464 let mut input = File::open(ramdump_path)
465 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
466
467 let pid = std::process::id() as i32;
468 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
469 .context("Failed to connect to tombstoned")?;
470 let mut output = conn
471 .text_output
472 .as_ref()
473 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
474
475 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
476 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
477
478 conn.notify_completion()?;
479 Ok(())
480 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000481}
482
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900483impl Rss {
484 fn extract_max(x: &Rss, y: &Rss) -> Rss {
485 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
486 }
487}
488
489// Get guest time from /proc/[crosvm pid]/stat
490fn get_guest_time(pid: u32) -> Result<i64> {
491 let file = read_to_string(format!("/proc/{}/stat", pid))?;
492 let data_list: Vec<_> = file.split_whitespace().collect();
493
494 // Information about guest_time is at 43th place of the file split with the whitespace.
495 // Example of /proc/[pid]/stat :
496 // 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
497 // 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
498 if data_list.len() < 43 {
499 bail!("Failed to parse command result for getting guest time : {}", file);
500 }
501
502 let guest_time_ticks = data_list[42].parse::<i64>()?;
503 // SAFETY : It just returns an integer about CPU tick information.
504 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
505 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
506}
507
508// Get rss from /proc/[crosvm pid]/smaps
509fn get_rss(pid: u32) -> Result<Rss> {
510 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
511 let lines: Vec<_> = file.split('\n').collect();
512
513 let mut rss_vm_total = 0i64;
514 let mut rss_crosvm_total = 0i64;
515 let mut is_vm = false;
516 for line in lines {
517 if line.contains("crosvm_guest") {
518 is_vm = true;
519 } else if line.contains("Rss:") {
520 let data_list: Vec<_> = line.split_whitespace().collect();
521 if data_list.len() < 2 {
522 bail!("Failed to parse command result for getting rss :\n{}", line);
523 }
524 let rss = data_list[1].parse::<i64>()?;
525
526 if is_vm {
527 rss_vm_total += rss;
528 is_vm = false;
529 }
530 rss_crosvm_total += rss;
531 }
532 }
533
534 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
535}
536
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100537fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
538 if let Some(position) = failure_reason.find('|') {
539 // Separator indicates extra context information is present after the failure name.
540 error!("Failure info: {}", &failure_reason[(position + 1)..]);
541 failure_reason = &failure_reason[..position];
542 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000543 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000544 match failure_reason {
545 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
546 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
547 }
548 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
549 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
550 }
551 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
552 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
553 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
554 }
Inseob Kim272f5722022-06-13 17:14:51 +0900555 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
556 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
557 }
558 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
559 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
560 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
561 }
562 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
563 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
564 }
565 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
566 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
567 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900568 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000569 _ => {}
570 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000571 match status.code() {
572 None => DeathReason::KILLED,
573 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000574 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000575 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000576 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000577 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000578 Some(_) => DeathReason::UNKNOWN,
579 }
580 } else {
581 DeathReason::INFRASTRUCTURE_ERROR
582 }
583}
584
Seungjae Yoo93430e82022-12-05 16:37:42 +0900585fn exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32> {
586 match result {
587 Ok(status) => status.signal(),
588 Err(_) => None,
589 }
590}
591
Andrew Walbrand3a84182021-09-07 14:48:52 +0000592/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000593fn run_vm(
594 config: CrosvmConfig,
595 temporary_directory: &Path,
596 failure_pipe_write: File,
597) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000598 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000599
600 let mut command = Command::new(CROSVM_PATH);
601 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000602 command
603 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900604 // Configure the logger for the crosvm process to silence logs from the disk crate which
605 // don't provide much information to us (but do spamming us).
606 .arg("--log-level")
607 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000608 .arg("run")
609 .arg("--disable-sandbox")
610 .arg("--cid")
611 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000612
Keir Fraserf25cb922022-11-23 14:26:00 +0000613 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
614 command.arg("--balloon-page-reporting");
615 } else {
616 command.arg("--no-balloon");
617 }
618
Andrew Walbranf8650422021-06-09 15:54:09 +0000619 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000620 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000621
622 // 3 virtio-console devices + vsock = 4.
623 let virtio_pci_device_count = 4 + config.disks.len();
624 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
625 // enough.
626 let swiotlb_size_mib = 2 * virtio_pci_device_count;
627 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000628 }
629
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000630 if let Some(memory_mib) = config.memory_mib {
631 command.arg("--mem").arg(memory_mib.to_string());
632 }
633
Jiyong Park032615f2022-01-10 13:55:34 +0900634 if let Some(cpus) = config.cpus {
635 command.arg("--cpus").arg(cpus.to_string());
636 }
637
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900638 if !config.task_profiles.is_empty() {
639 command.arg("--task-profiles").arg(config.task_profiles.join(","));
640 }
641
Jiyong Parkfa91d702021-10-18 23:51:39 +0900642 // Keep track of what file descriptors should be mapped to the crosvm process.
643 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
644
Jiyong Park747d6362021-10-19 17:12:52 +0900645 // Setup the serial devices.
646 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000647 // 2. uart device: used to report the reason for the VM failing.
648 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900649 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000650 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900651 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900652 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
653 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000654 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
655 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
656 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900657 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900658
Jiyong Park747d6362021-10-19 17:12:52 +0900659 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
660 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
661 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
662 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900663 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000664 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
665 // /dev/ttyS1
666 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900667 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900668 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900669 // /dev/hvc1
670 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900671 // /dev/hvc2
672 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000673
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000674 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000675 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000676 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000677
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000678 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000679 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000680 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000681
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000682 if let Some(params) = &config.params {
683 command.arg("--params").arg(params);
684 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000685
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000686 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000687 command
688 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000689 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000690 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000691
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000692 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000693 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000694 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000695
Keir Fraser13a956a2022-07-14 14:20:46 +0000696 let control_server_socket =
697 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
698 .context("failed to create control server")?;
699 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
700
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000701 debug!("Preserving FDs {:?}", preserved_fds);
702 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000703
Jaewan Kimb2814062022-11-14 13:21:40 +0900704 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900705 print_crosvm_args(&command);
706
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000707 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900708 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000709 Ok(result)
710}
711
712/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000713fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000714 if config.bootloader.is_none() && config.kernel.is_none() {
715 bail!("VM must have either a bootloader or a kernel image.");
716 }
717 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
718 bail!("Can't have both bootloader and kernel/initrd image.");
719 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900720 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
721 if !config.platform_version.matches(&version) {
722 bail!(
723 "Incompatible platform version. The config is compatible with platform version(s) \
724 {}, but the actual platform version is {}",
725 config.platform_version,
726 version
727 );
728 }
729
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000730 Ok(())
731}
732
Jiyong Park2d736562022-10-24 22:40:12 +0900733/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
734/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
735/// unmodified.
736fn print_crosvm_args(command: &Command) {
737 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
738 info!(
739 "Running crosvm with args: {:?}",
740 command
741 .get_args()
742 .map(|s| s.to_string_lossy())
743 .map(|s| {
744 re.replace_all(&s, |caps: &Captures| {
745 let path = &caps[0];
746 if let Ok(realpath) = std::fs::canonicalize(path) {
747 format!("{} ({})", path, realpath.to_string_lossy())
748 } else {
749 path.to_owned()
750 }
751 })
752 .into_owned()
753 })
754 .collect::<Vec<_>>()
755 );
756}
757
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000758/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
759/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000760fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000761 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000762 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000763 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000764}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000765
766/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
767/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
768fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
769 if let Some(file) = file {
770 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
771 } else {
772 "type=sink".to_string()
773 }
774}
775
776/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
777fn create_pipe() -> Result<(File, File), Error> {
778 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
779 // SAFETY: We are the sole owners of these fds as they were just created.
780 let read_fd = unsafe { File::from_raw_fd(raw_read) };
781 let write_fd = unsafe { File::from_raw_fd(raw_write) };
782 Ok((read_fd, write_fd))
783}