blob: 85a57c9052d6dfba9b9b7bce9f122ae6a95d1878 [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};
David Brazdil73988ea2022-11-11 15:10:32 +000046use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000047
Keir Fraser13a956a2022-07-14 14:20:46 +000048/// external/crosvm
49use base::UnixSeqpacketListener;
50
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
52
Jiyong Parkdcf17412022-02-08 15:07:23 +090053/// Version of the platform that crosvm currently implements. The format follows SemVer. This
54/// should be updated when there is a platform change in the crosvm side. Having this value here is
55/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
56/// APEX.
57const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
58
Andrew Walbrand15c5632022-02-03 13:38:31 +000059/// The exit status which crosvm returns when it has an error starting a VM.
60const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000061/// The exit status which crosvm returns when a VM requests a reboot.
62const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000063/// The exit status which crosvm returns when it crashes due to an error.
64const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000065/// The exit status which crosvm returns when vcpu is stalled.
66const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000067
Seungjae Yoo6d265d92022-11-15 10:51:33 +090068const MILLIS_PER_SEC: i64 = 1000;
69
Jiyong Parke6ed0f92022-06-22 00:13:00 +090070lazy_static! {
71 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
72 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010073 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090074 // Nested virtualization is slow, so we need a longer timeout.
75 Duration::from_secs(100)
76 } else {
77 Duration::from_secs(10)
78 };
79}
80
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081/// Configuration for a VM to run with crosvm.
82#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000083pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000084 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000085 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000086 pub bootloader: Option<File>,
87 pub kernel: Option<File>,
88 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089 pub disks: Vec<DiskFile>,
90 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000091 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000092 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090093 pub cpus: Option<NonZeroU32>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090094 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090095 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000096 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090097 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000098 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090099 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900100 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000101}
102
103/// A disk image to pass to crosvm for a VM.
104#[derive(Debug)]
105pub struct DiskFile {
106 pub image: File,
107 pub writable: bool,
108}
109
Andrew Walbran6b650662021-09-07 13:13:23 +0000110/// The lifecycle state which the payload in the VM has reported itself to be in.
111///
112/// Note that the order of enum variants is significant; only forward transitions are allowed by
113/// [`VmInstance::update_payload_state`].
114#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
115pub enum PayloadState {
116 Starting,
117 Started,
118 Ready,
119 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900120 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000121}
122
Andrew Walbranf8d94112021-09-07 11:45:36 +0000123/// The current state of the VM itself.
124#[derive(Debug)]
125pub enum VmState {
126 /// The VM has not yet tried to start.
127 NotStarted {
128 ///The configuration needed to start the VM, if it has not yet been started.
129 config: CrosvmConfig,
130 },
131 /// The VM has been started.
132 Running {
133 /// The crosvm child process.
134 child: Arc<SharedChild>,
135 },
136 /// The VM died or was killed.
137 Dead,
138 /// The VM failed to start.
139 Failed,
140}
141
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900142/// RSS values of VM and CrosVM process itself.
143#[derive(Copy, Clone, Debug, Default)]
144pub struct Rss {
145 pub vm: i64,
146 pub crosvm: i64,
147}
148
149/// Metrics regarding the VM.
150#[derive(Debug, Default)]
151pub struct VmMetric {
152 /// Recorded timestamp when the VM is started.
153 pub start_timestamp: Option<SystemTime>,
154 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
155 pub cpu_guest_time: Option<i64>,
156 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
157 pub rss: Option<Rss>,
158}
159
Andrew Walbranf8d94112021-09-07 11:45:36 +0000160impl VmState {
161 /// Tries to start the VM, if it is in the `NotStarted` state.
162 ///
163 /// Returns an error if the VM is in the wrong state, or fails to start.
164 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
165 let state = mem::replace(self, VmState::Failed);
166 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900167 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000168 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
169
Andrew Walbranf8d94112021-09-07 11:45:36 +0000170 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000171 let child =
172 Arc::new(run_vm(config, &instance.temporary_directory, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000173
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900174 let instance_monitor_status = instance.clone();
175 let child_monitor_status = child.clone();
176 thread::spawn(move || {
177 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
178 });
179
Andrew Walbranf8d94112021-09-07 11:45:36 +0000180 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900181 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000182 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900183 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000184 });
185
Jiyong Parka4eebde2022-07-12 18:01:12 +0900186 if detect_hangup {
187 let child_clone = child.clone();
188 thread::spawn(move || {
189 instance.monitor_payload_hangup(child_clone);
190 });
191 }
192
Andrew Walbranf8d94112021-09-07 11:45:36 +0000193 // If it started correctly, update the state.
194 *self = VmState::Running { child };
195 Ok(())
196 } else {
197 *self = state;
198 bail!("VM already started or failed")
199 }
200 }
201}
202
David Brazdil8cf8f482022-11-23 14:21:26 +0000203/// Internal struct that holds the handles to globally unique resources of a VM.
204#[derive(Debug)]
205pub struct VmContext {
206 #[allow(dead_code)] // Keeps the global context alive
207 global_context: Strong<dyn IGlobalVmContext>,
208 #[allow(dead_code)] // Keeps the server alive
209 vm_server: RpcServer,
210}
211
212impl VmContext {
213 /// Construct new VmContext.
214 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
215 VmContext { global_context, vm_server }
216 }
217}
218
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000220#[derive(Debug)]
221pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000222 /// The current state of the VM.
223 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000224 /// Global resources allocated for this VM.
225 #[allow(dead_code)] // Keeps the context alive
226 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000227 /// The CID assigned to the VM for vsock communication.
228 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000229 /// The name of the VM.
230 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000231 /// Whether the VM is a protected VM.
232 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000233 /// Directory of temporary files used by the VM while it is running.
234 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000235 /// The UID of the process which requested the VM.
236 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000237 /// The PID of the process which requested the VM. Note that this process may no longer exist
238 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000239 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000240 /// Callbacks to clients of the VM.
241 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000242 /// VirtualMachineService binder object for the VM.
243 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900244 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
245 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000246 /// The latest lifecycle state which the payload reported itself to be in.
247 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900248 /// Represents the condition that payload_state was updated
249 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000250}
251
252impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000253 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
254 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000255 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000256 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000257 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000258 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000259 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000260 ) -> Result<VmInstance, Error> {
261 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000262 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000263 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000264 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000265 Ok(VmInstance {
266 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100267 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000268 cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000269 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000270 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000271 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000272 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000273 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000274 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000275 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900276 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000277 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900278 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000279 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000280 }
281
Andrew Walbranf8d94112021-09-07 11:45:36 +0000282 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
283 /// the `VmInstance` is dropped.
284 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900285 let mut vm_metric = self.vm_metric.lock().unwrap();
286 vm_metric.start_timestamp = Some(SystemTime::now());
Andrew Walbranf8d94112021-09-07 11:45:36 +0000287 self.vm_state.lock().unwrap().start(self.clone())
288 }
289
Jiyong Parka4eebde2022-07-12 18:01:12 +0900290 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
291 /// handles the event by updating the state, noityfing the event to clients by calling
292 /// callbacks, and removing temporary files for the VM.
293 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000294 let result = child.wait();
295 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900296 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000297 Ok(status) => {
298 info!("crosvm({}) exited with status {}", child.id(), status);
299 if let Some(exit_status_code) = status.code() {
300 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
301 info!("detected vcpu stall on crosvm");
302 }
303 }
304 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000305 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000306
307 let mut vm_state = self.vm_state.lock().unwrap();
308 *vm_state = VmState::Dead;
309 // Ensure that the mutex is released before calling the callbacks.
310 drop(vm_state);
311
Jiyong Parka4eebde2022-07-12 18:01:12 +0900312 // Read the pipe to see if any failure reason is written
313 let mut failure_reason = String::new();
314 match failure_pipe_read.read_to_string(&mut failure_reason) {
315 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
316 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
317 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900318 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000319
Jiyong Parka4eebde2022-07-12 18:01:12 +0900320 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
321 // detected on the VM side (otherwise, it isn't a hangup), but in the
322 // monitor_payload_hangup function below which updates the payload state to Hangup.
323 let failure_reason =
324 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
325 Cow::from("HANGUP")
326 } else {
327 Cow::from(failure_reason)
328 };
329
Jiyong Parke558ab12022-07-07 20:18:55 +0900330 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000331
332 let death_reason = death_reason(&result, &failure_reason);
333 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900334
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900335 let vm_metric = self.vm_metric.lock().unwrap();
336 write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000337
338 // Delete temporary files.
339 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000340 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000341 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000342 }
343
Jiyong Parka4eebde2022-07-12 18:01:12 +0900344 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
345 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
346 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
347 debug!("Starting to monitor hangup for Microdroid({})", child.id());
348 let (_, result) = self
349 .payload_state_updated
350 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
351 *s < PayloadState::Started
352 })
353 .unwrap();
354 let child_still_running = child.try_wait().ok() == Some(None);
355 if result.timed_out() && child_still_running {
356 error!(
357 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
358 child.id(),
359 BOOT_HANGUP_TIMEOUT.as_secs()
360 );
361 self.update_payload_state(PayloadState::Hangup).unwrap();
362 if let Err(e) = self.kill() {
363 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
364 }
365 }
366 }
367
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900368 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
369 let pid = child.id();
370
371 loop {
372 {
373 // Check VM state
374 let vm_state = &*self.vm_state.lock().unwrap();
375 if let VmState::Dead = vm_state {
376 break;
377 }
378
379 let mut vm_metric = self.vm_metric.lock().unwrap();
380
381 // Get CPU Information
382 // TODO: Collect it once right before VM dies using SIGCHLD
383 if let Ok(guest_time) = get_guest_time(pid) {
384 vm_metric.cpu_guest_time = Some(guest_time);
385 } else {
386 error!("Failed to parse /proc/[pid]/stat");
387 }
388
389 // Get Memory Information
390 if let Ok(rss) = get_rss(pid) {
391 vm_metric.rss = match &vm_metric.rss {
392 Some(x) => Some(Rss::extract_max(x, &rss)),
393 None => Some(rss),
394 }
395 } else {
396 error!("Failed to parse /proc/[pid]/smaps");
397 }
398 }
399
400 thread::sleep(Duration::from_secs(1));
401 }
402 }
403
Andrew Walbran6b650662021-09-07 13:13:23 +0000404 /// Returns the last reported state of the VM payload.
405 pub fn payload_state(&self) -> PayloadState {
406 *self.payload_state.lock().unwrap()
407 }
408
409 /// Updates the payload state to the given value, if it is a valid state transition.
410 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
411 let mut state_locked = self.payload_state.lock().unwrap();
412 // Only allow forward transitions, e.g. from starting to started or finished, not back in
413 // the other direction.
414 if new_state > *state_locked {
415 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900416 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000417 Ok(())
418 } else {
419 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
420 }
421 }
422
Andrew Walbranf8d94112021-09-07 11:45:36 +0000423 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900424 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000425 let vm_state = &*self.vm_state.lock().unwrap();
426 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900427 let id = child.id();
428 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000429 // TODO: Talk to crosvm to shutdown cleanly.
430 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900431 bail!("Error killing crosvm({}) instance: {}", id, e);
432 } else {
433 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000434 }
Inseob Kima446f802022-07-11 19:46:37 +0900435 } else {
436 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000437 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000438 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900439
440 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
441 /// to read the ramdump.
442 fn handle_ramdump(&self) -> Result<(), Error> {
443 let ramdump_path = self.temporary_directory.join("ramdump");
444 if std::fs::metadata(&ramdump_path)?.len() > 0 {
445 let ramdump = File::open(&ramdump_path)
446 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
447 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900448
449 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900450 }
451 Ok(())
452 }
Jiyong Park1612b902022-08-22 14:47:39 +0900453
454 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
455 let mut input = File::open(ramdump_path)
456 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
457
458 let pid = std::process::id() as i32;
459 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
460 .context("Failed to connect to tombstoned")?;
461 let mut output = conn
462 .text_output
463 .as_ref()
464 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
465
466 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
467 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
468
469 conn.notify_completion()?;
470 Ok(())
471 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000472}
473
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900474impl Rss {
475 fn extract_max(x: &Rss, y: &Rss) -> Rss {
476 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
477 }
478}
479
480// Get guest time from /proc/[crosvm pid]/stat
481fn get_guest_time(pid: u32) -> Result<i64> {
482 let file = read_to_string(format!("/proc/{}/stat", pid))?;
483 let data_list: Vec<_> = file.split_whitespace().collect();
484
485 // Information about guest_time is at 43th place of the file split with the whitespace.
486 // Example of /proc/[pid]/stat :
487 // 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
488 // 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
489 if data_list.len() < 43 {
490 bail!("Failed to parse command result for getting guest time : {}", file);
491 }
492
493 let guest_time_ticks = data_list[42].parse::<i64>()?;
494 // SAFETY : It just returns an integer about CPU tick information.
495 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64;
496 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
497}
498
499// Get rss from /proc/[crosvm pid]/smaps
500fn get_rss(pid: u32) -> Result<Rss> {
501 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
502 let lines: Vec<_> = file.split('\n').collect();
503
504 let mut rss_vm_total = 0i64;
505 let mut rss_crosvm_total = 0i64;
506 let mut is_vm = false;
507 for line in lines {
508 if line.contains("crosvm_guest") {
509 is_vm = true;
510 } else if line.contains("Rss:") {
511 let data_list: Vec<_> = line.split_whitespace().collect();
512 if data_list.len() < 2 {
513 bail!("Failed to parse command result for getting rss :\n{}", line);
514 }
515 let rss = data_list[1].parse::<i64>()?;
516
517 if is_vm {
518 rss_vm_total += rss;
519 is_vm = false;
520 }
521 rss_crosvm_total += rss;
522 }
523 }
524
525 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
526}
527
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100528fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
529 if let Some(position) = failure_reason.find('|') {
530 // Separator indicates extra context information is present after the failure name.
531 error!("Failure info: {}", &failure_reason[(position + 1)..]);
532 failure_reason = &failure_reason[..position];
533 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000534 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000535 match failure_reason {
536 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
537 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
538 }
539 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
540 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
541 }
542 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
543 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
544 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
545 }
Inseob Kim272f5722022-06-13 17:14:51 +0900546 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
547 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
548 }
549 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
550 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
551 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
552 }
553 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
554 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
555 }
556 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
557 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
558 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900559 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000560 _ => {}
561 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000562 match status.code() {
563 None => DeathReason::KILLED,
564 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000565 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000566 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000567 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000568 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000569 Some(_) => DeathReason::UNKNOWN,
570 }
571 } else {
572 DeathReason::INFRASTRUCTURE_ERROR
573 }
574}
575
Andrew Walbrand3a84182021-09-07 14:48:52 +0000576/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000577fn run_vm(
578 config: CrosvmConfig,
579 temporary_directory: &Path,
580 failure_pipe_write: File,
581) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000582 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000583
584 let mut command = Command::new(CROSVM_PATH);
585 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000586 command
587 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900588 // Configure the logger for the crosvm process to silence logs from the disk crate which
589 // don't provide much information to us (but do spamming us).
590 .arg("--log-level")
591 .arg("info,disk=off")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000592 .arg("run")
593 .arg("--disable-sandbox")
594 .arg("--cid")
595 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000596
Keir Fraserf25cb922022-11-23 14:26:00 +0000597 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
598 command.arg("--balloon-page-reporting");
599 } else {
600 command.arg("--no-balloon");
601 }
602
Andrew Walbranf8650422021-06-09 15:54:09 +0000603 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000604 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000605
606 // 3 virtio-console devices + vsock = 4.
607 let virtio_pci_device_count = 4 + config.disks.len();
608 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
609 // enough.
610 let swiotlb_size_mib = 2 * virtio_pci_device_count;
611 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000612 }
613
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000614 if let Some(memory_mib) = config.memory_mib {
615 command.arg("--mem").arg(memory_mib.to_string());
616 }
617
Jiyong Park032615f2022-01-10 13:55:34 +0900618 if let Some(cpus) = config.cpus {
619 command.arg("--cpus").arg(cpus.to_string());
620 }
621
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900622 if !config.task_profiles.is_empty() {
623 command.arg("--task-profiles").arg(config.task_profiles.join(","));
624 }
625
Jiyong Parkfa91d702021-10-18 23:51:39 +0900626 // Keep track of what file descriptors should be mapped to the crosvm process.
627 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
628
Jiyong Park747d6362021-10-19 17:12:52 +0900629 // Setup the serial devices.
630 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000631 // 2. uart device: used to report the reason for the VM failing.
632 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900633 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000634 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900635 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900636 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
637 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000638 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
639 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
640 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900641 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900642
Jiyong Park747d6362021-10-19 17:12:52 +0900643 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
644 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
645 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
646 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900647 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000648 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
649 // /dev/ttyS1
650 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900651 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900652 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900653 // /dev/hvc1
654 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900655 // /dev/hvc2
656 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000657
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000658 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000659 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000660 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000661
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000662 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000663 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000664 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000665
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000666 if let Some(params) = &config.params {
667 command.arg("--params").arg(params);
668 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000669
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000670 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000671 command
672 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000673 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000674 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000675
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000676 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000677 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000678 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000679
Keir Fraser13a956a2022-07-14 14:20:46 +0000680 let control_server_socket =
681 UnixSeqpacketListener::bind(temporary_directory.join("crosvm.sock"))
682 .context("failed to create control server")?;
683 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
684
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000685 debug!("Preserving FDs {:?}", preserved_fds);
686 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000687
Jaewan Kimb2814062022-11-14 13:21:40 +0900688 command.arg("--params").arg("crashkernel=17M");
Jiyong Park2d736562022-10-24 22:40:12 +0900689 print_crosvm_args(&command);
690
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000691 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900692 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000693 Ok(result)
694}
695
696/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000697fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000698 if config.bootloader.is_none() && config.kernel.is_none() {
699 bail!("VM must have either a bootloader or a kernel image.");
700 }
701 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
702 bail!("Can't have both bootloader and kernel/initrd image.");
703 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900704 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
705 if !config.platform_version.matches(&version) {
706 bail!(
707 "Incompatible platform version. The config is compatible with platform version(s) \
708 {}, but the actual platform version is {}",
709 config.platform_version,
710 version
711 );
712 }
713
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000714 Ok(())
715}
716
Jiyong Park2d736562022-10-24 22:40:12 +0900717/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
718/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
719/// unmodified.
720fn print_crosvm_args(command: &Command) {
721 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
722 info!(
723 "Running crosvm with args: {:?}",
724 command
725 .get_args()
726 .map(|s| s.to_string_lossy())
727 .map(|s| {
728 re.replace_all(&s, |caps: &Captures| {
729 let path = &caps[0];
730 if let Ok(realpath) = std::fs::canonicalize(path) {
731 format!("{} ({})", path, realpath.to_string_lossy())
732 } else {
733 path.to_owned()
734 }
735 })
736 .into_owned()
737 })
738 .collect::<Vec<_>>()
739 );
740}
741
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000742/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
743/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000744fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000745 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000746 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000747 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000748}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000749
750/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
751/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
752fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
753 if let Some(file) = file {
754 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
755 } else {
756 "type=sink".to_string()
757 }
758}
759
760/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
761fn create_pipe() -> Result<(File, File), Error> {
762 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
763 // SAFETY: We are the sole owners of these fds as they were just created.
764 let read_fd = unsafe { File::from_raw_fd(raw_read) };
765 let write_fd = unsafe { File::from_raw_fd(raw_write) };
766 Ok((read_fd, write_fd))
767}