blob: db6da4372e4b8e57903d13a293af4cb7b9c2d5db [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;
Alan Stokes0e82b502022-08-08 14:44:48 +010041use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090043use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000044
Keir Fraser13a956a2022-07-14 14:20:46 +000045/// external/crosvm
46use base::UnixSeqpacketListener;
47
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000048const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
49
Jiyong Parkdcf17412022-02-08 15:07:23 +090050/// Version of the platform that crosvm currently implements. The format follows SemVer. This
51/// should be updated when there is a platform change in the crosvm side. Having this value here is
52/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
53/// APEX.
54const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
55
Andrew Walbrand15c5632022-02-03 13:38:31 +000056/// The exit status which crosvm returns when it has an error starting a VM.
57const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000058/// The exit status which crosvm returns when a VM requests a reboot.
59const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000060/// The exit status which crosvm returns when it crashes due to an error.
61const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000062/// The exit status which crosvm returns when vcpu is stalled.
63const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000064
Seungjae Yoo6d265d92022-11-15 10:51:33 +090065const MILLIS_PER_SEC: i64 = 1000;
66
Jiyong Parke6ed0f92022-06-22 00:13:00 +090067lazy_static! {
68 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
69 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010070 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090071 // Nested virtualization is slow, so we need a longer timeout.
72 Duration::from_secs(100)
73 } else {
74 Duration::from_secs(10)
75 };
76}
77
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078/// Configuration for a VM to run with crosvm.
79#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000080pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000082 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000083 pub bootloader: Option<File>,
84 pub kernel: Option<File>,
85 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000086 pub disks: Vec<DiskFile>,
87 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000088 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000089 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090090 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090091 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090092 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000093 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090094 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000095 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090096 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090097 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098}
99
100/// A disk image to pass to crosvm for a VM.
101#[derive(Debug)]
102pub struct DiskFile {
103 pub image: File,
104 pub writable: bool,
105}
106
Andrew Walbran6b650662021-09-07 13:13:23 +0000107/// The lifecycle state which the payload in the VM has reported itself to be in.
108///
109/// Note that the order of enum variants is significant; only forward transitions are allowed by
110/// [`VmInstance::update_payload_state`].
111#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
112pub enum PayloadState {
113 Starting,
114 Started,
115 Ready,
116 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900117 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000118}
119
Andrew Walbranf8d94112021-09-07 11:45:36 +0000120/// The current state of the VM itself.
121#[derive(Debug)]
122pub enum VmState {
123 /// The VM has not yet tried to start.
124 NotStarted {
125 ///The configuration needed to start the VM, if it has not yet been started.
126 config: CrosvmConfig,
127 },
128 /// The VM has been started.
129 Running {
130 /// The crosvm child process.
131 child: Arc<SharedChild>,
132 },
133 /// The VM died or was killed.
134 Dead,
135 /// The VM failed to start.
136 Failed,
137}
138
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900139/// RSS values of VM and CrosVM process itself.
140#[derive(Copy, Clone, Debug, Default)]
141pub struct Rss {
142 pub vm: i64,
143 pub crosvm: i64,
144}
145
146/// Metrics regarding the VM.
147#[derive(Debug, Default)]
148pub struct VmMetric {
149 /// Recorded timestamp when the VM is started.
150 pub start_timestamp: Option<SystemTime>,
151 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
152 pub cpu_guest_time: Option<i64>,
153 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
154 pub rss: Option<Rss>,
155}
156
Andrew Walbranf8d94112021-09-07 11:45:36 +0000157impl VmState {
158 /// Tries to start the VM, if it is in the `NotStarted` state.
159 ///
160 /// Returns an error if the VM is in the wrong state, or fails to start.
161 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
162 let state = mem::replace(self, VmState::Failed);
163 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900164 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000165 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
166
Andrew Walbranf8d94112021-09-07 11:45:36 +0000167 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000168 let child =
169 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000170
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900171 let instance_monitor_status = instance.clone();
172 let child_monitor_status = child.clone();
173 thread::spawn(move || {
174 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
175 });
176
Andrew Walbranf8d94112021-09-07 11:45:36 +0000177 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900178 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000179 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900180 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000181 });
182
Jiyong Parka4eebde2022-07-12 18:01:12 +0900183 if detect_hangup {
184 let child_clone = child.clone();
185 thread::spawn(move || {
186 instance.monitor_payload_hangup(child_clone);
187 });
188 }
189
Andrew Walbranf8d94112021-09-07 11:45:36 +0000190 // If it started correctly, update the state.
191 *self = VmState::Running { child };
192 Ok(())
193 } else {
194 *self = state;
195 bail!("VM already started or failed")
196 }
197 }
198}
199
200/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000201#[derive(Debug)]
202pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000203 /// The current state of the VM.
204 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000205 /// The CID assigned to the VM for vsock communication.
206 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000207 /// The name of the VM.
208 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000209 /// Whether the VM is a protected VM.
210 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000211 /// Directory of temporary files used by the VM while it is running.
212 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000213 /// The UID of the process which requested the VM.
214 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000215 /// The PID of the process which requested the VM. Note that this process may no longer exist
216 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000217 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000218 /// Callbacks to clients of the VM.
219 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000220 /// VirtualMachineService binder object for the VM.
221 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900222 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
223 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000224 /// The latest lifecycle state which the payload reported itself to be in.
225 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900226 /// Represents the condition that payload_state was updated
227 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000228}
229
230impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000231 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
232 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000233 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000235 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000236 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000237 ) -> Result<VmInstance, Error> {
238 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000239 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000240 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000241 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000242 Ok(VmInstance {
243 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000244 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000245 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000246 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000247 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000248 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000249 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000250 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000251 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900252 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000253 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900254 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000255 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000256 }
257
Andrew Walbranf8d94112021-09-07 11:45:36 +0000258 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
259 /// the `VmInstance` is dropped.
260 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900261 let mut vm_metric = self.vm_metric.lock().unwrap();
262 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000263 self.vm_state.lock().unwrap().start(self.clone())
264 }
265
Jiyong Parka4eebde2022-07-12 18:01:12 +0900266 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
267 /// handles the event by updating the state, noityfing the event to clients by calling
268 /// callbacks, and removing temporary files for the VM.
269 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000270 let result = child.wait();
271 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900272 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000273 Ok(status) => {
274 info!("crosvm({}) exited with status {}", child.id(), status);
275 if let Some(exit_status_code) = status.code() {
276 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
277 info!("detected vcpu stall on crosvm");
278 }
279 }
280 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000281 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000282
283 let mut vm_state = self.vm_state.lock().unwrap();
284 *vm_state = VmState::Dead;
285 // Ensure that the mutex is released before calling the callbacks.
286 drop(vm_state);
287
Jiyong Parka4eebde2022-07-12 18:01:12 +0900288 // Read the pipe to see if any failure reason is written
289 let mut failure_reason = String::new();
290 match failure_pipe_read.read_to_string(&mut failure_reason) {
291 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
292 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
293 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900294 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000295
Jiyong Parka4eebde2022-07-12 18:01:12 +0900296 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
297 // detected on the VM side (otherwise, it isn't a hangup), but in the
298 // monitor_payload_hangup function below which updates the payload state to Hangup.
299 let failure_reason =
300 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
301 Cow::from("HANGUP")
302 } else {
303 Cow::from(failure_reason)
304 };
305
Jiyong Parke558ab12022-07-07 20:18:55 +0900306 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000307
308 let death_reason = death_reason(&result, &failure_reason);
309 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900310
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900311 let vm_metric = self.vm_metric.lock().unwrap();
312 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000313
314 // Delete temporary files.
315 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000316 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000317 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000318 }
319
Jiyong Parka4eebde2022-07-12 18:01:12 +0900320 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
321 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
322 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
323 debug!("Starting to monitor hangup for Microdroid({})", child.id());
324 let (_, result) = self
325 .payload_state_updated
326 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
327 *s < PayloadState::Started
328 })
329 .unwrap();
330 let child_still_running = child.try_wait().ok() == Some(None);
331 if result.timed_out() && child_still_running {
332 error!(
333 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
334 child.id(),
335 BOOT_HANGUP_TIMEOUT.as_secs()
336 );
337 self.update_payload_state(PayloadState::Hangup).unwrap();
338 if let Err(e) = self.kill() {
339 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
340 }
341 }
342 }
343
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900344 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
345 let pid = child.id();
346
347 loop {
348 {
349 // Check VM state
350 let vm_state = &*self.vm_state.lock().unwrap();
351 if let VmState::Dead = vm_state {
352 break;
353 }
354
355 let mut vm_metric = self.vm_metric.lock().unwrap();
356
357 // Get CPU Information
358 // TODO: Collect it once right before VM dies using SIGCHLD
359 if let Ok(guest_time) = get_guest_time(pid) {
360 vm_metric.cpu_guest_time = Some(guest_time);
361 } else {
362 error!("Failed to parse /proc/[pid]/stat");
363 }
364
365 // Get Memory Information
366 if let Ok(rss) = get_rss(pid) {
367 vm_metric.rss = match &vm_metric.rss {
368 Some(x) => Some(Rss::extract_max(x, &rss)),
369 None => Some(rss),
370 }
371 } else {
372 error!("Failed to parse /proc/[pid]/smaps");
373 }
374 }
375
376 thread::sleep(Duration::from_secs(1));
377 }
378 }
379
Andrew Walbran6b650662021-09-07 13:13:23 +0000380 /// Returns the last reported state of the VM payload.
381 pub fn payload_state(&self) -> PayloadState {
382 *self.payload_state.lock().unwrap()
383 }
384
385 /// Updates the payload state to the given value, if it is a valid state transition.
386 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
387 let mut state_locked = self.payload_state.lock().unwrap();
388 // Only allow forward transitions, e.g. from starting to started or finished, not back in
389 // the other direction.
390 if new_state > *state_locked {
391 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900392 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000393 Ok(())
394 } else {
395 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
396 }
397 }
398
Andrew Walbranf8d94112021-09-07 11:45:36 +0000399 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900400 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000401 let vm_state = &*self.vm_state.lock().unwrap();
402 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900403 let id = child.id();
404 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000405 // TODO: Talk to crosvm to shutdown cleanly.
406 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900407 bail!("Error killing crosvm({}) instance: {}", id, e);
408 } else {
409 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000410 }
Inseob Kima446f802022-07-11 19:46:37 +0900411 } else {
412 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000413 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000414 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900415
416 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
417 /// to read the ramdump.
418 fn handle_ramdump(&self) -> Result<(), Error> {
419 let ramdump_path = self.temporary_directory.join("ramdump");
420 if std::fs::metadata(&ramdump_path)?.len() > 0 {
421 let ramdump = File::open(&ramdump_path)
422 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
423 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900424
425 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900426 }
427 Ok(())
428 }
Jiyong Park1612b902022-08-22 14:47:39 +0900429
430 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
431 let mut input = File::open(ramdump_path)
432 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
433
434 let pid = std::process::id() as i32;
435 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
436 .context("Failed to connect to tombstoned")?;
437 let mut output = conn
438 .text_output
439 .as_ref()
440 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
441
442 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
443 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
444
445 conn.notify_completion()?;
446 Ok(())
447 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000448}
449
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900450impl Rss {
451 fn extract_max(x: &Rss, y: &Rss) -> Rss {
452 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
453 }
454}
455
456// Get guest time from /proc/[crosvm pid]/stat
457fn get_guest_time(pid: u32) -> Result<i64> {
458 let file = read_to_string(format!("/proc/{}/stat", pid))?;
459 let data_list: Vec<_> = file.split_whitespace().collect();
460
461 // Information about guest_time is at 43th place of the file split with the whitespace.
462 // Example of /proc/[pid]/stat :
463 // 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
464 // 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
465 if data_list.len() < 43 {
466 bail!("Failed to parse command result for getting guest time : {}", file);
467 }
468
469 let guest_time_ticks = data_list[42].parse::<i64>()?;
470 // SAFETY : It just returns an integer about CPU tick information.
471 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
472 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
473}
474
475// Get rss from /proc/[crosvm pid]/smaps
476fn get_rss(pid: u32) -> Result<Rss> {
477 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
478 let lines: Vec<_> = file.split('\n').collect();
479
480 let mut rss_vm_total = 0i64;
481 let mut rss_crosvm_total = 0i64;
482 let mut is_vm = false;
483 for line in lines {
484 if line.contains("crosvm_guest") {
485 is_vm = true;
486 } else if line.contains("Rss:") {
487 let data_list: Vec<_> = line.split_whitespace().collect();
488 if data_list.len() < 2 {
489 bail!("Failed to parse command result for getting rss :\n{}", line);
490 }
491 let rss = data_list[1].parse::<i64>()?;
492
493 if is_vm {
494 rss_vm_total += rss;
495 is_vm = false;
496 }
497 rss_crosvm_total += rss;
498 }
499 }
500
501 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
502}
503
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100504fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
505 if let Some(position) = failure_reason.find('|') {
506 // Separator indicates extra context information is present after the failure name.
507 error!("Failure info: {}", &failure_reason[(position + 1)..]);
508 failure_reason = &failure_reason[..position];
509 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000510 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000511 match failure_reason {
512 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
513 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
514 }
515 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
516 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
517 }
518 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
519 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
520 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
521 }
Inseob Kim272f5722022-06-13 17:14:51 +0900522 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
523 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
524 }
525 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
526 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
527 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
528 }
529 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
530 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
531 }
532 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
533 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
534 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900535 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000536 _ => {}
537 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000538 match status.code() {
539 None => DeathReason::KILLED,
540 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000541 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000542 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000543 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000544 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000545 Some(_) => DeathReason::UNKNOWN,
546 }
547 } else {
548 DeathReason::INFRASTRUCTURE_ERROR
549 }
550}
551
Andrew Walbrand3a84182021-09-07 14:48:52 +0000552/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000553fn run_vm(
554 config: CrosvmConfig,
555 temporary_directory: &Path,
556 failure_pipe_write: File,
557) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000558 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000559
560 let mut command = Command::new(CROSVM_PATH);
561 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000562 command
563 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900564 // Configure the logger for the crosvm process to silence logs from the disk crate which
565 // don't provide much information to us (but do spamming us).
566 .arg("--log-level")
567 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000568 .arg("run")
569 .arg("--disable-sandbox")
Keir Fraser72762722022-09-30 16:12:06 +0000570 .arg("--no-balloon")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000571 .arg("--cid")
572 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000573
Andrew Walbranf8650422021-06-09 15:54:09 +0000574 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000575 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000576
577 // 3 virtio-console devices + vsock = 4.
578 let virtio_pci_device_count = 4 + config.disks.len();
579 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
580 // enough.
581 let swiotlb_size_mib = 2 * virtio_pci_device_count;
582 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000583 }
584
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000585 if let Some(memory_mib) = config.memory_mib {
586 command.arg("--mem").arg(memory_mib.to_string());
587 }
588
Jiyong Park032615f2022-01-10 13:55:34 +0900589 if let Some(cpus) = config.cpus {
590 command.arg("--cpus").arg(cpus.to_string());
591 }
592
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900593 if !config.task_profiles.is_empty() {
594 command.arg("--task-profiles").arg(config.task_profiles.join(","));
595 }
596
Jiyong Parkfa91d702021-10-18 23:51:39 +0900597 // Keep track of what file descriptors should be mapped to the crosvm process.
598 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
599
Jiyong Park747d6362021-10-19 17:12:52 +0900600 // Setup the serial devices.
601 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000602 // 2. uart device: used to report the reason for the VM failing.
603 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900604 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000605 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900606 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900607 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
608 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000609 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
610 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
611 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900612 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900613
Jiyong Park747d6362021-10-19 17:12:52 +0900614 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
615 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
616 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
617 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900618 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000619 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
620 // /dev/ttyS1
621 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900622 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900623 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900624 // /dev/hvc1
625 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900626 // /dev/hvc2
627 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000628
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000629 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000630 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000631 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000632
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000633 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000634 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000635 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000636
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000637 if let Some(params) = &config.params {
638 command.arg("--params").arg(params);
639 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000640
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000641 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000642 command
643 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000644 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000645 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000646
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000647 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000648 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000649 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000650
Keir Fraser13a956a2022-07-14 14:20:46 +0000651 let control_server_socket =
652 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
653 .context("failed to create control server")?;
654 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
655
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000656 debug!("Preserving FDs {:?}", preserved_fds);
657 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000658
Jaewan Kimb2814062022-11-14 13:21:40 +0900659 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900660 print_crosvm_args(&command);
661
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000662 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900663 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000664 Ok(result)
665}
666
667/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000668fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000669 if config.bootloader.is_none() && config.kernel.is_none() {
670 bail!("VM must have either a bootloader or a kernel image.");
671 }
672 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
673 bail!("Can't have both bootloader and kernel/initrd image.");
674 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900675 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
676 if !config.platform_version.matches(&version) {
677 bail!(
678 "Incompatible platform version. The config is compatible with platform version(s) \
679 {}, but the actual platform version is {}",
680 config.platform_version,
681 version
682 );
683 }
684
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000685 Ok(())
686}
687
Jiyong Park2d736562022-10-24 22:40:12 +0900688/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
689/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
690/// unmodified.
691fn print_crosvm_args(command: &Command) {
692 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
693 info!(
694 "Running crosvm with args: {:?}",
695 command
696 .get_args()
697 .map(|s| s.to_string_lossy())
698 .map(|s| {
699 re.replace_all(&s, |caps: &Captures| {
700 let path = &caps[0];
701 if let Ok(realpath) = std::fs::canonicalize(path) {
702 format!("{} ({})", path, realpath.to_string_lossy())
703 } else {
704 path.to_owned()
705 }
706 })
707 .into_owned()
708 })
709 .collect::<Vec<_>>()
710 );
711}
712
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000713/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
714/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000715fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000716 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000717 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000718 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000719}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000720
721/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
722/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
723fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
724 if let Some(file) = file {
725 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
726 } else {
727 "type=sink".to_string()
728 }
729}
730
731/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
732fn create_pipe() -> Result<(File, File), Error> {
733 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
734 // SAFETY: We are the sole owners of these fds as they were just created.
735 let read_fd = unsafe { File::from_raw_fd(raw_read) };
736 let write_fd = unsafe { File::from_raw_fd(raw_write) };
737 Ok((read_fd, write_fd))
738}