blob: 2d31fac55dda5f6fa37bf293917a47de5f3b39a3 [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};
Jiyong Park1612b902022-08-22 14:47:39 +090036use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000037use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090038use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090039use std::time::{Duration, SystemTime};
Andrew Walbrandae07162021-03-12 17:05:20 +000040use std::thread;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000041use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
David Brazdil528e0472022-10-10 15:06:02 +010042use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010043use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000044use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090045use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
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
202/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000203#[derive(Debug)]
204pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000205 /// The current state of the VM.
206 pub vm_state: Mutex<VmState>,
David Brazdil528e0472022-10-10 15:06:02 +0100207 /// Handle to global resources allocated for this VM.
208 #[allow(dead_code)] // The handle is never read, we only need to hold it.
209 vm_context: Strong<dyn IGlobalVmContext>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000210 /// The CID assigned to the VM for vsock communication.
211 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000212 /// The name of the VM.
213 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000214 /// Whether the VM is a protected VM.
215 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000216 /// Directory of temporary files used by the VM while it is running.
217 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000218 /// The UID of the process which requested the VM.
219 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000220 /// The PID of the process which requested the VM. Note that this process may no longer exist
221 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000222 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000223 /// Callbacks to clients of the VM.
224 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000225 /// VirtualMachineService binder object for the VM.
226 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900227 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
228 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000229 /// The latest lifecycle state which the payload reported itself to be in.
230 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900231 /// Represents the condition that payload_state was updated
232 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000233}
234
235impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000236 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
237 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000238 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000239 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000240 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000241 requester_debug_pid: i32,
David Brazdil528e0472022-10-10 15:06:02 +0100242 vm_context: Strong<dyn IGlobalVmContext>,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000243 ) -> Result<VmInstance, Error> {
244 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000245 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000246 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000247 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000248 Ok(VmInstance {
249 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100250 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000251 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000252 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000253 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000254 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000255 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000256 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000257 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000258 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900259 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000260 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900261 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000262 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000263 }
264
Andrew Walbranf8d94112021-09-07 11:45:36 +0000265 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
266 /// the `VmInstance` is dropped.
267 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900268 let mut vm_metric = self.vm_metric.lock().unwrap();
269 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000270 self.vm_state.lock().unwrap().start(self.clone())
271 }
272
Jiyong Parka4eebde2022-07-12 18:01:12 +0900273 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
274 /// handles the event by updating the state, noityfing the event to clients by calling
275 /// callbacks, and removing temporary files for the VM.
276 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000277 let result = child.wait();
278 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900279 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000280 Ok(status) => {
281 info!("crosvm({}) exited with status {}", child.id(), status);
282 if let Some(exit_status_code) = status.code() {
283 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
284 info!("detected vcpu stall on crosvm");
285 }
286 }
287 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000288 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000289
290 let mut vm_state = self.vm_state.lock().unwrap();
291 *vm_state = VmState::Dead;
292 // Ensure that the mutex is released before calling the callbacks.
293 drop(vm_state);
294
Jiyong Parka4eebde2022-07-12 18:01:12 +0900295 // Read the pipe to see if any failure reason is written
296 let mut failure_reason = String::new();
297 match failure_pipe_read.read_to_string(&mut failure_reason) {
298 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
299 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
300 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900301 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000302
Jiyong Parka4eebde2022-07-12 18:01:12 +0900303 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
304 // detected on the VM side (otherwise, it isn't a hangup), but in the
305 // monitor_payload_hangup function below which updates the payload state to Hangup.
306 let failure_reason =
307 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
308 Cow::from("HANGUP")
309 } else {
310 Cow::from(failure_reason)
311 };
312
Jiyong Parke558ab12022-07-07 20:18:55 +0900313 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000314
315 let death_reason = death_reason(&result, &failure_reason);
316 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900317
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900318 let vm_metric = self.vm_metric.lock().unwrap();
319 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000320
321 // Delete temporary files.
322 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000323 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000324 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000325 }
326
Jiyong Parka4eebde2022-07-12 18:01:12 +0900327 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
328 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
329 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
330 debug!("Starting to monitor hangup for Microdroid({})", child.id());
331 let (_, result) = self
332 .payload_state_updated
333 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
334 *s < PayloadState::Started
335 })
336 .unwrap();
337 let child_still_running = child.try_wait().ok() == Some(None);
338 if result.timed_out() && child_still_running {
339 error!(
340 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
341 child.id(),
342 BOOT_HANGUP_TIMEOUT.as_secs()
343 );
344 self.update_payload_state(PayloadState::Hangup).unwrap();
345 if let Err(e) = self.kill() {
346 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
347 }
348 }
349 }
350
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900351 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
352 let pid = child.id();
353
354 loop {
355 {
356 // Check VM state
357 let vm_state = &*self.vm_state.lock().unwrap();
358 if let VmState::Dead = vm_state {
359 break;
360 }
361
362 let mut vm_metric = self.vm_metric.lock().unwrap();
363
364 // Get CPU Information
365 // TODO: Collect it once right before VM dies using SIGCHLD
366 if let Ok(guest_time) = get_guest_time(pid) {
367 vm_metric.cpu_guest_time = Some(guest_time);
368 } else {
369 error!("Failed to parse /proc/[pid]/stat");
370 }
371
372 // Get Memory Information
373 if let Ok(rss) = get_rss(pid) {
374 vm_metric.rss = match &vm_metric.rss {
375 Some(x) => Some(Rss::extract_max(x, &rss)),
376 None => Some(rss),
377 }
378 } else {
379 error!("Failed to parse /proc/[pid]/smaps");
380 }
381 }
382
383 thread::sleep(Duration::from_secs(1));
384 }
385 }
386
Andrew Walbran6b650662021-09-07 13:13:23 +0000387 /// Returns the last reported state of the VM payload.
388 pub fn payload_state(&self) -> PayloadState {
389 *self.payload_state.lock().unwrap()
390 }
391
392 /// Updates the payload state to the given value, if it is a valid state transition.
393 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
394 let mut state_locked = self.payload_state.lock().unwrap();
395 // Only allow forward transitions, e.g. from starting to started or finished, not back in
396 // the other direction.
397 if new_state > *state_locked {
398 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900399 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000400 Ok(())
401 } else {
402 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
403 }
404 }
405
Andrew Walbranf8d94112021-09-07 11:45:36 +0000406 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900407 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000408 let vm_state = &*self.vm_state.lock().unwrap();
409 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900410 let id = child.id();
411 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000412 // TODO: Talk to crosvm to shutdown cleanly.
413 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900414 bail!("Error killing crosvm({}) instance: {}", id, e);
415 } else {
416 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000417 }
Inseob Kima446f802022-07-11 19:46:37 +0900418 } else {
419 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000420 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000421 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900422
423 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
424 /// to read the ramdump.
425 fn handle_ramdump(&self) -> Result<(), Error> {
426 let ramdump_path = self.temporary_directory.join("ramdump");
427 if std::fs::metadata(&ramdump_path)?.len() > 0 {
428 let ramdump = File::open(&ramdump_path)
429 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
430 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900431
432 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900433 }
434 Ok(())
435 }
Jiyong Park1612b902022-08-22 14:47:39 +0900436
437 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
438 let mut input = File::open(ramdump_path)
439 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
440
441 let pid = std::process::id() as i32;
442 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
443 .context("Failed to connect to tombstoned")?;
444 let mut output = conn
445 .text_output
446 .as_ref()
447 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
448
449 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
450 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
451
452 conn.notify_completion()?;
453 Ok(())
454 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000455}
456
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900457impl Rss {
458 fn extract_max(x: &Rss, y: &Rss) -> Rss {
459 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
460 }
461}
462
463// Get guest time from /proc/[crosvm pid]/stat
464fn get_guest_time(pid: u32) -> Result<i64> {
465 let file = read_to_string(format!("/proc/{}/stat", pid))?;
466 let data_list: Vec<_> = file.split_whitespace().collect();
467
468 // Information about guest_time is at 43th place of the file split with the whitespace.
469 // Example of /proc/[pid]/stat :
470 // 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
471 // 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
472 if data_list.len() < 43 {
473 bail!("Failed to parse command result for getting guest time : {}", file);
474 }
475
476 let guest_time_ticks = data_list[42].parse::<i64>()?;
477 // SAFETY : It just returns an integer about CPU tick information.
478 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
479 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
480}
481
482// Get rss from /proc/[crosvm pid]/smaps
483fn get_rss(pid: u32) -> Result<Rss> {
484 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
485 let lines: Vec<_> = file.split('\n').collect();
486
487 let mut rss_vm_total = 0i64;
488 let mut rss_crosvm_total = 0i64;
489 let mut is_vm = false;
490 for line in lines {
491 if line.contains("crosvm_guest") {
492 is_vm = true;
493 } else if line.contains("Rss:") {
494 let data_list: Vec<_> = line.split_whitespace().collect();
495 if data_list.len() < 2 {
496 bail!("Failed to parse command result for getting rss :\n{}", line);
497 }
498 let rss = data_list[1].parse::<i64>()?;
499
500 if is_vm {
501 rss_vm_total += rss;
502 is_vm = false;
503 }
504 rss_crosvm_total += rss;
505 }
506 }
507
508 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
509}
510
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100511fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
512 if let Some(position) = failure_reason.find('|') {
513 // Separator indicates extra context information is present after the failure name.
514 error!("Failure info: {}", &failure_reason[(position + 1)..]);
515 failure_reason = &failure_reason[..position];
516 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000517 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000518 match failure_reason {
519 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
520 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
521 }
522 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
523 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
524 }
525 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
526 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
527 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
528 }
Inseob Kim272f5722022-06-13 17:14:51 +0900529 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
530 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
531 }
532 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
533 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
534 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
535 }
536 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
537 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
538 }
539 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
540 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
541 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900542 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000543 _ => {}
544 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000545 match status.code() {
546 None => DeathReason::KILLED,
547 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000548 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000549 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000550 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000551 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000552 Some(_) => DeathReason::UNKNOWN,
553 }
554 } else {
555 DeathReason::INFRASTRUCTURE_ERROR
556 }
557}
558
Andrew Walbrand3a84182021-09-07 14:48:52 +0000559/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000560fn run_vm(
561 config: CrosvmConfig,
562 temporary_directory: &Path,
563 failure_pipe_write: File,
564) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000565 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000566
567 let mut command = Command::new(CROSVM_PATH);
568 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000569 command
570 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900571 // Configure the logger for the crosvm process to silence logs from the disk crate which
572 // don't provide much information to us (but do spamming us).
573 .arg("--log-level")
574 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000575 .arg("run")
576 .arg("--disable-sandbox")
577 .arg("--cid")
578 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000579
Keir Fraserf25cb922022-11-23 14:26:00 +0000580 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
581 command.arg("--balloon-page-reporting");
582 } else {
583 command.arg("--no-balloon");
584 }
585
Andrew Walbranf8650422021-06-09 15:54:09 +0000586 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000587 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000588
589 // 3 virtio-console devices + vsock = 4.
590 let virtio_pci_device_count = 4 + config.disks.len();
591 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
592 // enough.
593 let swiotlb_size_mib = 2 * virtio_pci_device_count;
594 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000595 }
596
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000597 if let Some(memory_mib) = config.memory_mib {
598 command.arg("--mem").arg(memory_mib.to_string());
599 }
600
Jiyong Park032615f2022-01-10 13:55:34 +0900601 if let Some(cpus) = config.cpus {
602 command.arg("--cpus").arg(cpus.to_string());
603 }
604
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900605 if !config.task_profiles.is_empty() {
606 command.arg("--task-profiles").arg(config.task_profiles.join(","));
607 }
608
Jiyong Parkfa91d702021-10-18 23:51:39 +0900609 // Keep track of what file descriptors should be mapped to the crosvm process.
610 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
611
Jiyong Park747d6362021-10-19 17:12:52 +0900612 // Setup the serial devices.
613 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000614 // 2. uart device: used to report the reason for the VM failing.
615 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900616 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000617 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900618 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900619 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
620 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000621 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
622 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
623 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900624 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900625
Jiyong Park747d6362021-10-19 17:12:52 +0900626 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
627 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
628 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
629 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900630 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000631 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
632 // /dev/ttyS1
633 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900634 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900635 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900636 // /dev/hvc1
637 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900638 // /dev/hvc2
639 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000640
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000641 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000642 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000643 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000644
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000645 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000646 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000647 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000648
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000649 if let Some(params) = &config.params {
650 command.arg("--params").arg(params);
651 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000652
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000653 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000654 command
655 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000656 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000657 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000658
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000659 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000660 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000661 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000662
Keir Fraser13a956a2022-07-14 14:20:46 +0000663 let control_server_socket =
664 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
665 .context("failed to create control server")?;
666 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
667
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000668 debug!("Preserving FDs {:?}", preserved_fds);
669 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000670
Jaewan Kimb2814062022-11-14 13:21:40 +0900671 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900672 print_crosvm_args(&command);
673
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000674 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900675 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000676 Ok(result)
677}
678
679/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000680fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000681 if config.bootloader.is_none() && config.kernel.is_none() {
682 bail!("VM must have either a bootloader or a kernel image.");
683 }
684 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
685 bail!("Can't have both bootloader and kernel/initrd image.");
686 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900687 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
688 if !config.platform_version.matches(&version) {
689 bail!(
690 "Incompatible platform version. The config is compatible with platform version(s) \
691 {}, but the actual platform version is {}",
692 config.platform_version,
693 version
694 );
695 }
696
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000697 Ok(())
698}
699
Jiyong Park2d736562022-10-24 22:40:12 +0900700/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
701/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
702/// unmodified.
703fn print_crosvm_args(command: &Command) {
704 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
705 info!(
706 "Running crosvm with args: {:?}",
707 command
708 .get_args()
709 .map(|s| s.to_string_lossy())
710 .map(|s| {
711 re.replace_all(&s, |caps: &Captures| {
712 let path = &caps[0];
713 if let Ok(realpath) = std::fs::canonicalize(path) {
714 format!("{} ({})", path, realpath.to_string_lossy())
715 } else {
716 path.to_owned()
717 }
718 })
719 .into_owned()
720 })
721 .collect::<Vec<_>>()
722 );
723}
724
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000725/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
726/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000727fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000728 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000729 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000730 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000731}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000732
733/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
734/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
735fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
736 if let Some(file) = file {
737 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
738 } else {
739 "type=sink".to_string()
740 }
741}
742
743/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
744fn create_pipe() -> Result<(File, File), Error> {
745 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
746 // SAFETY: We are the sole owners of these fds as they were just created.
747 let read_fd = unsafe { File::from_raw_fd(raw_read) };
748 let write_fd = unsafe { File::from_raw_fd(raw_write) };
749 Ok((read_fd, write_fd))
750}