blob: bb6066f13648bde8cba3cc7444bf158492b1707b [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};
Seungjae Yoob2db3d22023-04-06 18:05:43 +090018use crate::atom::{get_num_cpus, write_vm_exited_stats_sync};
Jaewan Kim61f86142023-03-28 15:12:52 +090019use crate::debug_config::DebugConfig;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090020use anyhow::{anyhow, bail, Context, Error, Result};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000021use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090022use lazy_static::lazy_static;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090023use libc::{sysconf, _SC_CLK_TCK};
Andrew Walbran3a5a9212021-05-04 17:09:08 +000024use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090025use semver::{Version, VersionReq};
Jiyong Park08eee7b2022-11-11 15:01:26 +090026use nix::{fcntl::OFlag, unistd::pipe2, unistd::Uid, unistd::User};
Jiyong Park2d736562022-10-24 22:40:12 +090027use regex::{Captures, Regex};
Keir Fraserf25cb922022-11-23 14:26:00 +000028use rustutils::system_properties;
Andrew Walbrandae07162021-03-12 17:05:20 +000029use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090030use std::borrow::Cow;
Seungjae Yoo6d265d92022-11-15 10:51:33 +090031use std::cmp::max;
Jiyong Park08eee7b2022-11-11 15:01:26 +090032use std::fmt;
David Brazdil4b4c5102022-12-19 22:56:20 +000033use std::fs::{read_to_string, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000034use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000035use std::mem;
Nikita Ioffe5776f082023-02-10 21:38:26 +000036use std::num::{NonZeroU16, NonZeroU32};
Andrew Walbranb27681f2022-02-23 15:11:52 +000037use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Seungjae Yoo93430e82022-12-05 16:37:42 +090038use std::os::unix::process::ExitStatusExt;
Jiyong Park1612b902022-08-22 14:47:39 +090039use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000040use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090041use std::sync::{Arc, Condvar, Mutex};
Seungjae Yoo2e7beea2022-08-24 16:09:12 +090042use std::time::{Duration, SystemTime};
David Brazdilf18e1162022-12-18 18:27:23 +000043use std::thread::{self, JoinHandle};
David Brazdil49f96f52022-12-16 21:29:13 +000044use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
Jaewan Kim84b91212023-02-28 00:11:57 +090045use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
46 MemoryTrimLevel::MemoryTrimLevel,
47 VirtualMachineAppConfig::DebugLevel::DebugLevel
48};
David Brazdil528e0472022-10-10 15:06:02 +010049use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
Alan Stokes0e82b502022-08-08 14:44:48 +010050use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000051use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090052use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
David Brazdil73988ea2022-11-11 15:10:32 +000053use rpcbinder::RpcServer;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054
Keir Fraser13a956a2022-07-14 14:20:46 +000055/// external/crosvm
Elie Kheirallah2d12ff32023-03-20 18:12:07 +000056use base::AsRawDescriptor;
Keir Fraser13a956a2022-07-14 14:20:46 +000057use base::UnixSeqpacketListener;
Keir Frasercdd4b112022-11-24 14:02:25 +000058use vm_control::{BalloonControlCommand, VmRequest, VmResponse};
Keir Fraser13a956a2022-07-14 14:20:46 +000059
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000060const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
61
Jiyong Parkdcf17412022-02-08 15:07:23 +090062/// Version of the platform that crosvm currently implements. The format follows SemVer. This
63/// should be updated when there is a platform change in the crosvm side. Having this value here is
64/// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
65/// APEX.
66const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
67
Andrew Walbrand15c5632022-02-03 13:38:31 +000068/// The exit status which crosvm returns when it has an error starting a VM.
Alan Stokes7c459e82022-12-06 12:21:49 +000069const CROSVM_START_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000070/// The exit status which crosvm returns when a VM requests a reboot.
71const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000072/// The exit status which crosvm returns when it crashes due to an error.
73const CROSVM_CRASH_STATUS: i32 = 33;
Sebastian Ene23167d82022-10-07 14:09:53 +000074/// The exit status which crosvm returns when vcpu is stalled.
75const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
Jiyong Park3115cdb2023-02-24 18:04:44 +090076/// The size of memory (in MiB) reserved for ramdump
77const RAMDUMP_RESERVED_MIB: u32 = 17;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000078
Seungjae Yoo6d265d92022-11-15 10:51:33 +090079const MILLIS_PER_SEC: i64 = 1000;
80
Jaewan Kim46422812022-11-25 10:59:39 +090081const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path";
82
Jiyong Parke6ed0f92022-06-22 00:13:00 +090083lazy_static! {
84 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
85 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010086 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090087 // Nested virtualization is slow, so we need a longer timeout.
Inseob Kime557cec2023-01-26 22:49:58 +090088 Duration::from_secs(300)
Jiyong Parke6ed0f92022-06-22 00:13:00 +090089 } else {
Inseob Kime557cec2023-01-26 22:49:58 +090090 Duration::from_secs(30)
Jiyong Parke6ed0f92022-06-22 00:13:00 +090091 };
92}
93
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000094/// Configuration for a VM to run with crosvm.
95#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000096pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000097 pub cid: Cid,
Seungjae Yoo62085c02022-08-12 04:44:52 +000098 pub name: String,
Andrew Walbrand3a84182021-09-07 14:48:52 +000099 pub bootloader: Option<File>,
100 pub kernel: Option<File>,
101 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102 pub disks: Vec<DiskFile>,
103 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +0000104 pub protected: bool,
Jaewan Kim61f86142023-03-28 15:12:52 +0900105 pub debug_config: DebugConfig,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000106 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +0900107 pub cpus: Option<NonZeroU32>,
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000108 pub host_cpu_topology: bool,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900109 pub task_profiles: Vec<String>,
Jiyong Parke6fb1672023-06-26 16:45:55 +0900110 pub console_out_fd: Option<File>,
111 pub console_in_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000112 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +0900113 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000114 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900115 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900116 pub detect_hangup: bool,
Nikita Ioffe5776f082023-02-10 21:38:26 +0000117 pub gdb_port: Option<NonZeroU16>,
Inseob Kim7307a892023-09-14 13:37:58 +0900118 pub vfio_devices: Vec<VfioDevice>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119}
120
121/// A disk image to pass to crosvm for a VM.
122#[derive(Debug)]
123pub struct DiskFile {
124 pub image: File,
125 pub writable: bool,
126}
127
Inseob Kim7307a892023-09-14 13:37:58 +0900128#[derive(Clone, Debug)]
129pub struct VfioDevice {
130 pub sysfs_path: PathBuf,
Jaewan Kim35e818d2023-10-18 05:36:38 +0000131 pub dtbo_label: String,
Inseob Kim7307a892023-09-14 13:37:58 +0900132}
133
Andrew Walbran6b650662021-09-07 13:13:23 +0000134/// The lifecycle state which the payload in the VM has reported itself to be in.
135///
136/// Note that the order of enum variants is significant; only forward transitions are allowed by
137/// [`VmInstance::update_payload_state`].
138#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
139pub enum PayloadState {
140 Starting,
141 Started,
142 Ready,
143 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900144 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000145}
146
Andrew Walbranf8d94112021-09-07 11:45:36 +0000147/// The current state of the VM itself.
148#[derive(Debug)]
149pub enum VmState {
150 /// The VM has not yet tried to start.
151 NotStarted {
152 ///The configuration needed to start the VM, if it has not yet been started.
Inseob Kim7307a892023-09-14 13:37:58 +0900153 config: Box<CrosvmConfig>,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000154 },
155 /// The VM has been started.
156 Running {
157 /// The crosvm child process.
158 child: Arc<SharedChild>,
David Brazdilf18e1162022-12-18 18:27:23 +0000159 /// The thread waiting for crosvm to finish.
160 monitor_vm_exit_thread: Option<JoinHandle<()>>,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000161 },
162 /// The VM died or was killed.
163 Dead,
164 /// The VM failed to start.
165 Failed,
166}
167
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900168/// RSS values of VM and CrosVM process itself.
169#[derive(Copy, Clone, Debug, Default)]
170pub struct Rss {
171 pub vm: i64,
172 pub crosvm: i64,
173}
174
175/// Metrics regarding the VM.
176#[derive(Debug, Default)]
177pub struct VmMetric {
178 /// Recorded timestamp when the VM is started.
179 pub start_timestamp: Option<SystemTime>,
Pierre-Clément Tosi44aba642023-09-15 11:44:34 +0100180 /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is
181 /// running.
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900182 pub cpu_guest_time: Option<i64>,
183 /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
184 pub rss: Option<Rss>,
185}
186
Andrew Walbranf8d94112021-09-07 11:45:36 +0000187impl VmState {
188 /// Tries to start the VM, if it is in the `NotStarted` state.
189 ///
190 /// Returns an error if the VM is in the wrong state, or fails to start.
191 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
192 let state = mem::replace(self, VmState::Failed);
193 if let VmState::NotStarted { config } = state {
Inseob Kim7307a892023-09-14 13:37:58 +0900194 let config = *config;
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900195 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000196 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900197 let vfio_devices = config.vfio_devices.clone();
Andrew Walbranb27681f2022-02-23 15:11:52 +0000198
Andrew Walbranf8d94112021-09-07 11:45:36 +0000199 // If this fails and returns an error, `self` will be left in the `Failed` state.
Keir Fraser13a956a2022-07-14 14:20:46 +0000200 let child =
Keir Frasercdd4b112022-11-24 14:02:25 +0000201 Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000202
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900203 let instance_monitor_status = instance.clone();
204 let child_monitor_status = child.clone();
205 thread::spawn(move || {
206 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
207 });
208
Andrew Walbranf8d94112021-09-07 11:45:36 +0000209 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900210 let instance_clone = instance.clone();
David Brazdilf18e1162022-12-18 18:27:23 +0000211 let monitor_vm_exit_thread = Some(thread::spawn(move || {
Inseob Kim6ef80972023-07-20 17:23:36 +0900212 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read, vfio_devices);
David Brazdilf18e1162022-12-18 18:27:23 +0000213 }));
Andrew Walbranf8d94112021-09-07 11:45:36 +0000214
Jiyong Parka4eebde2022-07-12 18:01:12 +0900215 if detect_hangup {
216 let child_clone = child.clone();
217 thread::spawn(move || {
218 instance.monitor_payload_hangup(child_clone);
219 });
220 }
221
Andrew Walbranf8d94112021-09-07 11:45:36 +0000222 // If it started correctly, update the state.
David Brazdilf18e1162022-12-18 18:27:23 +0000223 *self = VmState::Running { child, monitor_vm_exit_thread };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000224 Ok(())
225 } else {
226 *self = state;
227 bail!("VM already started or failed")
228 }
229 }
230}
231
David Brazdil8cf8f482022-11-23 14:21:26 +0000232/// Internal struct that holds the handles to globally unique resources of a VM.
233#[derive(Debug)]
234pub struct VmContext {
235 #[allow(dead_code)] // Keeps the global context alive
236 global_context: Strong<dyn IGlobalVmContext>,
237 #[allow(dead_code)] // Keeps the server alive
238 vm_server: RpcServer,
239}
240
241impl VmContext {
242 /// Construct new VmContext.
243 pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
244 VmContext { global_context, vm_server }
245 }
246}
247
Andrew Walbranf8d94112021-09-07 11:45:36 +0000248/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000249#[derive(Debug)]
250pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000251 /// The current state of the VM.
252 pub vm_state: Mutex<VmState>,
David Brazdil8cf8f482022-11-23 14:21:26 +0000253 /// Global resources allocated for this VM.
254 #[allow(dead_code)] // Keeps the context alive
255 vm_context: VmContext,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000256 /// The CID assigned to the VM for vsock communication.
257 pub cid: Cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000258 /// Path to crosvm control socket
259 crosvm_control_socket_path: PathBuf,
Seungjae Yoo62085c02022-08-12 04:44:52 +0000260 /// The name of the VM.
261 pub name: String,
Andrew Walbranf8650422021-06-09 15:54:09 +0000262 /// Whether the VM is a protected VM.
263 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000264 /// Directory of temporary files used by the VM while it is running.
265 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000266 /// The UID of the process which requested the VM.
267 pub requester_uid: u32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000268 /// The PID of the process which requested the VM. Note that this process may no longer exist
269 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000270 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000271 /// Callbacks to clients of the VM.
272 pub callbacks: VirtualMachineCallbacks,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000273 /// VirtualMachineService binder object for the VM.
274 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900275 /// Recorded metrics of VM such as timestamp or cpu / memory usage.
276 pub vm_metric: Mutex<VmMetric>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000277 /// The latest lifecycle state which the payload reported itself to be in.
278 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900279 /// Represents the condition that payload_state was updated
280 payload_state_updated: Condvar,
Jiyong Park08eee7b2022-11-11 15:01:26 +0900281 /// The human readable name of requester_uid
282 requester_uid_name: String,
283}
284
285impl fmt::Display for VmInstance {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 let adj = if self.protected { "Protected" } else { "Non-protected" };
288 write!(
289 f,
290 "{} virtual machine \"{}\" (owner: {}, cid: {})",
291 adj, self.name, self.requester_uid_name, self.cid
292 )
293 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000294}
295
296impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000297 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
298 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000299 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000300 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000301 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000302 requester_debug_pid: i32,
David Brazdil8cf8f482022-11-23 14:21:26 +0000303 vm_context: VmContext,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000304 ) -> Result<VmInstance, Error> {
305 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000306 let cid = config.cid;
Seungjae Yoo62085c02022-08-12 04:44:52 +0000307 let name = config.name.clone();
Andrew Walbrand3a84182021-09-07 14:48:52 +0000308 let protected = config.protected;
Jiyong Park08eee7b2022-11-11 15:01:26 +0900309 let requester_uid_name = User::from_uid(Uid::from_raw(requester_uid))
310 .ok()
311 .flatten()
312 .map_or_else(|| format!("{}", requester_uid), |u| u.name);
313 let instance = VmInstance {
Inseob Kim7307a892023-09-14 13:37:58 +0900314 vm_state: Mutex::new(VmState::NotStarted { config: Box::new(config) }),
David Brazdil528e0472022-10-10 15:06:02 +0100315 vm_context,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000316 cid,
Keir Frasercdd4b112022-11-24 14:02:25 +0000317 crosvm_control_socket_path: temporary_directory.join("crosvm.sock"),
Seungjae Yoo62085c02022-08-12 04:44:52 +0000318 name,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000319 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000320 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000321 requester_uid,
Andrew Walbran02034492021-04-13 15:05:07 +0000322 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000323 callbacks: Default::default(),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000324 vm_service: Mutex::new(None),
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900325 vm_metric: Mutex::new(Default::default()),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000326 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900327 payload_state_updated: Condvar::new(),
Jiyong Park08eee7b2022-11-11 15:01:26 +0900328 requester_uid_name,
329 };
330 info!("{} created", &instance);
331 Ok(instance)
Andrew Walbrandae07162021-03-12 17:05:20 +0000332 }
333
Andrew Walbranf8d94112021-09-07 11:45:36 +0000334 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
335 /// the `VmInstance` is dropped.
336 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900337 let mut vm_metric = self.vm_metric.lock().unwrap();
338 vm_metric.start_timestamp = Some(SystemTime::now());
Jiyong Park08eee7b2022-11-11 15:01:26 +0900339 let ret = self.vm_state.lock().unwrap().start(self.clone());
340 if ret.is_ok() {
341 info!("{} started", &self);
342 }
343 ret.with_context(|| format!("{} failed to start", &self))
Andrew Walbranf8d94112021-09-07 11:45:36 +0000344 }
345
Jiyong Parka4eebde2022-07-12 18:01:12 +0900346 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
347 /// handles the event by updating the state, noityfing the event to clients by calling
348 /// callbacks, and removing temporary files for the VM.
Inseob Kim6ef80972023-07-20 17:23:36 +0900349 fn monitor_vm_exit(
350 &self,
351 child: Arc<SharedChild>,
352 mut failure_pipe_read: File,
Inseob Kim7307a892023-09-14 13:37:58 +0900353 vfio_devices: Vec<VfioDevice>,
Inseob Kim6ef80972023-07-20 17:23:36 +0900354 ) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000355 let result = child.wait();
356 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900357 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
Sebastian Ene23167d82022-10-07 14:09:53 +0000358 Ok(status) => {
359 info!("crosvm({}) exited with status {}", child.id(), status);
360 if let Some(exit_status_code) = status.code() {
361 if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
362 info!("detected vcpu stall on crosvm");
363 }
364 }
365 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000366 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000367
368 let mut vm_state = self.vm_state.lock().unwrap();
369 *vm_state = VmState::Dead;
370 // Ensure that the mutex is released before calling the callbacks.
371 drop(vm_state);
Jiyong Park08eee7b2022-11-11 15:01:26 +0900372 info!("{} exited", &self);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000373
Jiyong Parka4eebde2022-07-12 18:01:12 +0900374 // Read the pipe to see if any failure reason is written
375 let mut failure_reason = String::new();
376 match failure_pipe_read.read_to_string(&mut failure_reason) {
377 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
378 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
379 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900380 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000381
Jiyong Parka4eebde2022-07-12 18:01:12 +0900382 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
383 // detected on the VM side (otherwise, it isn't a hangup), but in the
384 // monitor_payload_hangup function below which updates the payload state to Hangup.
385 let failure_reason =
386 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
387 Cow::from("HANGUP")
388 } else {
389 Cow::from(failure_reason)
390 };
391
Jiyong Parke558ab12022-07-07 20:18:55 +0900392 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000393
394 let death_reason = death_reason(&result, &failure_reason);
Seungjae Yoo93430e82022-12-05 16:37:42 +0900395 let exit_signal = exit_signal(&result);
396
Seungjae Yoob4c07ba2022-08-12 04:44:52 +0000397 self.callbacks.callback_on_died(self.cid, death_reason);
Seungjae Yoo2e7beea2022-08-24 16:09:12 +0900398
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900399 let vm_metric = self.vm_metric.lock().unwrap();
Seungjae Yoob2db3d22023-04-06 18:05:43 +0900400 write_vm_exited_stats_sync(
Seungjae Yoo93430e82022-12-05 16:37:42 +0900401 self.requester_uid as i32,
402 &self.name,
403 death_reason,
404 exit_signal,
Chris Wailes75269622022-12-05 23:01:44 -0800405 &vm_metric,
Seungjae Yoo93430e82022-12-05 16:37:42 +0900406 );
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000407
David Brazdil4b4c5102022-12-19 22:56:20 +0000408 // Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
409 remove_temporary_files(&self.temporary_directory).unwrap_or_else(|e| {
410 error!("Error removing temporary files from {:?}: {}", self.temporary_directory, e);
411 });
Inseob Kim6ef80972023-07-20 17:23:36 +0900412
413 // TODO(b/278008182): clean up assigned devices.
414 for device in vfio_devices.iter() {
415 info!("NOT RELEASING {device:?}");
416 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000417 }
418
Jiyong Parka4eebde2022-07-12 18:01:12 +0900419 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
420 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
421 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
422 debug!("Starting to monitor hangup for Microdroid({})", child.id());
423 let (_, result) = self
424 .payload_state_updated
425 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
426 *s < PayloadState::Started
427 })
428 .unwrap();
429 let child_still_running = child.try_wait().ok() == Some(None);
430 if result.timed_out() && child_still_running {
431 error!(
432 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
433 child.id(),
434 BOOT_HANGUP_TIMEOUT.as_secs()
435 );
436 self.update_payload_state(PayloadState::Hangup).unwrap();
437 if let Err(e) = self.kill() {
438 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
439 }
440 }
441 }
442
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900443 fn monitor_vm_status(&self, child: Arc<SharedChild>) {
444 let pid = child.id();
445
446 loop {
447 {
448 // Check VM state
449 let vm_state = &*self.vm_state.lock().unwrap();
450 if let VmState::Dead = vm_state {
451 break;
452 }
453
454 let mut vm_metric = self.vm_metric.lock().unwrap();
455
456 // Get CPU Information
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900457 if let Ok(guest_time) = get_guest_time(pid) {
458 vm_metric.cpu_guest_time = Some(guest_time);
459 } else {
460 error!("Failed to parse /proc/[pid]/stat");
461 }
462
463 // Get Memory Information
464 if let Ok(rss) = get_rss(pid) {
465 vm_metric.rss = match &vm_metric.rss {
466 Some(x) => Some(Rss::extract_max(x, &rss)),
467 None => Some(rss),
468 }
469 } else {
470 error!("Failed to parse /proc/[pid]/smaps");
471 }
472 }
473
474 thread::sleep(Duration::from_secs(1));
475 }
476 }
477
Andrew Walbran6b650662021-09-07 13:13:23 +0000478 /// Returns the last reported state of the VM payload.
479 pub fn payload_state(&self) -> PayloadState {
480 *self.payload_state.lock().unwrap()
481 }
482
483 /// Updates the payload state to the given value, if it is a valid state transition.
484 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
485 let mut state_locked = self.payload_state.lock().unwrap();
486 // Only allow forward transitions, e.g. from starting to started or finished, not back in
487 // the other direction.
488 if new_state > *state_locked {
489 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900490 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000491 Ok(())
492 } else {
493 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
494 }
495 }
496
Andrew Walbranf8d94112021-09-07 11:45:36 +0000497 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900498 pub fn kill(&self) -> Result<(), Error> {
David Brazdilf18e1162022-12-18 18:27:23 +0000499 let monitor_vm_exit_thread = {
500 let vm_state = &mut *self.vm_state.lock().unwrap();
501 if let VmState::Running { child, monitor_vm_exit_thread } = vm_state {
502 let id = child.id();
503 debug!("Killing crosvm({})", id);
504 // TODO: Talk to crosvm to shutdown cleanly.
505 child.kill().with_context(|| format!("Error killing crosvm({id}) instance"))?;
506 monitor_vm_exit_thread.take()
Inseob Kima446f802022-07-11 19:46:37 +0900507 } else {
David Brazdilf18e1162022-12-18 18:27:23 +0000508 bail!("VM is not running")
Andrew Walbranf8d94112021-09-07 11:45:36 +0000509 }
David Brazdilf18e1162022-12-18 18:27:23 +0000510 };
511
512 // Wait for monitor_vm_exit() to finish. Must release vm_state lock
513 // first, as monitor_vm_exit() takes it as well.
514 monitor_vm_exit_thread.map(JoinHandle::join);
515
David Brazdil5af55832023-03-08 13:08:56 +0000516 // Now that the VM has been killed, shut down the VirtualMachineService
517 // server to eagerly free up the server threads.
518 self.vm_context.vm_server.shutdown()?;
519
David Brazdilf18e1162022-12-18 18:27:23 +0000520 Ok(())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000521 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900522
Keir Frasercdd4b112022-11-24 14:02:25 +0000523 /// Responds to memory-trimming notifications by inflating the virtio
524 /// balloon to reclaim guest memory.
525 pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> {
526 let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {});
527 match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) {
528 Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => {
529 if let Some(total_memory) = stats.total_memory {
530 // Reclaim up to 50% of total memory assuming worst case
531 // most memory is anonymous and must be swapped to zram
532 // with an approximate 2:1 compression ratio.
533 let pct = match level {
534 MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50,
535 MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30,
536 MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10,
537 _ => bail!("Invalid memory trim level {:?}", level),
538 };
Devin Moore30be4482023-08-21 22:44:26 +0000539 let command = BalloonControlCommand::Adjust {
540 num_bytes: total_memory * pct / 100,
541 wait_for_success: false,
542 };
Keir Frasercdd4b112022-11-24 14:02:25 +0000543 if let Err(e) = vm_control::client::handle_request(
544 &VmRequest::BalloonCommand(command),
545 &self.crosvm_control_socket_path,
546 ) {
547 bail!("Error sending balloon adjustment: {:?}", e);
548 }
549 }
550 }
551 Ok(VmResponse::Err(e)) => {
Alice Wangeff58392023-07-04 13:32:09 +0000552 // ENOTSUP is returned when the balloon protocol is not initialized. This
Keir Frasercdd4b112022-11-24 14:02:25 +0000553 // can occur for numerous reasons: Guest is still booting, guest doesn't
554 // support ballooning, host doesn't support ballooning. We don't log or
555 // raise an error in this case: trim is just a hint and we can ignore it.
556 if e.errno() != libc::ENOTSUP {
557 bail!("Errno return when requesting balloon stats: {}", e.errno())
558 }
559 }
560 e => bail!("Error requesting balloon stats: {:?}", e),
561 }
562 Ok(())
563 }
564
Alan Stokes3e98d292022-12-14 15:18:22 +0000565 /// Checks if ramdump has been created. If so, send it to tombstoned.
Jiyong Parke558ab12022-07-07 20:18:55 +0900566 fn handle_ramdump(&self) -> Result<(), Error> {
567 let ramdump_path = self.temporary_directory.join("ramdump");
Jiyong Park933d2b22023-02-28 11:41:19 +0900568 if !ramdump_path.as_path().try_exists()? {
569 return Ok(());
570 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900571 if std::fs::metadata(&ramdump_path)?.len() > 0 {
Jiyong Park1612b902022-08-22 14:47:39 +0900572 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900573 }
574 Ok(())
575 }
Jiyong Park1612b902022-08-22 14:47:39 +0900576
577 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
578 let mut input = File::open(ramdump_path)
Alan Stokes3e98d292022-12-14 15:18:22 +0000579 .context(format!("Failed to open ramdump {:?} for reading", ramdump_path))?;
Jiyong Park1612b902022-08-22 14:47:39 +0900580
581 let pid = std::process::id() as i32;
582 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
583 .context("Failed to connect to tombstoned")?;
584 let mut output = conn
585 .text_output
586 .as_ref()
587 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
588
589 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
590 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
591
592 conn.notify_completion()?;
593 Ok(())
594 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000595}
596
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900597impl Rss {
598 fn extract_max(x: &Rss, y: &Rss) -> Rss {
599 Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
600 }
601}
602
603// Get guest time from /proc/[crosvm pid]/stat
604fn get_guest_time(pid: u32) -> Result<i64> {
605 let file = read_to_string(format!("/proc/{}/stat", pid))?;
606 let data_list: Vec<_> = file.split_whitespace().collect();
607
608 // Information about guest_time is at 43th place of the file split with the whitespace.
609 // Example of /proc/[pid]/stat :
610 // 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
611 // 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
612 if data_list.len() < 43 {
613 bail!("Failed to parse command result for getting guest time : {}", file);
614 }
615
616 let guest_time_ticks = data_list[42].parse::<i64>()?;
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100617 // SAFETY: It just returns an integer about CPU tick information.
Charisee96113f32023-01-26 09:00:42 +0000618 let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) };
Seungjae Yoo6d265d92022-11-15 10:51:33 +0900619 Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
620}
621
622// Get rss from /proc/[crosvm pid]/smaps
623fn get_rss(pid: u32) -> Result<Rss> {
624 let file = read_to_string(format!("/proc/{}/smaps", pid))?;
625 let lines: Vec<_> = file.split('\n').collect();
626
627 let mut rss_vm_total = 0i64;
628 let mut rss_crosvm_total = 0i64;
629 let mut is_vm = false;
630 for line in lines {
631 if line.contains("crosvm_guest") {
632 is_vm = true;
633 } else if line.contains("Rss:") {
634 let data_list: Vec<_> = line.split_whitespace().collect();
635 if data_list.len() < 2 {
636 bail!("Failed to parse command result for getting rss :\n{}", line);
637 }
638 let rss = data_list[1].parse::<i64>()?;
639
640 if is_vm {
641 rss_vm_total += rss;
642 is_vm = false;
643 }
644 rss_crosvm_total += rss;
645 }
646 }
647
648 Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
649}
650
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100651fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
Pierre-Clément Tosic0611e72023-09-15 11:41:07 +0100652 if let Some((reason, info)) = failure_reason.split_once('|') {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100653 // Separator indicates extra context information is present after the failure name.
Pierre-Clément Tosic0611e72023-09-15 11:41:07 +0100654 error!("Failure info: {info}");
655 failure_reason = reason;
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100656 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000657 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000658 match failure_reason {
659 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
660 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
661 }
662 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
663 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
664 }
Inseob Kim272f5722022-06-13 17:14:51 +0900665 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
666 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
667 }
668 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
669 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
670 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
671 }
672 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
673 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
674 }
675 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
676 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
677 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900678 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000679 _ => {}
680 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000681 match status.code() {
682 None => DeathReason::KILLED,
683 Some(0) => DeathReason::SHUTDOWN,
Alan Stokes7c459e82022-12-06 12:21:49 +0000684 Some(CROSVM_START_ERROR_STATUS) => DeathReason::START_FAILED,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000685 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000686 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Sebastian Ene23167d82022-10-07 14:09:53 +0000687 Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000688 Some(_) => DeathReason::UNKNOWN,
689 }
690 } else {
691 DeathReason::INFRASTRUCTURE_ERROR
692 }
693}
694
Seungjae Yoo93430e82022-12-05 16:37:42 +0900695fn exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32> {
696 match result {
697 Ok(status) => status.signal(),
698 Err(_) => None,
699 }
700}
701
Inseob Kim6ef80972023-07-20 17:23:36 +0900702const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
703const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
704
Inseob Kim7307a892023-09-14 13:37:58 +0900705fn vfio_argument_for_platform_device(device: &VfioDevice) -> Result<String, Error> {
Inseob Kim6ef80972023-07-20 17:23:36 +0900706 // Check platform device exists
Inseob Kim7307a892023-09-14 13:37:58 +0900707 let path = device.sysfs_path.canonicalize()?;
Inseob Kim6ef80972023-07-20 17:23:36 +0900708 if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
709 bail!("{path:?} is not a platform device");
710 }
711
712 // Check platform device is bound to VFIO driver
713 let dev_driver_path = path.join("driver").canonicalize()?;
714 if dev_driver_path != Path::new(VFIO_PLATFORM_DRIVER_PATH) {
715 bail!("{path:?} is not bound to VFIO-platform driver");
716 }
717
718 if let Some(p) = path.to_str() {
Jaewan Kim35e818d2023-10-18 05:36:38 +0000719 Ok(format!("--vfio={p},iommu=viommu,dt-symbol={0}", device.dtbo_label))
Inseob Kim6ef80972023-07-20 17:23:36 +0900720 } else {
721 bail!("invalid path {path:?}");
722 }
723}
724
725fn append_platform_devices(command: &mut Command, config: &CrosvmConfig) -> Result<(), Error> {
726 for device in &config.vfio_devices {
727 command.arg(vfio_argument_for_platform_device(device)?);
728 }
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900729 // TODO(b/291192693): add dtbo to command line when assigned device is not empty.
Inseob Kim6ef80972023-07-20 17:23:36 +0900730 Ok(())
731}
732
Andrew Walbrand3a84182021-09-07 14:48:52 +0000733/// Starts an instance of `crosvm` to manage a new VM.
Keir Fraser13a956a2022-07-14 14:20:46 +0000734fn run_vm(
735 config: CrosvmConfig,
Keir Frasercdd4b112022-11-24 14:02:25 +0000736 crosvm_control_socket_path: &Path,
Keir Fraser13a956a2022-07-14 14:20:46 +0000737 failure_pipe_write: File,
738) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000739 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000740
741 let mut command = Command::new(CROSVM_PATH);
742 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000743 command
744 .arg("--extended-status")
Jiyong Park6c60fea2022-10-24 16:10:01 +0900745 // Configure the logger for the crosvm process to silence logs from the disk crate which
746 // don't provide much information to us (but do spamming us).
747 .arg("--log-level")
Frederick Mayle138f53c2023-01-24 18:55:26 -0800748 .arg("info,disk=warn")
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000749 .arg("run")
750 .arg("--disable-sandbox")
751 .arg("--cid")
752 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000753
Keir Fraserf25cb922022-11-23 14:26:00 +0000754 if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
755 command.arg("--balloon-page-reporting");
756 } else {
757 command.arg("--no-balloon");
758 }
759
Andrew Walbranf8650422021-06-09 15:54:09 +0000760 if config.protected {
Jaewan Kim46422812022-11-25 10:59:39 +0900761 match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? {
762 Some(pvmfw_path) if !pvmfw_path.is_empty() => {
763 command.arg("--protected-vm-with-firmware").arg(pvmfw_path)
764 }
765 _ => command.arg("--protected-vm"),
766 };
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000767
768 // 3 virtio-console devices + vsock = 4.
769 let virtio_pci_device_count = 4 + config.disks.len();
770 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
771 // enough.
Jiyong Park3115cdb2023-02-24 18:04:44 +0900772 let swiotlb_size_mib = 2 * virtio_pci_device_count as u32;
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000773 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Frederick Mayle58baa302023-02-14 19:06:37 -0800774
775 // Workaround to keep crash_dump from trying to read protected guest memory.
776 // Context in b/238324526.
777 command.arg("--unmap-guest-memory-on-fork");
Jiyong Park3115cdb2023-02-24 18:04:44 +0900778
Jiyong Parked180932023-02-24 19:55:41 +0900779 if config.ramdump.is_some() {
Jaewan Kim3124ef02023-03-23 19:25:20 +0900780 // Protected VM needs to reserve memory for ramdump here. Note that we reserve more
Jiyong Parked180932023-02-24 19:55:41 +0900781 // memory for the restricted dma pool.
782 let ramdump_reserve = RAMDUMP_RESERVED_MIB + swiotlb_size_mib;
783 command.arg("--params").arg(format!("crashkernel={ramdump_reserve}M"));
784 }
Jaewan Kimd4dae652023-03-28 13:45:43 +0900785 } else if config.ramdump.is_some() {
786 command.arg("--params").arg(format!("crashkernel={RAMDUMP_RESERVED_MIB}M"));
787 }
Jaewan Kim61f86142023-03-28 15:12:52 +0900788 if config.debug_config.debug_level == DebugLevel::NONE
789 && config.debug_config.should_prepare_console_output()
790 {
Jaewan Kimd4dae652023-03-28 13:45:43 +0900791 // bootconfig.normal will be used, but we need log.
792 command.arg("--params").arg("printk.devkmsg=on");
793 command.arg("--params").arg("console=hvc0");
Andrew Walbranf8650422021-06-09 15:54:09 +0000794 }
795
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000796 if let Some(memory_mib) = config.memory_mib {
797 command.arg("--mem").arg(memory_mib.to_string());
798 }
799
Jiyong Park032615f2022-01-10 13:55:34 +0900800 if let Some(cpus) = config.cpus {
801 command.arg("--cpus").arg(cpus.to_string());
802 }
803
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000804 if config.host_cpu_topology {
David Brazdil25e8c052023-02-17 12:53:01 +0000805 // TODO(b/266664564): replace with --host-cpu-topology once available
806 if let Some(cpus) = get_num_cpus() {
807 command.arg("--cpus").arg(cpus.to_string());
808 } else {
809 bail!("Could not determine the number of CPUs in the system");
810 }
David Brazdil7d1e5ec2023-02-06 17:56:29 +0000811 }
812
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900813 if !config.task_profiles.is_empty() {
814 command.arg("--task-profiles").arg(config.task_profiles.join(","));
815 }
816
Nikita Ioffe5776f082023-02-10 21:38:26 +0000817 if let Some(gdb_port) = config.gdb_port {
818 command.arg("--gdb").arg(gdb_port.to_string());
819 }
820
Jiyong Parkfa91d702021-10-18 23:51:39 +0900821 // Keep track of what file descriptors should be mapped to the crosvm process.
822 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
823
Jiyong Park747d6362021-10-19 17:12:52 +0900824 // Setup the serial devices.
825 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000826 // 2. uart device: used to report the reason for the VM failing.
827 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900828 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000829 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900830 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900831 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
832 // written there is discarded.
Jiyong Parke6fb1672023-06-26 16:45:55 +0900833 let console_out_arg = format_serial_out_arg(&mut preserved_fds, &config.console_out_fd);
834 let console_in_arg = config
835 .console_in_fd
836 .as_ref()
837 .map(|fd| format!(",input={}", add_preserved_fd(&mut preserved_fds, fd)))
838 .unwrap_or_default();
839 let log_arg = format_serial_out_arg(&mut preserved_fds, &config.log_fd);
Andrew Walbranb27681f2022-02-23 15:11:52 +0000840 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke6fb1672023-06-26 16:45:55 +0900841 let ramdump_arg = format_serial_out_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900842
Jiyong Park747d6362021-10-19 17:12:52 +0900843 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
844 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
845 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
846 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900847 // /dev/ttyS0
Jiyong Park34cf4342023-07-03 15:03:15 +0900848 command.arg(format!("--serial={},hardware=serial,num=1", &console_out_arg));
Andrew Walbranb27681f2022-02-23 15:11:52 +0000849 // /dev/ttyS1
850 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900851 // /dev/hvc0
Jiyong Parke6fb1672023-06-26 16:45:55 +0900852 command.arg(format!(
853 "--serial={}{},hardware=virtio-console,num=1",
854 &console_out_arg, &console_in_arg
855 ));
Jiyong Park4afe2012022-07-08 05:38:49 +0900856 // /dev/hvc1
857 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900858 // /dev/hvc2
859 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000860
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000861 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000862 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000863 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000864
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000865 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000866 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000867 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000868
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000869 if let Some(params) = &config.params {
870 command.arg("--params").arg(params);
871 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000872
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000873 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000874 command
875 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000876 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000877 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000878
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000879 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000880 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000881 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000882
Keir Frasercdd4b112022-11-24 14:02:25 +0000883 let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path)
884 .context("failed to create control server")?;
Elie Kheirallah2d12ff32023-03-20 18:12:07 +0000885 command
886 .arg("--socket")
887 .arg(add_preserved_fd(&mut preserved_fds, &control_server_socket.as_raw_descriptor()));
Keir Fraser13a956a2022-07-14 14:20:46 +0000888
Inseob Kim6ef80972023-07-20 17:23:36 +0900889 append_platform_devices(&mut command, &config)?;
890
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000891 debug!("Preserving FDs {:?}", preserved_fds);
892 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000893
Jiyong Park2d736562022-10-24 22:40:12 +0900894 print_crosvm_args(&command);
895
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000896 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900897 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000898 Ok(result)
899}
900
901/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000902fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000903 if config.bootloader.is_none() && config.kernel.is_none() {
904 bail!("VM must have either a bootloader or a kernel image.");
905 }
906 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
907 bail!("Can't have both bootloader and kernel/initrd image.");
908 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900909 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
910 if !config.platform_version.matches(&version) {
911 bail!(
912 "Incompatible platform version. The config is compatible with platform version(s) \
913 {}, but the actual platform version is {}",
914 config.platform_version,
915 version
916 );
917 }
918
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000919 Ok(())
920}
921
Jiyong Park2d736562022-10-24 22:40:12 +0900922/// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
923/// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
924/// unmodified.
925fn print_crosvm_args(command: &Command) {
926 let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
927 info!(
928 "Running crosvm with args: {:?}",
929 command
930 .get_args()
931 .map(|s| s.to_string_lossy())
932 .map(|s| {
933 re.replace_all(&s, |caps: &Captures| {
934 let path = &caps[0];
935 if let Ok(realpath) = std::fs::canonicalize(path) {
936 format!("{} ({})", path, realpath.to_string_lossy())
937 } else {
938 path.to_owned()
939 }
940 })
941 .into_owned()
942 })
943 .collect::<Vec<_>>()
944 );
945}
946
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000947/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
948/// "/proc/self/fd/N" where N is the file descriptor.
Keir Fraser13a956a2022-07-14 14:20:46 +0000949fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000950 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000951 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000952 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000953}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000954
955/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
956/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
Jiyong Parke6fb1672023-06-26 16:45:55 +0900957fn format_serial_out_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000958 if let Some(file) = file {
959 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
960 } else {
961 "type=sink".to_string()
962 }
963}
964
965/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
966fn create_pipe() -> Result<(File, File), Error> {
967 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100968 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000969 let read_fd = unsafe { File::from_raw_fd(raw_read) };
Andrew Walbranb58d1b42023-07-07 13:54:49 +0100970 // SAFETY: We are the sole owner of this FD as we just created it, and it is valid and open.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000971 let write_fd = unsafe { File::from_raw_fd(raw_write) };
972 Ok((read_fd, write_fd))
973}