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