Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 1 | // 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 Brazdil | 41d1a87 | 2022-10-05 14:44:19 +0100 | [diff] [blame] | 17 | use crate::aidl::{Cid, VirtualMachineCallbacks}; |
Seungjae Yoo | b4c07ba | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 18 | use crate::atom::write_vm_exited_stats; |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 19 | use anyhow::{anyhow, bail, Context, Error, Result}; |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 20 | use command_fds::CommandFdExt; |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 21 | use lazy_static::lazy_static; |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 22 | use libc::{sysconf, _SC_CLK_TCK}; |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 23 | use log::{debug, error, info}; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 24 | use semver::{Version, VersionReq}; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 25 | use nix::{fcntl::OFlag, unistd::pipe2}; |
Jiyong Park | 2d73656 | 2022-10-24 22:40:12 +0900 | [diff] [blame] | 26 | use regex::{Captures, Regex}; |
Keir Fraser | f25cb92 | 2022-11-23 14:26:00 +0000 | [diff] [blame] | 27 | use rustutils::system_properties; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 28 | use shared_child::SharedChild; |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 29 | use std::borrow::Cow; |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 30 | use std::cmp::max; |
| 31 | use std::fs::{read_to_string, remove_dir_all, File}; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 32 | use std::io::{self, Read}; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 33 | use std::mem; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 34 | use std::num::NonZeroU32; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 35 | use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; |
Jiyong Park | 1612b90 | 2022-08-22 14:47:39 +0900 | [diff] [blame] | 36 | use std::path::{Path, PathBuf}; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 37 | use std::process::{Command, ExitStatus}; |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 38 | use std::sync::{Arc, Condvar, Mutex}; |
Seungjae Yoo | 2e7beea | 2022-08-24 16:09:12 +0900 | [diff] [blame] | 39 | use std::time::{Duration, SystemTime}; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 40 | use std::thread; |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 41 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
| 42 | DeathReason::DeathReason, |
| 43 | MemoryTrimLevel::MemoryTrimLevel, |
| 44 | }; |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 45 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext; |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 46 | use binder::Strong; |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 47 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService; |
Jiyong Park | 1612b90 | 2022-08-22 14:47:39 +0900 | [diff] [blame] | 48 | use tombstoned_client::{TombstonedConnection, DebuggerdDumpType}; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 49 | use rpcbinder::RpcServer; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 50 | |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 51 | /// external/crosvm |
| 52 | use base::UnixSeqpacketListener; |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 53 | use vm_control::{BalloonControlCommand, VmRequest, VmResponse}; |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 54 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 55 | const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm"; |
| 56 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 57 | /// 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. |
| 61 | const CROSVM_PLATFORM_VERSION: &str = "1.0.0"; |
| 62 | |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 63 | /// The exit status which crosvm returns when it has an error starting a VM. |
| 64 | const CROSVM_ERROR_STATUS: i32 = 1; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 65 | /// The exit status which crosvm returns when a VM requests a reboot. |
| 66 | const CROSVM_REBOOT_STATUS: i32 = 32; |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 67 | /// The exit status which crosvm returns when it crashes due to an error. |
| 68 | const CROSVM_CRASH_STATUS: i32 = 33; |
Sebastian Ene | 23167d8 | 2022-10-07 14:09:53 +0000 | [diff] [blame] | 69 | /// The exit status which crosvm returns when vcpu is stalled. |
| 70 | const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 71 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 72 | const MILLIS_PER_SEC: i64 = 1000; |
| 73 | |
Jaewan Kim | 4642281 | 2022-11-25 10:59:39 +0900 | [diff] [blame] | 74 | const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path"; |
| 75 | |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 76 | lazy_static! { |
| 77 | /// If the VM doesn't move to the Started state within this amount time, a hang-up error is |
| 78 | /// triggered. |
Alan Stokes | c3f2ac2 | 2022-06-23 12:19:46 +0100 | [diff] [blame] | 79 | static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() { |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 80 | // Nested virtualization is slow, so we need a longer timeout. |
| 81 | Duration::from_secs(100) |
| 82 | } else { |
| 83 | Duration::from_secs(10) |
| 84 | }; |
| 85 | } |
| 86 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 87 | /// Configuration for a VM to run with crosvm. |
| 88 | #[derive(Debug)] |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 89 | pub struct CrosvmConfig { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 90 | pub cid: Cid, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 91 | pub name: String, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 92 | pub bootloader: Option<File>, |
| 93 | pub kernel: Option<File>, |
| 94 | pub initrd: Option<File>, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 95 | pub disks: Vec<DiskFile>, |
| 96 | pub params: Option<String>, |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 97 | pub protected: bool, |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 98 | pub memory_mib: Option<NonZeroU32>, |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 99 | pub cpus: Option<NonZeroU32>, |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 100 | pub task_profiles: Vec<String>, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 101 | pub console_fd: Option<File>, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 102 | pub log_fd: Option<File>, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 103 | pub ramdump: Option<File>, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 104 | pub indirect_files: Vec<File>, |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 105 | pub platform_version: VersionReq, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 106 | pub detect_hangup: bool, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 107 | } |
| 108 | |
| 109 | /// A disk image to pass to crosvm for a VM. |
| 110 | #[derive(Debug)] |
| 111 | pub struct DiskFile { |
| 112 | pub image: File, |
| 113 | pub writable: bool, |
| 114 | } |
| 115 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 116 | /// The lifecycle state which the payload in the VM has reported itself to be in. |
| 117 | /// |
| 118 | /// Note that the order of enum variants is significant; only forward transitions are allowed by |
| 119 | /// [`VmInstance::update_payload_state`]. |
| 120 | #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
| 121 | pub enum PayloadState { |
| 122 | Starting, |
| 123 | Started, |
| 124 | Ready, |
| 125 | Finished, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 126 | Hangup, // Hasn't reached to Ready before timeout expires |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 127 | } |
| 128 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 129 | /// The current state of the VM itself. |
| 130 | #[derive(Debug)] |
| 131 | pub enum VmState { |
| 132 | /// The VM has not yet tried to start. |
| 133 | NotStarted { |
| 134 | ///The configuration needed to start the VM, if it has not yet been started. |
| 135 | config: CrosvmConfig, |
| 136 | }, |
| 137 | /// The VM has been started. |
| 138 | Running { |
| 139 | /// The crosvm child process. |
| 140 | child: Arc<SharedChild>, |
| 141 | }, |
| 142 | /// The VM died or was killed. |
| 143 | Dead, |
| 144 | /// The VM failed to start. |
| 145 | Failed, |
| 146 | } |
| 147 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 148 | /// RSS values of VM and CrosVM process itself. |
| 149 | #[derive(Copy, Clone, Debug, Default)] |
| 150 | pub struct Rss { |
| 151 | pub vm: i64, |
| 152 | pub crosvm: i64, |
| 153 | } |
| 154 | |
| 155 | /// Metrics regarding the VM. |
| 156 | #[derive(Debug, Default)] |
| 157 | pub struct VmMetric { |
| 158 | /// Recorded timestamp when the VM is started. |
| 159 | pub start_timestamp: Option<SystemTime>, |
| 160 | /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running. |
| 161 | pub cpu_guest_time: Option<i64>, |
| 162 | /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running. |
| 163 | pub rss: Option<Rss>, |
| 164 | } |
| 165 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 166 | impl VmState { |
| 167 | /// Tries to start the VM, if it is in the `NotStarted` state. |
| 168 | /// |
| 169 | /// Returns an error if the VM is in the wrong state, or fails to start. |
| 170 | fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> { |
| 171 | let state = mem::replace(self, VmState::Failed); |
| 172 | if let VmState::NotStarted { config } = state { |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 173 | let detect_hangup = config.detect_hangup; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 174 | let (failure_pipe_read, failure_pipe_write) = create_pipe()?; |
| 175 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 176 | // If this fails and returns an error, `self` will be left in the `Failed` state. |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 177 | let child = |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 178 | Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 179 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 180 | let instance_monitor_status = instance.clone(); |
| 181 | let child_monitor_status = child.clone(); |
| 182 | thread::spawn(move || { |
| 183 | instance_monitor_status.clone().monitor_vm_status(child_monitor_status); |
| 184 | }); |
| 185 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 186 | let child_clone = child.clone(); |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 187 | let instance_clone = instance.clone(); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 188 | thread::spawn(move || { |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 189 | instance_clone.monitor_vm_exit(child_clone, failure_pipe_read); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 190 | }); |
| 191 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 192 | if detect_hangup { |
| 193 | let child_clone = child.clone(); |
| 194 | thread::spawn(move || { |
| 195 | instance.monitor_payload_hangup(child_clone); |
| 196 | }); |
| 197 | } |
| 198 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 199 | // If it started correctly, update the state. |
| 200 | *self = VmState::Running { child }; |
| 201 | Ok(()) |
| 202 | } else { |
| 203 | *self = state; |
| 204 | bail!("VM already started or failed") |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 209 | /// Internal struct that holds the handles to globally unique resources of a VM. |
| 210 | #[derive(Debug)] |
| 211 | pub struct VmContext { |
| 212 | #[allow(dead_code)] // Keeps the global context alive |
| 213 | global_context: Strong<dyn IGlobalVmContext>, |
| 214 | #[allow(dead_code)] // Keeps the server alive |
| 215 | vm_server: RpcServer, |
| 216 | } |
| 217 | |
| 218 | impl VmContext { |
| 219 | /// Construct new VmContext. |
| 220 | pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext { |
| 221 | VmContext { global_context, vm_server } |
| 222 | } |
| 223 | } |
| 224 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 225 | /// Information about a particular instance of a VM which may be running. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 226 | #[derive(Debug)] |
| 227 | pub struct VmInstance { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 228 | /// The current state of the VM. |
| 229 | pub vm_state: Mutex<VmState>, |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 230 | /// Global resources allocated for this VM. |
| 231 | #[allow(dead_code)] // Keeps the context alive |
| 232 | vm_context: VmContext, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 233 | /// The CID assigned to the VM for vsock communication. |
| 234 | pub cid: Cid, |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 235 | /// Path to crosvm control socket |
| 236 | crosvm_control_socket_path: PathBuf, |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 237 | /// The name of the VM. |
| 238 | pub name: String, |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 239 | /// Whether the VM is a protected VM. |
| 240 | pub protected: bool, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 241 | /// Directory of temporary files used by the VM while it is running. |
| 242 | pub temporary_directory: PathBuf, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 243 | /// The UID of the process which requested the VM. |
| 244 | pub requester_uid: u32, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 245 | /// The PID of the process which requested the VM. Note that this process may no longer exist |
| 246 | /// and the PID may have been reused for a different process, so this should not be trusted. |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 247 | pub requester_debug_pid: i32, |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 248 | /// Callbacks to clients of the VM. |
| 249 | pub callbacks: VirtualMachineCallbacks, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 250 | /// VirtualMachineService binder object for the VM. |
| 251 | pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>, |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 252 | /// Recorded metrics of VM such as timestamp or cpu / memory usage. |
| 253 | pub vm_metric: Mutex<VmMetric>, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 254 | /// The latest lifecycle state which the payload reported itself to be in. |
| 255 | payload_state: Mutex<PayloadState>, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 256 | /// Represents the condition that payload_state was updated |
| 257 | payload_state_updated: Condvar, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 258 | } |
| 259 | |
| 260 | impl VmInstance { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 261 | /// Validates the given config and creates a new `VmInstance` but doesn't start running it. |
| 262 | pub fn new( |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 263 | config: CrosvmConfig, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 264 | temporary_directory: PathBuf, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 265 | requester_uid: u32, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 266 | requester_debug_pid: i32, |
David Brazdil | 8cf8f48 | 2022-11-23 14:21:26 +0000 | [diff] [blame] | 267 | vm_context: VmContext, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 268 | ) -> Result<VmInstance, Error> { |
| 269 | validate_config(&config)?; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 270 | let cid = config.cid; |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 271 | let name = config.name.clone(); |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 272 | let protected = config.protected; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 273 | Ok(VmInstance { |
| 274 | vm_state: Mutex::new(VmState::NotStarted { config }), |
David Brazdil | 528e047 | 2022-10-10 15:06:02 +0100 | [diff] [blame] | 275 | vm_context, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 276 | cid, |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 277 | crosvm_control_socket_path: temporary_directory.join("crosvm.sock"), |
Seungjae Yoo | 62085c0 | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 278 | name, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 279 | protected, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 280 | temporary_directory, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 281 | requester_uid, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 282 | requester_debug_pid, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 283 | callbacks: Default::default(), |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 284 | vm_service: Mutex::new(None), |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 285 | vm_metric: Mutex::new(Default::default()), |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 286 | payload_state: Mutex::new(PayloadState::Starting), |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 287 | payload_state_updated: Condvar::new(), |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 288 | }) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 289 | } |
| 290 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 291 | /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when |
| 292 | /// the `VmInstance` is dropped. |
| 293 | pub fn start(self: &Arc<Self>) -> Result<(), Error> { |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 294 | let mut vm_metric = self.vm_metric.lock().unwrap(); |
| 295 | vm_metric.start_timestamp = Some(SystemTime::now()); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 296 | self.vm_state.lock().unwrap().start(self.clone()) |
| 297 | } |
| 298 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 299 | /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens, |
| 300 | /// handles the event by updating the state, noityfing the event to clients by calling |
| 301 | /// callbacks, and removing temporary files for the VM. |
| 302 | fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 303 | let result = child.wait(); |
| 304 | match &result { |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 305 | Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e), |
Sebastian Ene | 23167d8 | 2022-10-07 14:09:53 +0000 | [diff] [blame] | 306 | Ok(status) => { |
| 307 | info!("crosvm({}) exited with status {}", child.id(), status); |
| 308 | if let Some(exit_status_code) = status.code() { |
| 309 | if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS { |
| 310 | info!("detected vcpu stall on crosvm"); |
| 311 | } |
| 312 | } |
| 313 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 314 | } |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 315 | |
| 316 | let mut vm_state = self.vm_state.lock().unwrap(); |
| 317 | *vm_state = VmState::Dead; |
| 318 | // Ensure that the mutex is released before calling the callbacks. |
| 319 | drop(vm_state); |
| 320 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 321 | // Read the pipe to see if any failure reason is written |
| 322 | let mut failure_reason = String::new(); |
| 323 | match failure_pipe_read.read_to_string(&mut failure_reason) { |
| 324 | Err(e) => error!("Error reading VM failure reason from pipe: {}", e), |
| 325 | Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason), |
| 326 | _ => (), |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 327 | }; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 328 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 329 | // In case of hangup, the pipe doesn't give us any information because the hangup can't be |
| 330 | // detected on the VM side (otherwise, it isn't a hangup), but in the |
| 331 | // monitor_payload_hangup function below which updates the payload state to Hangup. |
| 332 | let failure_reason = |
| 333 | if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup { |
| 334 | Cow::from("HANGUP") |
| 335 | } else { |
| 336 | Cow::from(failure_reason) |
| 337 | }; |
| 338 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 339 | self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e)); |
Seungjae Yoo | b4c07ba | 2022-08-12 04:44:52 +0000 | [diff] [blame] | 340 | |
| 341 | let death_reason = death_reason(&result, &failure_reason); |
| 342 | self.callbacks.callback_on_died(self.cid, death_reason); |
Seungjae Yoo | 2e7beea | 2022-08-24 16:09:12 +0900 | [diff] [blame] | 343 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 344 | let vm_metric = self.vm_metric.lock().unwrap(); |
| 345 | write_vm_exited_stats(self.requester_uid as i32, &self.name, death_reason, &*vm_metric); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 346 | |
| 347 | // Delete temporary files. |
| 348 | if let Err(e) = remove_dir_all(&self.temporary_directory) { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 349 | error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 350 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 351 | } |
| 352 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 353 | /// Waits until payload is started, or timeout expires. When timeout occurs, kill |
| 354 | /// the VM to prevent indefinite hangup and update the payload_state accordingly. |
| 355 | fn monitor_payload_hangup(&self, child: Arc<SharedChild>) { |
| 356 | debug!("Starting to monitor hangup for Microdroid({})", child.id()); |
| 357 | let (_, result) = self |
| 358 | .payload_state_updated |
| 359 | .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| { |
| 360 | *s < PayloadState::Started |
| 361 | }) |
| 362 | .unwrap(); |
| 363 | let child_still_running = child.try_wait().ok() == Some(None); |
| 364 | if result.timed_out() && child_still_running { |
| 365 | error!( |
| 366 | "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.", |
| 367 | child.id(), |
| 368 | BOOT_HANGUP_TIMEOUT.as_secs() |
| 369 | ); |
| 370 | self.update_payload_state(PayloadState::Hangup).unwrap(); |
| 371 | if let Err(e) = self.kill() { |
| 372 | error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e); |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 377 | fn monitor_vm_status(&self, child: Arc<SharedChild>) { |
| 378 | let pid = child.id(); |
| 379 | |
| 380 | loop { |
| 381 | { |
| 382 | // Check VM state |
| 383 | let vm_state = &*self.vm_state.lock().unwrap(); |
| 384 | if let VmState::Dead = vm_state { |
| 385 | break; |
| 386 | } |
| 387 | |
| 388 | let mut vm_metric = self.vm_metric.lock().unwrap(); |
| 389 | |
| 390 | // Get CPU Information |
| 391 | // TODO: Collect it once right before VM dies using SIGCHLD |
| 392 | if let Ok(guest_time) = get_guest_time(pid) { |
| 393 | vm_metric.cpu_guest_time = Some(guest_time); |
| 394 | } else { |
| 395 | error!("Failed to parse /proc/[pid]/stat"); |
| 396 | } |
| 397 | |
| 398 | // Get Memory Information |
| 399 | if let Ok(rss) = get_rss(pid) { |
| 400 | vm_metric.rss = match &vm_metric.rss { |
| 401 | Some(x) => Some(Rss::extract_max(x, &rss)), |
| 402 | None => Some(rss), |
| 403 | } |
| 404 | } else { |
| 405 | error!("Failed to parse /proc/[pid]/smaps"); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | thread::sleep(Duration::from_secs(1)); |
| 410 | } |
| 411 | } |
| 412 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 413 | /// Returns the last reported state of the VM payload. |
| 414 | pub fn payload_state(&self) -> PayloadState { |
| 415 | *self.payload_state.lock().unwrap() |
| 416 | } |
| 417 | |
| 418 | /// Updates the payload state to the given value, if it is a valid state transition. |
| 419 | pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> { |
| 420 | let mut state_locked = self.payload_state.lock().unwrap(); |
| 421 | // Only allow forward transitions, e.g. from starting to started or finished, not back in |
| 422 | // the other direction. |
| 423 | if new_state > *state_locked { |
| 424 | *state_locked = new_state; |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 425 | self.payload_state_updated.notify_all(); |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 426 | Ok(()) |
| 427 | } else { |
| 428 | bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state) |
| 429 | } |
| 430 | } |
| 431 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 432 | /// Kills the crosvm instance, if it is running. |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 433 | pub fn kill(&self) -> Result<(), Error> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 434 | let vm_state = &*self.vm_state.lock().unwrap(); |
| 435 | if let VmState::Running { child } = vm_state { |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 436 | let id = child.id(); |
| 437 | debug!("Killing crosvm({})", id); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 438 | // TODO: Talk to crosvm to shutdown cleanly. |
| 439 | if let Err(e) = child.kill() { |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 440 | bail!("Error killing crosvm({}) instance: {}", id, e); |
| 441 | } else { |
| 442 | Ok(()) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 443 | } |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 444 | } else { |
| 445 | bail!("VM is not running") |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 446 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 447 | } |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 448 | |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 449 | /// Responds to memory-trimming notifications by inflating the virtio |
| 450 | /// balloon to reclaim guest memory. |
| 451 | pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> { |
| 452 | let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {}); |
| 453 | match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) { |
| 454 | Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => { |
| 455 | if let Some(total_memory) = stats.total_memory { |
| 456 | // Reclaim up to 50% of total memory assuming worst case |
| 457 | // most memory is anonymous and must be swapped to zram |
| 458 | // with an approximate 2:1 compression ratio. |
| 459 | let pct = match level { |
| 460 | MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50, |
| 461 | MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30, |
| 462 | MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10, |
| 463 | _ => bail!("Invalid memory trim level {:?}", level), |
| 464 | }; |
| 465 | let command = |
| 466 | BalloonControlCommand::Adjust { num_bytes: total_memory * pct / 100 }; |
| 467 | if let Err(e) = vm_control::client::handle_request( |
| 468 | &VmRequest::BalloonCommand(command), |
| 469 | &self.crosvm_control_socket_path, |
| 470 | ) { |
| 471 | bail!("Error sending balloon adjustment: {:?}", e); |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | Ok(VmResponse::Err(e)) => { |
| 476 | // ENOTSUP is returned when the balloon protocol is not initialised. This |
| 477 | // can occur for numerous reasons: Guest is still booting, guest doesn't |
| 478 | // support ballooning, host doesn't support ballooning. We don't log or |
| 479 | // raise an error in this case: trim is just a hint and we can ignore it. |
| 480 | if e.errno() != libc::ENOTSUP { |
| 481 | bail!("Errno return when requesting balloon stats: {}", e.errno()) |
| 482 | } |
| 483 | } |
| 484 | e => bail!("Error requesting balloon stats: {:?}", e), |
| 485 | } |
| 486 | Ok(()) |
| 487 | } |
| 488 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 489 | /// Checks if ramdump has been created. If so, send a notification to the user with the handle |
| 490 | /// to read the ramdump. |
| 491 | fn handle_ramdump(&self) -> Result<(), Error> { |
| 492 | let ramdump_path = self.temporary_directory.join("ramdump"); |
| 493 | if std::fs::metadata(&ramdump_path)?.len() > 0 { |
| 494 | let ramdump = File::open(&ramdump_path) |
| 495 | .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?; |
| 496 | self.callbacks.callback_on_ramdump(self.cid, ramdump); |
Jiyong Park | 1612b90 | 2022-08-22 14:47:39 +0900 | [diff] [blame] | 497 | |
| 498 | Self::send_ramdump_to_tombstoned(&ramdump_path)?; |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 499 | } |
| 500 | Ok(()) |
| 501 | } |
Jiyong Park | 1612b90 | 2022-08-22 14:47:39 +0900 | [diff] [blame] | 502 | |
| 503 | fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> { |
| 504 | let mut input = File::open(ramdump_path) |
| 505 | .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?; |
| 506 | |
| 507 | let pid = std::process::id() as i32; |
| 508 | let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone) |
| 509 | .context("Failed to connect to tombstoned")?; |
| 510 | let mut output = conn |
| 511 | .text_output |
| 512 | .as_ref() |
| 513 | .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?; |
| 514 | |
| 515 | std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?; |
| 516 | info!("Ramdump {:?} sent to tombstoned", ramdump_path); |
| 517 | |
| 518 | conn.notify_completion()?; |
| 519 | Ok(()) |
| 520 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 521 | } |
| 522 | |
Seungjae Yoo | 6d265d9 | 2022-11-15 10:51:33 +0900 | [diff] [blame] | 523 | impl Rss { |
| 524 | fn extract_max(x: &Rss, y: &Rss) -> Rss { |
| 525 | Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) } |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | // Get guest time from /proc/[crosvm pid]/stat |
| 530 | fn get_guest_time(pid: u32) -> Result<i64> { |
| 531 | let file = read_to_string(format!("/proc/{}/stat", pid))?; |
| 532 | let data_list: Vec<_> = file.split_whitespace().collect(); |
| 533 | |
| 534 | // Information about guest_time is at 43th place of the file split with the whitespace. |
| 535 | // Example of /proc/[pid]/stat : |
| 536 | // 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 |
| 537 | // 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 |
| 538 | if data_list.len() < 43 { |
| 539 | bail!("Failed to parse command result for getting guest time : {}", file); |
| 540 | } |
| 541 | |
| 542 | let guest_time_ticks = data_list[42].parse::<i64>()?; |
| 543 | // SAFETY : It just returns an integer about CPU tick information. |
| 544 | let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) } as i64; |
| 545 | Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec) |
| 546 | } |
| 547 | |
| 548 | // Get rss from /proc/[crosvm pid]/smaps |
| 549 | fn get_rss(pid: u32) -> Result<Rss> { |
| 550 | let file = read_to_string(format!("/proc/{}/smaps", pid))?; |
| 551 | let lines: Vec<_> = file.split('\n').collect(); |
| 552 | |
| 553 | let mut rss_vm_total = 0i64; |
| 554 | let mut rss_crosvm_total = 0i64; |
| 555 | let mut is_vm = false; |
| 556 | for line in lines { |
| 557 | if line.contains("crosvm_guest") { |
| 558 | is_vm = true; |
| 559 | } else if line.contains("Rss:") { |
| 560 | let data_list: Vec<_> = line.split_whitespace().collect(); |
| 561 | if data_list.len() < 2 { |
| 562 | bail!("Failed to parse command result for getting rss :\n{}", line); |
| 563 | } |
| 564 | let rss = data_list[1].parse::<i64>()?; |
| 565 | |
| 566 | if is_vm { |
| 567 | rss_vm_total += rss; |
| 568 | is_vm = false; |
| 569 | } |
| 570 | rss_crosvm_total += rss; |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total }) |
| 575 | } |
| 576 | |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 577 | fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason { |
| 578 | if let Some(position) = failure_reason.find('|') { |
| 579 | // Separator indicates extra context information is present after the failure name. |
| 580 | error!("Failure info: {}", &failure_reason[(position + 1)..]); |
| 581 | failure_reason = &failure_reason[..position]; |
| 582 | } |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 583 | if let Ok(status) = result { |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 584 | match failure_reason { |
| 585 | "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => { |
| 586 | return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH |
| 587 | } |
| 588 | "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => { |
| 589 | return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED |
| 590 | } |
| 591 | "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH, |
| 592 | "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => { |
| 593 | return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED |
| 594 | } |
Inseob Kim | 272f572 | 2022-06-13 17:14:51 +0900 | [diff] [blame] | 595 | "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => { |
| 596 | return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE |
| 597 | } |
| 598 | "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED, |
| 599 | "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => { |
| 600 | return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED |
| 601 | } |
| 602 | "MICRODROID_INVALID_PAYLOAD_CONFIG" => { |
| 603 | return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG |
| 604 | } |
| 605 | "MICRODROID_UNKNOWN_RUNTIME_ERROR" => { |
| 606 | return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR |
| 607 | } |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 608 | "HANGUP" => return DeathReason::HANGUP, |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 609 | _ => {} |
| 610 | } |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 611 | match status.code() { |
| 612 | None => DeathReason::KILLED, |
| 613 | Some(0) => DeathReason::SHUTDOWN, |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 614 | Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR, |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 615 | Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT, |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 616 | Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH, |
Sebastian Ene | 23167d8 | 2022-10-07 14:09:53 +0000 | [diff] [blame] | 617 | Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT, |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 618 | Some(_) => DeathReason::UNKNOWN, |
| 619 | } |
| 620 | } else { |
| 621 | DeathReason::INFRASTRUCTURE_ERROR |
| 622 | } |
| 623 | } |
| 624 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 625 | /// Starts an instance of `crosvm` to manage a new VM. |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 626 | fn run_vm( |
| 627 | config: CrosvmConfig, |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 628 | crosvm_control_socket_path: &Path, |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 629 | failure_pipe_write: File, |
| 630 | ) -> Result<SharedChild, Error> { |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 631 | validate_config(&config)?; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 632 | |
| 633 | let mut command = Command::new(CROSVM_PATH); |
| 634 | // TODO(qwandor): Remove --disable-sandbox. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 635 | command |
| 636 | .arg("--extended-status") |
Jiyong Park | 6c60fea | 2022-10-24 16:10:01 +0900 | [diff] [blame] | 637 | // Configure the logger for the crosvm process to silence logs from the disk crate which |
| 638 | // don't provide much information to us (but do spamming us). |
| 639 | .arg("--log-level") |
| 640 | .arg("info,disk=off") |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 641 | .arg("run") |
| 642 | .arg("--disable-sandbox") |
| 643 | .arg("--cid") |
| 644 | .arg(config.cid.to_string()); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 645 | |
Keir Fraser | f25cb92 | 2022-11-23 14:26:00 +0000 | [diff] [blame] | 646 | if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? { |
| 647 | command.arg("--balloon-page-reporting"); |
| 648 | } else { |
| 649 | command.arg("--no-balloon"); |
| 650 | } |
| 651 | |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 652 | if config.protected { |
Jaewan Kim | 4642281 | 2022-11-25 10:59:39 +0900 | [diff] [blame] | 653 | match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? { |
| 654 | Some(pvmfw_path) if !pvmfw_path.is_empty() => { |
| 655 | command.arg("--protected-vm-with-firmware").arg(pvmfw_path) |
| 656 | } |
| 657 | _ => command.arg("--protected-vm"), |
| 658 | }; |
Andrew Walbran | 0b5789f | 2022-02-04 13:57:57 +0000 | [diff] [blame] | 659 | |
| 660 | // 3 virtio-console devices + vsock = 4. |
| 661 | let virtio_pci_device_count = 4 + config.disks.len(); |
| 662 | // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be |
| 663 | // enough. |
| 664 | let swiotlb_size_mib = 2 * virtio_pci_device_count; |
| 665 | command.arg("--swiotlb").arg(swiotlb_size_mib.to_string()); |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 666 | } |
| 667 | |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 668 | if let Some(memory_mib) = config.memory_mib { |
| 669 | command.arg("--mem").arg(memory_mib.to_string()); |
| 670 | } |
| 671 | |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 672 | if let Some(cpus) = config.cpus { |
| 673 | command.arg("--cpus").arg(cpus.to_string()); |
| 674 | } |
| 675 | |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 676 | if !config.task_profiles.is_empty() { |
| 677 | command.arg("--task-profiles").arg(config.task_profiles.join(",")); |
| 678 | } |
| 679 | |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 680 | // Keep track of what file descriptors should be mapped to the crosvm process. |
| 681 | let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect(); |
| 682 | |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 683 | // Setup the serial devices. |
| 684 | // 1. uart device: used as the output device by bootloaders and as early console by linux |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 685 | // 2. uart device: used to report the reason for the VM failing. |
| 686 | // 3. virtio-console device: used as the console device where kmsg is redirected to |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 687 | // 4. virtio-console device: used as the ramdump output |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 688 | // 5. virtio-console device: used as the logcat output |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 689 | // |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 690 | // When [console|log]_fd is not specified, the devices are attached to sink, which means what's |
| 691 | // written there is discarded. |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 692 | let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd); |
| 693 | let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd); |
| 694 | let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write); |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 695 | let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump); |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 696 | |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 697 | // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot |
| 698 | // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block |
| 699 | // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm |
| 700 | // doesn't have the issue. |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 701 | // /dev/ttyS0 |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 702 | command.arg(format!("--serial={},hardware=serial,num=1", &console_arg)); |
| 703 | // /dev/ttyS1 |
| 704 | command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path)); |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 705 | // /dev/hvc0 |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 706 | command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg)); |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 707 | // /dev/hvc1 |
| 708 | command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg)); |
Jiyong Park | ae5a4ed | 2021-11-01 18:36:28 +0900 | [diff] [blame] | 709 | // /dev/hvc2 |
| 710 | command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg)); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 711 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 712 | if let Some(bootloader) = &config.bootloader { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 713 | command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 714 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 715 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 716 | if let Some(initrd) = &config.initrd { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 717 | command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 718 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 719 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 720 | if let Some(params) = &config.params { |
| 721 | command.arg("--params").arg(params); |
| 722 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 723 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 724 | for disk in &config.disks { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 725 | command |
| 726 | .arg(if disk.writable { "--rwdisk" } else { "--disk" }) |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 727 | .arg(add_preserved_fd(&mut preserved_fds, &disk.image)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 728 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 729 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 730 | if let Some(kernel) = &config.kernel { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 731 | command.arg(add_preserved_fd(&mut preserved_fds, kernel)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 732 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 733 | |
Keir Fraser | cdd4b11 | 2022-11-24 14:02:25 +0000 | [diff] [blame^] | 734 | let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path) |
| 735 | .context("failed to create control server")?; |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 736 | command.arg("--socket").arg(add_preserved_fd(&mut preserved_fds, &control_server_socket)); |
| 737 | |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 738 | debug!("Preserving FDs {:?}", preserved_fds); |
| 739 | command.preserved_fds(preserved_fds); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 740 | |
Jaewan Kim | b281406 | 2022-11-14 13:21:40 +0900 | [diff] [blame] | 741 | command.arg("--params").arg("crashkernel=17M"); |
Jiyong Park | 2d73656 | 2022-10-24 22:40:12 +0900 | [diff] [blame] | 742 | print_crosvm_args(&command); |
| 743 | |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 744 | let result = SharedChild::spawn(&mut command)?; |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 745 | debug!("Spawned crosvm({}).", result.id()); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 746 | Ok(result) |
| 747 | } |
| 748 | |
| 749 | /// Ensure that the configuration has a valid combination of fields set, or return an error if not. |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 750 | fn validate_config(config: &CrosvmConfig) -> Result<(), Error> { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 751 | if config.bootloader.is_none() && config.kernel.is_none() { |
| 752 | bail!("VM must have either a bootloader or a kernel image."); |
| 753 | } |
| 754 | if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) { |
| 755 | bail!("Can't have both bootloader and kernel/initrd image."); |
| 756 | } |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 757 | let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap(); |
| 758 | if !config.platform_version.matches(&version) { |
| 759 | bail!( |
| 760 | "Incompatible platform version. The config is compatible with platform version(s) \ |
| 761 | {}, but the actual platform version is {}", |
| 762 | config.platform_version, |
| 763 | version |
| 764 | ); |
| 765 | } |
| 766 | |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 767 | Ok(()) |
| 768 | } |
| 769 | |
Jiyong Park | 2d73656 | 2022-10-24 22:40:12 +0900 | [diff] [blame] | 770 | /// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the |
| 771 | /// actual file path if the FD is backed by a regular file. If not, the /proc path is printed |
| 772 | /// unmodified. |
| 773 | fn print_crosvm_args(command: &Command) { |
| 774 | let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap(); |
| 775 | info!( |
| 776 | "Running crosvm with args: {:?}", |
| 777 | command |
| 778 | .get_args() |
| 779 | .map(|s| s.to_string_lossy()) |
| 780 | .map(|s| { |
| 781 | re.replace_all(&s, |caps: &Captures| { |
| 782 | let path = &caps[0]; |
| 783 | if let Ok(realpath) = std::fs::canonicalize(path) { |
| 784 | format!("{} ({})", path, realpath.to_string_lossy()) |
| 785 | } else { |
| 786 | path.to_owned() |
| 787 | } |
| 788 | }) |
| 789 | .into_owned() |
| 790 | }) |
| 791 | .collect::<Vec<_>>() |
| 792 | ); |
| 793 | } |
| 794 | |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 795 | /// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form |
| 796 | /// "/proc/self/fd/N" where N is the file descriptor. |
Keir Fraser | 13a956a | 2022-07-14 14:20:46 +0000 | [diff] [blame] | 797 | fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 798 | let fd = file.as_raw_fd(); |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 799 | preserved_fds.push(fd); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 800 | format!("/proc/self/fd/{}", fd) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 801 | } |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 802 | |
| 803 | /// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate |
| 804 | /// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device. |
| 805 | fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String { |
| 806 | if let Some(file) = file { |
| 807 | format!("type=file,path={}", add_preserved_fd(preserved_fds, file)) |
| 808 | } else { |
| 809 | "type=sink".to_string() |
| 810 | } |
| 811 | } |
| 812 | |
| 813 | /// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side. |
| 814 | fn create_pipe() -> Result<(File, File), Error> { |
| 815 | let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?; |
| 816 | // SAFETY: We are the sole owners of these fds as they were just created. |
| 817 | let read_fd = unsafe { File::from_raw_fd(raw_read) }; |
| 818 | let write_fd = unsafe { File::from_raw_fd(raw_write) }; |
| 819 | Ok((read_fd, write_fd)) |
| 820 | } |