blob: 76e18dbdcab9ce0c151091d34cf85dbb10d2f059 [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};
David Brazdil73988ea2022-11-11 15:10:32 +000045use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000046
Keir Fraser13a956a2022-07-14 14:20:46 +000047/// external/crosvm
48use base::UnixSeqpacketListener;
49
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
51
Jiyong Parkdcf17412022-02-08 15:07:23 +090052/// Version of the platform that crosvm currently implements. The format follows SemVer. This
53/// should be updated when there is a platform change in the crosvm side. Having this value here is
54/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
55/// APEX.
56const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
57
Andrew Walbrand15c5632022-02-03 13:38:31 +000058/// The exit status which crosvm returns when it has an error starting a VM.
59const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000060/// The exit status which crosvm returns when a VM requests a reboot.
61const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000062/// The exit status which crosvm returns when it crashes due to an error.
63const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000064/// The exit status which crosvm returns when vcpu is stalled.
65const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000066
Seungjae Yoo6d265d92022-11-15 10:51:33 +090067const MILLIS_PER_SEC: i64 = 1000;
68
Jiyong Parke6ed0f92022-06-22 00:13:00 +090069lazy_static! {
70 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
71 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010072 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090073 // Nested virtualization is slow, so we need a longer timeout.
74 Duration::from_secs(100)
75 } else {
76 Duration::from_secs(10)
77 };
78}
79
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000080/// Configuration for a VM to run with crosvm.
81#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000082pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000083 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000084 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000085 pub bootloader: Option<File>,
86 pub kernel: Option<File>,
87 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000088 pub disks: Vec<DiskFile>,
89 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000090 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000091 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090092 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090093 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090094 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000095 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090096 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000097 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090098 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090099 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100}
101
102/// A disk image to pass to crosvm for a VM.
103#[derive(Debug)]
104pub struct DiskFile {
105 pub image: File,
106 pub writable: bool,
107}
108
Andrew Walbran6b650662021-09-07 13:13:23 +0000109/// The lifecycle state which the payload in the VM has reported itself to be in.
110///
111/// Note that the order of enum variants is significant; only forward transitions are allowed by
112/// [`VmInstance::update_payload_state`].
113#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
114pub enum PayloadState {
115 Starting,
116 Started,
117 Ready,
118 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900119 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000120}
121
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122/// The current state of the VM itself.
123#[derive(Debug)]
124pub enum VmState {
125 /// The VM has not yet tried to start.
126 NotStarted {
127 ///The configuration needed to start the VM, if it has not yet been started.
128 config: CrosvmConfig,
129 },
130 /// The VM has been started.
131 Running {
132 /// The crosvm child process.
133 child: Arc<SharedChild>,
134 },
135 /// The VM died or was killed.
136 Dead,
137 /// The VM failed to start.
138 Failed,
139}
140
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900141/// RSS values of VM and CrosVM process itself.
142#[derive(Copy, Clone, Debug, Default)]
143pub struct Rss {
144 pub vm: i64,
145 pub crosvm: i64,
146}
147
148/// Metrics regarding the VM.
149#[derive(Debug, Default)]
150pub struct VmMetric {
151 /// Recorded timestamp when the VM is started.
152 pub start_timestamp: Option<SystemTime>,
153 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
154 pub cpu_guest_time: Option<i64>,
155 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
156 pub rss: Option<Rss>,
157}
158
Andrew Walbranf8d94112021-09-07 11:45:36 +0000159impl VmState {
160 /// Tries to start the VM, if it is in the `NotStarted` state.
161 ///
162 /// Returns an error if the VM is in the wrong state, or fails to start.
163 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
164 let state = mem::replace(self, VmState::Failed);
165 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900166 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000167 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
168
Andrew Walbranf8d94112021-09-07 11:45:36 +0000169 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000170 let child =
171 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000172
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900173 let instance_monitor_status = instance.clone();
174 let child_monitor_status = child.clone();
175 thread::spawn(move || {
176 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
177 });
178
Andrew Walbranf8d94112021-09-07 11:45:36 +0000179 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900180 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000181 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900182 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000183 });
184
Jiyong Parka4eebde2022-07-12 18:01:12 +0900185 if detect_hangup {
186 let child_clone = child.clone();
187 thread::spawn(move || {
188 instance.monitor_payload_hangup(child_clone);
189 });
190 }
191
Andrew Walbranf8d94112021-09-07 11:45:36 +0000192 // If it started correctly, update the state.
193 *self = VmState::Running { child };
194 Ok(())
195 } else {
196 *self = state;
197 bail!("VM already started or failed")
198 }
199 }
200}
201
David Brazdil8cf8f482022-11-23 14:21:26 +0000202/// Internal struct that holds the handles to globally unique resources of a VM.
203#[derive(Debug)]
204pub struct VmContext {
205 #[allow(dead_code)] // Keeps the global context alive
206 global_context: Strong<dyn IGlobalVmContext>,
207 #[allow(dead_code)] // Keeps the server alive
208 vm_server: RpcServer,
209}
210
211impl VmContext {
212 /// Construct new VmContext.
213 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
214 VmContext { global_context, vm_server }
215 }
216}
217
Andrew Walbranf8d94112021-09-07 11:45:36 +0000218/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000219#[derive(Debug)]
220pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000221 /// The current state of the VM.
222 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000223 /// Global resources allocated for this VM.
224 #[allow(dead_code)] // Keeps the context alive
225 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000226 /// The CID assigned to the VM for vsock communication.
227 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000228 /// The name of the VM.
229 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000230 /// Whether the VM is a protected VM.
231 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000232 /// Directory of temporary files used by the VM while it is running.
233 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000234 /// The UID of the process which requested the VM.
235 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000236 /// The PID of the process which requested the VM. Note that this process may no longer exist
237 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000238 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000239 /// Callbacks to clients of the VM.
240 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000241 /// VirtualMachineService binder object for the VM.
242 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900243 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
244 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000245 /// The latest lifecycle state which the payload reported itself to be in.
246 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900247 /// Represents the condition that payload_state was updated
248 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000249}
250
251impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000252 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
253 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000254 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000255 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000256 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000257 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000258 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000259 ) -> Result<VmInstance, Error> {
260 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000261 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000262 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000263 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000264 Ok(VmInstance {
265 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100266 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000267 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000268 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000269 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000270 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000271 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000272 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000273 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000274 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900275 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000276 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900277 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000278 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000279 }
280
Andrew Walbranf8d94112021-09-07 11:45:36 +0000281 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
282 /// the `VmInstance` is dropped.
283 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900284 let mut vm_metric = self.vm_metric.lock().unwrap();
285 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000286 self.vm_state.lock().unwrap().start(self.clone())
287 }
288
Jiyong Parka4eebde2022-07-12 18:01:12 +0900289 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
290 /// handles the event by updating the state, noityfing the event to clients by calling
291 /// callbacks, and removing temporary files for the VM.
292 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000293 let result = child.wait();
294 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900295 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000296 Ok(status) => {
297 info!("crosvm({}) exited with status {}", child.id(), status);
298 if let Some(exit_status_code) = status.code() {
299 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
300 info!("detected vcpu stall on crosvm");
301 }
302 }
303 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000304 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000305
306 let mut vm_state = self.vm_state.lock().unwrap();
307 *vm_state = VmState::Dead;
308 // Ensure that the mutex is released before calling the callbacks.
309 drop(vm_state);
310
Jiyong Parka4eebde2022-07-12 18:01:12 +0900311 // Read the pipe to see if any failure reason is written
312 let mut failure_reason = String::new();
313 match failure_pipe_read.read_to_string(&mut failure_reason) {
314 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
315 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
316 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900317 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000318
Jiyong Parka4eebde2022-07-12 18:01:12 +0900319 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
320 // detected on the VM side (otherwise, it isn't a hangup), but in the
321 // monitor_payload_hangup function below which updates the payload state to Hangup.
322 let failure_reason =
323 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
324 Cow::from("HANGUP")
325 } else {
326 Cow::from(failure_reason)
327 };
328
Jiyong Parke558ab12022-07-07 20:18:55 +0900329 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000330
331 let death_reason = death_reason(&result, &failure_reason);
332 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900333
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900334 let vm_metric = self.vm_metric.lock().unwrap();
335 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000336
337 // Delete temporary files.
338 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000339 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000340 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000341 }
342
Jiyong Parka4eebde2022-07-12 18:01:12 +0900343 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
344 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
345 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
346 debug!("Starting to monitor hangup for Microdroid({})", child.id());
347 let (_, result) = self
348 .payload_state_updated
349 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
350 *s < PayloadState::Started
351 })
352 .unwrap();
353 let child_still_running = child.try_wait().ok() == Some(None);
354 if result.timed_out() && child_still_running {
355 error!(
356 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
357 child.id(),
358 BOOT_HANGUP_TIMEOUT.as_secs()
359 );
360 self.update_payload_state(PayloadState::Hangup).unwrap();
361 if let Err(e) = self.kill() {
362 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
363 }
364 }
365 }
366
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900367 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
368 let pid = child.id();
369
370 loop {
371 {
372 // Check VM state
373 let vm_state = &*self.vm_state.lock().unwrap();
374 if let VmState::Dead = vm_state {
375 break;
376 }
377
378 let mut vm_metric = self.vm_metric.lock().unwrap();
379
380 // Get CPU Information
381 // TODO: Collect it once right before VM dies using SIGCHLD
382 if let Ok(guest_time) = get_guest_time(pid) {
383 vm_metric.cpu_guest_time = Some(guest_time);
384 } else {
385 error!("Failed to parse /proc/[pid]/stat");
386 }
387
388 // Get Memory Information
389 if let Ok(rss) = get_rss(pid) {
390 vm_metric.rss = match &vm_metric.rss {
391 Some(x) => Some(Rss::extract_max(x, &rss)),
392 None => Some(rss),
393 }
394 } else {
395 error!("Failed to parse /proc/[pid]/smaps");
396 }
397 }
398
399 thread::sleep(Duration::from_secs(1));
400 }
401 }
402
Andrew Walbran6b650662021-09-07 13:13:23 +0000403 /// Returns the last reported state of the VM payload.
404 pub fn payload_state(&self) -> PayloadState {
405 *self.payload_state.lock().unwrap()
406 }
407
408 /// Updates the payload state to the given value, if it is a valid state transition.
409 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
410 let mut state_locked = self.payload_state.lock().unwrap();
411 // Only allow forward transitions, e.g. from starting to started or finished, not back in
412 // the other direction.
413 if new_state > *state_locked {
414 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900415 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000416 Ok(())
417 } else {
418 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
419 }
420 }
421
Andrew Walbranf8d94112021-09-07 11:45:36 +0000422 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900423 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000424 let vm_state = &*self.vm_state.lock().unwrap();
425 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900426 let id = child.id();
427 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000428 // TODO: Talk to crosvm to shutdown cleanly.
429 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900430 bail!("Error killing crosvm({}) instance: {}", id, e);
431 } else {
432 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000433 }
Inseob Kima446f802022-07-11 19:46:37 +0900434 } else {
435 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000436 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000437 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900438
439 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
440 /// to read the ramdump.
441 fn handle_ramdump(&self) -> Result<(), Error> {
442 let ramdump_path = self.temporary_directory.join("ramdump");
443 if std::fs::metadata(&ramdump_path)?.len() > 0 {
444 let ramdump = File::open(&ramdump_path)
445 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
446 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900447
448 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900449 }
450 Ok(())
451 }
Jiyong Park1612b902022-08-22 14:47:39 +0900452
453 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
454 let mut input = File::open(ramdump_path)
455 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
456
457 let pid = std::process::id() as i32;
458 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
459 .context("Failed to connect to tombstoned")?;
460 let mut output = conn
461 .text_output
462 .as_ref()
463 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
464
465 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
466 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
467
468 conn.notify_completion()?;
469 Ok(())
470 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000471}
472
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900473impl Rss {
474 fn extract_max(x: &Rss, y: &Rss) -> Rss {
475 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
476 }
477}
478
479// Get guest time from /proc/[crosvm pid]/stat
480fn get_guest_time(pid: u32) -> Result<i64> {
481 let file = read_to_string(format!("/proc/{}/stat", pid))?;
482 let data_list: Vec<_> = file.split_whitespace().collect();
483
484 // Information about guest_time is at 43th place of the file split with the whitespace.
485 // Example of /proc/[pid]/stat :
486 // 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
487 // 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
488 if data_list.len() < 43 {
489 bail!("Failed to parse command result for getting guest time : {}", file);
490 }
491
492 let guest_time_ticks = data_list[42].parse::<i64>()?;
493 // SAFETY : It just returns an integer about CPU tick information.
494 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
495 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
496}
497
498// Get rss from /proc/[crosvm pid]/smaps
499fn get_rss(pid: u32) -> Result<Rss> {
500 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
501 let lines: Vec<_> = file.split('\n').collect();
502
503 let mut rss_vm_total = 0i64;
504 let mut rss_crosvm_total = 0i64;
505 let mut is_vm = false;
506 for line in lines {
507 if line.contains("crosvm_guest") {
508 is_vm = true;
509 } else if line.contains("Rss:") {
510 let data_list: Vec<_> = line.split_whitespace().collect();
511 if data_list.len() < 2 {
512 bail!("Failed to parse command result for getting rss :\n{}", line);
513 }
514 let rss = data_list[1].parse::<i64>()?;
515
516 if is_vm {
517 rss_vm_total += rss;
518 is_vm = false;
519 }
520 rss_crosvm_total += rss;
521 }
522 }
523
524 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
525}
526
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100527fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
528 if let Some(position) = failure_reason.find('|') {
529 // Separator indicates extra context information is present after the failure name.
530 error!("Failure info: {}", &failure_reason[(position + 1)..]);
531 failure_reason = &failure_reason[..position];
532 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000533 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000534 match failure_reason {
535 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
536 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
537 }
538 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
539 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
540 }
541 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
542 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
543 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
544 }
Inseob Kim272f5722022-06-13 17:14:51 +0900545 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
546 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
547 }
548 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
549 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
550 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
551 }
552 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
553 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
554 }
555 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
556 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
557 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900558 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000559 _ => {}
560 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000561 match status.code() {
562 None => DeathReason::KILLED,
563 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000564 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000565 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000566 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000567 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000568 Some(_) => DeathReason::UNKNOWN,
569 }
570 } else {
571 DeathReason::INFRASTRUCTURE_ERROR
572 }
573}
574
Andrew Walbrand3a84182021-09-07 14:48:52 +0000575/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000576fn run_vm(
577 config: CrosvmConfig,
578 temporary_directory: &Path,
579 failure_pipe_write: File,
580) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000581 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000582
583 let mut command = Command::new(CROSVM_PATH);
584 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000585 command
586 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900587 // Configure the logger for the crosvm process to silence logs from the disk crate which
588 // don't provide much information to us (but do spamming us).
589 .arg("--log-level")
590 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000591 .arg("run")
592 .arg("--disable-sandbox")
Keir Fraser72762722022-09-30 16:12:06 +0000593 .arg("--no-balloon")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000594 .arg("--cid")
595 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000596
Andrew Walbranf8650422021-06-09 15:54:09 +0000597 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000598 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000599
600 // 3 virtio-console devices + vsock = 4.
601 let virtio_pci_device_count = 4 + config.disks.len();
602 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
603 // enough.
604 let swiotlb_size_mib = 2 * virtio_pci_device_count;
605 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000606 }
607
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000608 if let Some(memory_mib) = config.memory_mib {
609 command.arg("--mem").arg(memory_mib.to_string());
610 }
611
Jiyong Park032615f2022-01-10 13:55:34 +0900612 if let Some(cpus) = config.cpus {
613 command.arg("--cpus").arg(cpus.to_string());
614 }
615
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900616 if !config.task_profiles.is_empty() {
617 command.arg("--task-profiles").arg(config.task_profiles.join(","));
618 }
619
Jiyong Parkfa91d702021-10-18 23:51:39 +0900620 // Keep track of what file descriptors should be mapped to the crosvm process.
621 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
622
Jiyong Park747d6362021-10-19 17:12:52 +0900623 // Setup the serial devices.
624 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000625 // 2. uart device: used to report the reason for the VM failing.
626 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900627 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000628 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900629 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900630 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
631 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000632 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
633 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
634 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900635 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900636
Jiyong Park747d6362021-10-19 17:12:52 +0900637 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
638 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
639 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
640 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900641 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000642 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
643 // /dev/ttyS1
644 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900645 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900646 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900647 // /dev/hvc1
648 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900649 // /dev/hvc2
650 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000651
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000652 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000653 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000654 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000655
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000656 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000657 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000658 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000659
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000660 if let Some(params) = &config.params {
661 command.arg("--params").arg(params);
662 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000663
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000664 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000665 command
666 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000667 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000668 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000669
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000670 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000671 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000672 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000673
Keir Fraser13a956a2022-07-14 14:20:46 +0000674 let control_server_socket =
675 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
676 .context("failed to create control server")?;
677 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
678
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000679 debug!("Preserving FDs {:?}", preserved_fds);
680 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000681
Jaewan Kimb2814062022-11-14 13:21:40 +0900682 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900683 print_crosvm_args(&command);
684
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000685 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900686 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000687 Ok(result)
688}
689
690/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000691fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000692 if config.bootloader.is_none() && config.kernel.is_none() {
693 bail!("VM must have either a bootloader or a kernel image.");
694 }
695 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
696 bail!("Can't have both bootloader and kernel/initrd image.");
697 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900698 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
699 if !config.platform_version.matches(&version) {
700 bail!(
701 "Incompatible platform version. The config is compatible with platform version(s) \
702 {}, but the actual platform version is {}",
703 config.platform_version,
704 version
705 );
706 }
707
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000708 Ok(())
709}
710
Jiyong Park2d736562022-10-24 22:40:12 +0900711/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
712/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
713/// unmodified.
714fn print_crosvm_args(command: &Command) {
715 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
716 info!(
717 "Running crosvm with args: {:?}",
718 command
719 .get_args()
720 .map(|s| s.to_string_lossy())
721 .map(|s| {
722 re.replace_all(&s, |caps: &Captures| {
723 let path = &caps[0];
724 if let Ok(realpath) = std::fs::canonicalize(path) {
725 format!("{} ({})", path, realpath.to_string_lossy())
726 } else {
727 path.to_owned()
728 }
729 })
730 .into_owned()
731 })
732 .collect::<Vec<_>>()
733 );
734}
735
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000736/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
737/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000738fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000739 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000740 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000741 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000742}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000743
744/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
745/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
746fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
747 if let Some(file) = file {
748 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
749 } else {
750 "type=sink".to_string()
751 }
752}
753
754/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
755fn create_pipe() -> Result<(File, File), Error> {
756 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
757 // SAFETY: We are the sole owners of these fds as they were just created.
758 let read_fd = unsafe { File::from_raw_fd(raw_read) };
759 let write_fd = unsafe { File::from_raw_fd(raw_write) };
760 Ok((read_fd, write_fd))
761}