blob: 1456d17bf2bc7ee016058c9932eb87c0ef2eed35 [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 Brazdil4b4c5102022-12-19 22:56:20 +000017use crate::aidl::{remove_temporary_files, Cid, VirtualMachineCallbacks};
David Brazdil25e8c052023-02-17 12:53:01 +000018use crate::atom::{get_num_cpus, 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};
Jiyong Park08eee7b2022-11-11 15:01:26 +090025use nix::{fcntl::OFlag, unistd::pipe2, unistd::Uid, unistd::User};
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;
Jiyong Park08eee7b2022-11-11 15:01:26 +090031use std::fmt;
David Brazdil4b4c5102022-12-19 22:56:20 +000032use std::fs::{read_to_string, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000033use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000034use std::mem;
Nikita Ioffe5776f082023-02-10 21:38:26 +000035use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbranb27681f2022-02-23 15:11:52 +000036use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Seungjae Yoo93430e82022-12-05 16:37:42 +090037use std::os::unix::process::ExitStatusExt;
Jiyong Park1612b902022-08-22 14:47:39 +090038use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000039use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090040use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090041use std::time::{Duration, SystemTime};
David Brazdilf18e1162022-12-18 18:27:23 +000042use std::thread::{self, JoinHandle};
David Brazdil49f96f52022-12-16 21:29:13 +000043use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
44use android_system_virtualizationservice::aidl::android::system::virtualizationservice::MemoryTrimLevel::MemoryTrimLevel;
David Brazdil528e0472022-10-10 15:06:02 +010045use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010046use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000047use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090048use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
David Brazdil73988ea2022-11-11 15:10:32 +000049use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000050
Keir Fraser13a956a2022-07-14 14:20:46 +000051/// external/crosvm
52use base::UnixSeqpacketListener;
Keir Frasercdd4b112022-11-24 14:02:25 +000053use vm_control::{BalloonControlCommand, VmRequest, VmResponse};
Keir Fraser13a956a2022-07-14 14:20:46 +000054
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000055const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
56
Jiyong Parkdcf17412022-02-08 15:07:23 +090057/// Version of the platform that crosvm currently implements. The format follows SemVer. This
58/// should be updated when there is a platform change in the crosvm side. Having this value here is
59/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
60/// APEX.
61const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
62
Andrew Walbrand15c5632022-02-03 13:38:31 +000063/// The exit status which crosvm returns when it has an error starting a VM.
Alan Stokes7c459e82022-12-06 12:21:49 +000064const CROSVM_START_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000065/// The exit status which crosvm returns when a VM requests a reboot.
66const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000067/// The exit status which crosvm returns when it crashes due to an error.
68const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000069/// The exit status which crosvm returns when vcpu is stalled.
70const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000071
Seungjae Yoo6d265d92022-11-15 10:51:33 +090072const MILLIS_PER_SEC: i64 = 1000;
73
Jaewan Kim46422812022-11-25 10:59:39 +090074const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path";
75
Jiyong Parke6ed0f92022-06-22 00:13:00 +090076lazy_static! {
77 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
78 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010079 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090080 // Nested virtualization is slow, so we need a longer timeout.
Inseob Kime557cec2023-01-26 22:49:58 +090081 Duration::from_secs(300)
Jiyong Parke6ed0f92022-06-22 00:13:00 +090082 } else {
Inseob Kime557cec2023-01-26 22:49:58 +090083 Duration::from_secs(30)
Jiyong Parke6ed0f92022-06-22 00:13:00 +090084 };
85}
86
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087/// Configuration for a VM to run with crosvm.
88#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000089pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000091 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000092 pub bootloader: Option<File>,
93 pub kernel: Option<File>,
94 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000095 pub disks: Vec<DiskFile>,
96 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000097 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000098 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090099 pub cpus: Option<NonZeroU32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000100 pub host_cpu_topology: bool,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900101 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900102 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000103 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +0900104 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000105 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900106 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900107 pub detect_hangup: bool,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000108 pub gdb_port: Option<NonZeroU16>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109}
110
111/// A disk image to pass to crosvm for a VM.
112#[derive(Debug)]
113pub struct DiskFile {
114 pub image: File,
115 pub writable: bool,
116}
117
Andrew Walbran6b650662021-09-07 13:13:23 +0000118/// The lifecycle state which the payload in the VM has reported itself to be in.
119///
120/// Note that the order of enum variants is significant; only forward transitions are allowed by
121/// [`VmInstance::update_payload_state`].
122#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
123pub enum PayloadState {
124 Starting,
125 Started,
126 Ready,
127 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900128 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000129}
130
Andrew Walbranf8d94112021-09-07 11:45:36 +0000131/// The current state of the VM itself.
132#[derive(Debug)]
133pub enum VmState {
134 /// The VM has not yet tried to start.
135 NotStarted {
136 ///The configuration needed to start the VM, if it has not yet been started.
137 config: CrosvmConfig,
138 },
139 /// The VM has been started.
140 Running {
141 /// The crosvm child process.
142 child: Arc<SharedChild>,
David Brazdilf18e1162022-12-18 18:27:23 +0000143 /// The thread waiting for crosvm to finish.
144 monitor_vm_exit_thread: Option<JoinHandle<()>>,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000145 },
146 /// The VM died or was killed.
147 Dead,
148 /// The VM failed to start.
149 Failed,
150}
151
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900152/// RSS values of VM and CrosVM process itself.
153#[derive(Copy, Clone, Debug, Default)]
154pub struct Rss {
155 pub vm: i64,
156 pub crosvm: i64,
157}
158
159/// Metrics regarding the VM.
160#[derive(Debug, Default)]
161pub struct VmMetric {
162 /// Recorded timestamp when the VM is started.
163 pub start_timestamp: Option<SystemTime>,
164 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
165 pub cpu_guest_time: Option<i64>,
166 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
167 pub rss: Option<Rss>,
168}
169
Andrew Walbranf8d94112021-09-07 11:45:36 +0000170impl VmState {
171 /// Tries to start the VM, if it is in the `NotStarted` state.
172 ///
173 /// Returns an error if the VM is in the wrong state, or fails to start.
174 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
175 let state = mem::replace(self, VmState::Failed);
176 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900177 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000178 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
179
Andrew Walbranf8d94112021-09-07 11:45:36 +0000180 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000181 let child =
Keir Frasercdd4b112022-11-24 14:02:25 +0000182 Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000183
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900184 let instance_monitor_status = instance.clone();
185 let child_monitor_status = child.clone();
186 thread::spawn(move || {
187 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
188 });
189
Andrew Walbranf8d94112021-09-07 11:45:36 +0000190 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900191 let instance_clone = instance.clone();
David Brazdilf18e1162022-12-18 18:27:23 +0000192 let monitor_vm_exit_thread = Some(thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900193 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
David Brazdilf18e1162022-12-18 18:27:23 +0000194 }));
Andrew Walbranf8d94112021-09-07 11:45:36 +0000195
Jiyong Parka4eebde2022-07-12 18:01:12 +0900196 if detect_hangup {
197 let child_clone = child.clone();
198 thread::spawn(move || {
199 instance.monitor_payload_hangup(child_clone);
200 });
201 }
202
Andrew Walbranf8d94112021-09-07 11:45:36 +0000203 // If it started correctly, update the state.
David Brazdilf18e1162022-12-18 18:27:23 +0000204 *self = VmState::Running { child, monitor_vm_exit_thread };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000205 Ok(())
206 } else {
207 *self = state;
208 bail!("VM already started or failed")
209 }
210 }
211}
212
David Brazdil8cf8f482022-11-23 14:21:26 +0000213/// Internal struct that holds the handles to globally unique resources of a VM.
214#[derive(Debug)]
215pub struct VmContext {
216 #[allow(dead_code)] // Keeps the global context alive
217 global_context: Strong<dyn IGlobalVmContext>,
218 #[allow(dead_code)] // Keeps the server alive
219 vm_server: RpcServer,
220}
221
222impl VmContext {
223 /// Construct new VmContext.
224 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
225 VmContext { global_context, vm_server }
226 }
227}
228
Andrew Walbranf8d94112021-09-07 11:45:36 +0000229/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000230#[derive(Debug)]
231pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000232 /// The current state of the VM.
233 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000234 /// Global resources allocated for this VM.
235 #[allow(dead_code)] // Keeps the context alive
236 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000237 /// The CID assigned to the VM for vsock communication.
238 pub cid: Cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000239 /// Path to crosvm control socket
240 crosvm_control_socket_path: PathBuf,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000241 /// The name of the VM.
242 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000243 /// Whether the VM is a protected VM.
244 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000245 /// Directory of temporary files used by the VM while it is running.
246 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000247 /// The UID of the process which requested the VM.
248 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000249 /// The PID of the process which requested the VM. Note that this process may no longer exist
250 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000251 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000252 /// Callbacks to clients of the VM.
253 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000254 /// VirtualMachineService binder object for the VM.
255 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900256 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
257 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000258 /// The latest lifecycle state which the payload reported itself to be in.
259 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900260 /// Represents the condition that payload_state was updated
261 payload_state_updated: Condvar,
Jiyong Park08eee7b2022-11-11 15:01:26 +0900262 /// The human readable name of requester_uid
263 requester_uid_name: String,
264}
265
266impl fmt::Display for VmInstance {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 let adj = if self.protected { "Protected" } else { "Non-protected" };
269 write!(
270 f,
271 "{} virtual machine \"{}\" (owner: {}, cid: {})",
272 adj, self.name, self.requester_uid_name, self.cid
273 )
274 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000275}
276
277impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000278 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
279 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000280 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000281 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000282 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000283 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000284 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000285 ) -> Result<VmInstance, Error> {
286 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000287 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000288 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000289 let protected = config.protected;
Jiyong Park08eee7b2022-11-11 15:01:26 +0900290 let requester_uid_name = User::from_uid(Uid::from_raw(requester_uid))
291 .ok()
292 .flatten()
293 .map_or_else(|| format!("{}", requester_uid), |u| u.name);
294 let instance = VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000295 vm_state: Mutex::new(VmState::NotStarted { config }),
David Brazdil528e0472022-10-10 15:06:02 +0100296 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000297 cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000298 crosvm_control_socket_path: temporary_directory.join("crosvm.sock"),
Seungjae Yoo62085c02022-08-12 04:44:52 +0000299 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000300 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000301 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000302 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000303 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000304 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000305 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900306 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000307 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900308 payload_state_updated: Condvar::new(),
Jiyong Park08eee7b2022-11-11 15:01:26 +0900309 requester_uid_name,
310 };
311 info!("{} created", &instance);
312 Ok(instance)
Andrew Walbrandae07162021-03-12 17:05:20 +0000313 }
314
Andrew Walbranf8d94112021-09-07 11:45:36 +0000315 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
316 /// the `VmInstance` is dropped.
317 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900318 let mut vm_metric = self.vm_metric.lock().unwrap();
319 vm_metric.start_timestamp = Some(SystemTime::now());
Jiyong Park08eee7b2022-11-11 15:01:26 +0900320 let ret = self.vm_state.lock().unwrap().start(self.clone());
321 if ret.is_ok() {
322 info!("{} started", &self);
323 }
324 ret.with_context(|| format!("{} failed to start", &self))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000325 }
326
Jiyong Parka4eebde2022-07-12 18:01:12 +0900327 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
328 /// handles the event by updating the state, noityfing the event to clients by calling
329 /// callbacks, and removing temporary files for the VM.
330 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000331 let result = child.wait();
332 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900333 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000334 Ok(status) => {
335 info!("crosvm({}) exited with status {}", child.id(), status);
336 if let Some(exit_status_code) = status.code() {
337 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
338 info!("detected vcpu stall on crosvm");
339 }
340 }
341 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000342 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000343
344 let mut vm_state = self.vm_state.lock().unwrap();
345 *vm_state = VmState::Dead;
346 // Ensure that the mutex is released before calling the callbacks.
347 drop(vm_state);
Jiyong Park08eee7b2022-11-11 15:01:26 +0900348 info!("{} exited", &self);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000349
Jiyong Parka4eebde2022-07-12 18:01:12 +0900350 // Read the pipe to see if any failure reason is written
351 let mut failure_reason = String::new();
352 match failure_pipe_read.read_to_string(&mut failure_reason) {
353 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
354 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
355 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900356 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000357
Jiyong Parka4eebde2022-07-12 18:01:12 +0900358 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
359 // detected on the VM side (otherwise, it isn't a hangup), but in the
360 // monitor_payload_hangup function below which updates the payload state to Hangup.
361 let failure_reason =
362 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
363 Cow::from("HANGUP")
364 } else {
365 Cow::from(failure_reason)
366 };
367
Jiyong Parke558ab12022-07-07 20:18:55 +0900368 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000369
370 let death_reason = death_reason(&result, &failure_reason);
Seungjae Yoo93430e82022-12-05 16:37:42 +0900371 let exit_signal = exit_signal(&result);
372
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000373 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900374
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900375 let vm_metric = self.vm_metric.lock().unwrap();
Seungjae Yoo93430e82022-12-05 16:37:42 +0900376 write_vm_exited_stats(
377 self.requester_uid as i32,
378 &self.name,
379 death_reason,
380 exit_signal,
Chris Wailes75269622022-12-05 23:01:44 -0800381 &vm_metric,
Seungjae Yoo93430e82022-12-05 16:37:42 +0900382 );
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000383
David Brazdil4b4c5102022-12-19 22:56:20 +0000384 // Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
385 remove_temporary_files(&self.temporary_directory).unwrap_or_else(|e| {
386 error!("Error removing temporary files from {:?}: {}", self.temporary_directory, e);
387 });
Andrew Walbrandae07162021-03-12 17:05:20 +0000388 }
389
Jiyong Parka4eebde2022-07-12 18:01:12 +0900390 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
391 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
392 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
393 debug!("Starting to monitor hangup for Microdroid({})", child.id());
394 let (_, result) = self
395 .payload_state_updated
396 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
397 *s < PayloadState::Started
398 })
399 .unwrap();
400 let child_still_running = child.try_wait().ok() == Some(None);
401 if result.timed_out() && child_still_running {
402 error!(
403 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
404 child.id(),
405 BOOT_HANGUP_TIMEOUT.as_secs()
406 );
407 self.update_payload_state(PayloadState::Hangup).unwrap();
408 if let Err(e) = self.kill() {
409 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
410 }
411 }
412 }
413
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900414 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
415 let pid = child.id();
416
417 loop {
418 {
419 // Check VM state
420 let vm_state = &*self.vm_state.lock().unwrap();
421 if let VmState::Dead = vm_state {
422 break;
423 }
424
425 let mut vm_metric = self.vm_metric.lock().unwrap();
426
427 // Get CPU Information
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900428 if let Ok(guest_time) = get_guest_time(pid) {
429 vm_metric.cpu_guest_time = Some(guest_time);
430 } else {
431 error!("Failed to parse /proc/[pid]/stat");
432 }
433
434 // Get Memory Information
435 if let Ok(rss) = get_rss(pid) {
436 vm_metric.rss = match &vm_metric.rss {
437 Some(x) => Some(Rss::extract_max(x, &rss)),
438 None => Some(rss),
439 }
440 } else {
441 error!("Failed to parse /proc/[pid]/smaps");
442 }
443 }
444
445 thread::sleep(Duration::from_secs(1));
446 }
447 }
448
Andrew Walbran6b650662021-09-07 13:13:23 +0000449 /// Returns the last reported state of the VM payload.
450 pub fn payload_state(&self) -> PayloadState {
451 *self.payload_state.lock().unwrap()
452 }
453
454 /// Updates the payload state to the given value, if it is a valid state transition.
455 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
456 let mut state_locked = self.payload_state.lock().unwrap();
457 // Only allow forward transitions, e.g. from starting to started or finished, not back in
458 // the other direction.
459 if new_state > *state_locked {
460 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900461 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000462 Ok(())
463 } else {
464 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
465 }
466 }
467
Andrew Walbranf8d94112021-09-07 11:45:36 +0000468 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900469 pub fn kill(&self) -> Result<(), Error> {
David Brazdilf18e1162022-12-18 18:27:23 +0000470 let monitor_vm_exit_thread = {
471 let vm_state = &mut *self.vm_state.lock().unwrap();
472 if let VmState::Running { child, monitor_vm_exit_thread } = vm_state {
473 let id = child.id();
474 debug!("Killing crosvm({})", id);
475 // TODO: Talk to crosvm to shutdown cleanly.
476 child.kill().with_context(|| format!("Error killing crosvm({id}) instance"))?;
477 monitor_vm_exit_thread.take()
Inseob Kima446f802022-07-11 19:46:37 +0900478 } else {
David Brazdilf18e1162022-12-18 18:27:23 +0000479 bail!("VM is not running")
Andrew Walbranf8d94112021-09-07 11:45:36 +0000480 }
David Brazdilf18e1162022-12-18 18:27:23 +0000481 };
482
483 // Wait for monitor_vm_exit() to finish. Must release vm_state lock
484 // first, as monitor_vm_exit() takes it as well.
485 monitor_vm_exit_thread.map(JoinHandle::join);
486
487 Ok(())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000488 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900489
Keir Frasercdd4b112022-11-24 14:02:25 +0000490 /// Responds to memory-trimming notifications by inflating the virtio
491 /// balloon to reclaim guest memory.
492 pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> {
493 let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {});
494 match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) {
495 Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => {
496 if let Some(total_memory) = stats.total_memory {
497 // Reclaim up to 50% of total memory assuming worst case
498 // most memory is anonymous and must be swapped to zram
499 // with an approximate 2:1 compression ratio.
500 let pct = match level {
501 MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50,
502 MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30,
503 MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10,
504 _ => bail!("Invalid memory trim level {:?}", level),
505 };
506 let command =
507 BalloonControlCommand::Adjust { num_bytes: total_memory * pct / 100 };
508 if let Err(e) = vm_control::client::handle_request(
509 &VmRequest::BalloonCommand(command),
510 &self.crosvm_control_socket_path,
511 ) {
512 bail!("Error sending balloon adjustment: {:?}", e);
513 }
514 }
515 }
516 Ok(VmResponse::Err(e)) => {
517 // ENOTSUP is returned when the balloon protocol is not initialised. This
518 // can occur for numerous reasons: Guest is still booting, guest doesn't
519 // support ballooning, host doesn't support ballooning. We don't log or
520 // raise an error in this case: trim is just a hint and we can ignore it.
521 if e.errno() != libc::ENOTSUP {
522 bail!("Errno return when requesting balloon stats: {}", e.errno())
523 }
524 }
525 e => bail!("Error requesting balloon stats: {:?}", e),
526 }
527 Ok(())
528 }
529
Alan Stokes3e98d292022-12-14 15:18:22 +0000530 /// Checks if ramdump has been created. If so, send it to tombstoned.
Jiyong Parke558ab12022-07-07 20:18:55 +0900531 fn handle_ramdump(&self) -> Result<(), Error> {
532 let ramdump_path = self.temporary_directory.join("ramdump");
533 if std::fs::metadata(&ramdump_path)?.len() > 0 {
Jiyong Park1612b902022-08-22 14:47:39 +0900534 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900535 }
536 Ok(())
537 }
Jiyong Park1612b902022-08-22 14:47:39 +0900538
539 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
540 let mut input = File::open(ramdump_path)
Alan Stokes3e98d292022-12-14 15:18:22 +0000541 .context(format!("Failed to open ramdump {:?} for reading", ramdump_path))?;
Jiyong Park1612b902022-08-22 14:47:39 +0900542
543 let pid = std::process::id() as i32;
544 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
545 .context("Failed to connect to tombstoned")?;
546 let mut output = conn
547 .text_output
548 .as_ref()
549 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
550
551 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
552 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
553
554 conn.notify_completion()?;
555 Ok(())
556 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000557}
558
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900559impl Rss {
560 fn extract_max(x: &Rss, y: &Rss) -> Rss {
561 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
562 }
563}
564
565// Get guest time from /proc/[crosvm pid]/stat
566fn get_guest_time(pid: u32) -> Result<i64> {
567 let file = read_to_string(format!("/proc/{}/stat", pid))?;
568 let data_list: Vec<_> = file.split_whitespace().collect();
569
570 // Information about guest_time is at 43th place of the file split with the whitespace.
571 // Example of /proc/[pid]/stat :
572 // 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
573 // 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
574 if data_list.len() < 43 {
575 bail!("Failed to parse command result for getting guest time : {}", file);
576 }
577
578 let guest_time_ticks = data_list[42].parse::<i64>()?;
579 // SAFETY : It just returns an integer about CPU tick information.
Charisee96113f32023-01-26 09:00:42 +0000580 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) };
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900581 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
582}
583
584// Get rss from /proc/[crosvm pid]/smaps
585fn get_rss(pid: u32) -> Result<Rss> {
586 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
587 let lines: Vec<_> = file.split('\n').collect();
588
589 let mut rss_vm_total = 0i64;
590 let mut rss_crosvm_total = 0i64;
591 let mut is_vm = false;
592 for line in lines {
593 if line.contains("crosvm_guest") {
594 is_vm = true;
595 } else if line.contains("Rss:") {
596 let data_list: Vec<_> = line.split_whitespace().collect();
597 if data_list.len() < 2 {
598 bail!("Failed to parse command result for getting rss :\n{}", line);
599 }
600 let rss = data_list[1].parse::<i64>()?;
601
602 if is_vm {
603 rss_vm_total += rss;
604 is_vm = false;
605 }
606 rss_crosvm_total += rss;
607 }
608 }
609
610 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
611}
612
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100613fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
614 if let Some(position) = failure_reason.find('|') {
615 // Separator indicates extra context information is present after the failure name.
616 error!("Failure info: {}", &failure_reason[(position + 1)..]);
617 failure_reason = &failure_reason[..position];
618 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000619 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000620 match failure_reason {
621 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
622 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
623 }
624 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
625 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
626 }
627 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
628 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
629 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
630 }
Inseob Kim272f5722022-06-13 17:14:51 +0900631 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
632 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
633 }
634 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
635 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
636 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
637 }
638 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
639 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
640 }
641 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
642 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
643 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900644 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000645 _ => {}
646 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000647 match status.code() {
648 None => DeathReason::KILLED,
649 Some(0) => DeathReason::SHUTDOWN,
Alan Stokes7c459e82022-12-06 12:21:49 +0000650 Some(CROSVM_START_ERROR_STATUS) => DeathReason::START_FAILED,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000651 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000652 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000653 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000654 Some(_) => DeathReason::UNKNOWN,
655 }
656 } else {
657 DeathReason::INFRASTRUCTURE_ERROR
658 }
659}
660
Seungjae Yoo93430e82022-12-05 16:37:42 +0900661fn exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32> {
662 match result {
663 Ok(status) => status.signal(),
664 Err(_) => None,
665 }
666}
667
Jaewan Kimd1884ca2023-02-06 05:15:58 +0000668fn should_configure_ramdump(protected: bool) -> bool {
669 if protected {
670 // Protected VM needs ramdump configuration here.
671 // pvmfw will disable ramdump if unnecessary.
672 true
673 } else {
674 // For unprotected VM, ramdump should be handled here.
675 // ramdump wouldn't be enabled if ramdump is explicitly set to <1>.
676 if let Ok(mut file) = File::open("/proc/device-tree/avf/guest/common/ramdump") {
677 let mut ramdump: [u8; 4] = Default::default();
678 file.read_exact(&mut ramdump).map_err(|_| false).unwrap();
679 // DT spec uses big endian although Android is always little endian.
680 return u32::from_be_bytes(ramdump) == 1;
681 }
682 false
683 }
684}
685
Andrew Walbrand3a84182021-09-07 14:48:52 +0000686/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000687fn run_vm(
688 config: CrosvmConfig,
Keir Frasercdd4b112022-11-24 14:02:25 +0000689 crosvm_control_socket_path: &Path,
Keir Fraser13a956a2022-07-14 14:20:46 +0000690 failure_pipe_write: File,
691) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000692 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000693
694 let mut command = Command::new(CROSVM_PATH);
695 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000696 command
697 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900698 // Configure the logger for the crosvm process to silence logs from the disk crate which
699 // don't provide much information to us (but do spamming us).
700 .arg("--log-level")
Frederick Mayle138f53c2023-01-24 18:55:26 -0800701 .arg("info,disk=warn")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000702 .arg("run")
703 .arg("--disable-sandbox")
704 .arg("--cid")
705 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000706
Keir Fraserf25cb922022-11-23 14:26:00 +0000707 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
708 command.arg("--balloon-page-reporting");
709 } else {
710 command.arg("--no-balloon");
711 }
712
Andrew Walbranf8650422021-06-09 15:54:09 +0000713 if config.protected {
Jaewan Kim46422812022-11-25 10:59:39 +0900714 match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? {
715 Some(pvmfw_path) if !pvmfw_path.is_empty() => {
716 command.arg("--protected-vm-with-firmware").arg(pvmfw_path)
717 }
718 _ => command.arg("--protected-vm"),
719 };
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000720
721 // 3 virtio-console devices + vsock = 4.
722 let virtio_pci_device_count = 4 + config.disks.len();
723 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
724 // enough.
725 let swiotlb_size_mib = 2 * virtio_pci_device_count;
726 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Frederick Mayle58baa302023-02-14 19:06:37 -0800727
728 // Workaround to keep crash_dump from trying to read protected guest memory.
729 // Context in b/238324526.
730 command.arg("--unmap-guest-memory-on-fork");
Andrew Walbranf8650422021-06-09 15:54:09 +0000731 }
732
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000733 if let Some(memory_mib) = config.memory_mib {
734 command.arg("--mem").arg(memory_mib.to_string());
735 }
736
Jiyong Park032615f2022-01-10 13:55:34 +0900737 if let Some(cpus) = config.cpus {
738 command.arg("--cpus").arg(cpus.to_string());
739 }
740
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000741 if config.host_cpu_topology {
David Brazdil25e8c052023-02-17 12:53:01 +0000742 // TODO(b/266664564): replace with --host-cpu-topology once available
743 if let Some(cpus) = get_num_cpus() {
744 command.arg("--cpus").arg(cpus.to_string());
745 } else {
746 bail!("Could not determine the number of CPUs in the system");
747 }
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000748 }
749
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900750 if !config.task_profiles.is_empty() {
751 command.arg("--task-profiles").arg(config.task_profiles.join(","));
752 }
753
Nikita Ioffe5776f082023-02-10 21:38:26 +0000754 if let Some(gdb_port) = config.gdb_port {
755 command.arg("--gdb").arg(gdb_port.to_string());
756 }
757
Jiyong Parkfa91d702021-10-18 23:51:39 +0900758 // Keep track of what file descriptors should be mapped to the crosvm process.
759 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
760
Jiyong Park747d6362021-10-19 17:12:52 +0900761 // Setup the serial devices.
762 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000763 // 2. uart device: used to report the reason for the VM failing.
764 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900765 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000766 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900767 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900768 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
769 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000770 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
771 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
772 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900773 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900774
Jiyong Park747d6362021-10-19 17:12:52 +0900775 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
776 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
777 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
778 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900779 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000780 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
781 // /dev/ttyS1
782 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900783 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900784 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900785 // /dev/hvc1
786 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900787 // /dev/hvc2
788 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000789
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000790 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000791 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000792 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000793
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000794 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000795 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000796 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000797
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000798 if let Some(params) = &config.params {
799 command.arg("--params").arg(params);
800 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000801
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000802 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000803 command
804 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000805 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000806 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000807
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000808 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000809 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000810 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000811
Keir Frasercdd4b112022-11-24 14:02:25 +0000812 let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path)
813 .context("failed to create control server")?;
Keir Fraser13a956a2022-07-14 14:20:46 +0000814 command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket));
815
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000816 debug!("Preserving FDs {:?}", preserved_fds);
817 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000818
Jaewan Kimd1884ca2023-02-06 05:15:58 +0000819 if should_configure_ramdump(config.protected) {
820 command.arg("--params").arg("crashkernel=17M");
821 }
822
Jiyong Park2d736562022-10-24 22:40:12 +0900823 print_crosvm_args(&command);
824
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000825 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900826 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000827 Ok(result)
828}
829
830/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000831fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000832 if config.bootloader.is_none() && config.kernel.is_none() {
833 bail!("VM must have either a bootloader or a kernel image.");
834 }
835 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
836 bail!("Can't have both bootloader and kernel/initrd image.");
837 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900838 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
839 if !config.platform_version.matches(&version) {
840 bail!(
841 "Incompatible platform version. The config is compatible with platform version(s) \
842 {}, but the actual platform version is {}",
843 config.platform_version,
844 version
845 );
846 }
847
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000848 Ok(())
849}
850
Jiyong Park2d736562022-10-24 22:40:12 +0900851/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
852/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
853/// unmodified.
854fn print_crosvm_args(command: &Command) {
855 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
856 info!(
857 "Running crosvm with args: {:?}",
858 command
859 .get_args()
860 .map(|s| s.to_string_lossy())
861 .map(|s| {
862 re.replace_all(&s, |caps: &Captures| {
863 let path = &caps[0];
864 if let Ok(realpath) = std::fs::canonicalize(path) {
865 format!("{} ({})", path, realpath.to_string_lossy())
866 } else {
867 path.to_owned()
868 }
869 })
870 .into_owned()
871 })
872 .collect::<Vec<_>>()
873 );
874}
875
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000876/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
877/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000878fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000879 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000880 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000881 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000882}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000883
884/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
885/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
886fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
887 if let Some(file) = file {
888 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
889 } else {
890 "type=sink".to_string()
891 }
892}
893
894/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
895fn create_pipe() -> Result<(File, File), Error> {
896 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
897 // SAFETY: We are the sole owners of these fds as they were just created.
898 let read_fd = unsafe { File::from_raw_fd(raw_read) };
899 let write_fd = unsafe { File::from_raw_fd(raw_write) };
900 Ok((read_fd, write_fd))
901}