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 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 17 | use crate::aidl::VirtualMachineCallbacks; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 18 | use crate::Cid; |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 19 | use anyhow::{bail, Context, Error}; |
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; |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 22 | use log::{debug, error, info}; |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 23 | use semver::{Version, VersionReq}; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 24 | use nix::{fcntl::OFlag, unistd::pipe2}; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 25 | use shared_child::SharedChild; |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 26 | use std::borrow::Cow; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 27 | use std::fs::{remove_dir_all, File}; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 28 | use std::io::{self, Read}; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 29 | use std::mem; |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 30 | use std::num::NonZeroU32; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 31 | use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 32 | use std::path::PathBuf; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 33 | use std::process::{Command, ExitStatus}; |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 34 | use std::sync::{Arc, Condvar, Mutex}; |
| 35 | use std::time::Duration; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 36 | use std::thread; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 37 | use vsock::VsockStream; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 38 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason; |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 39 | use android_system_virtualmachineservice::binder::Strong; |
| 40 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 41 | |
| 42 | const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm"; |
| 43 | |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 44 | /// Version of the platform that crosvm currently implements. The format follows SemVer. This |
| 45 | /// should be updated when there is a platform change in the crosvm side. Having this value here is |
| 46 | /// fine because virtualizationservice and crosvm are supposed to be updated together in the virt |
| 47 | /// APEX. |
| 48 | const CROSVM_PLATFORM_VERSION: &str = "1.0.0"; |
| 49 | |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 50 | /// The exit status which crosvm returns when it has an error starting a VM. |
| 51 | const CROSVM_ERROR_STATUS: i32 = 1; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 52 | /// The exit status which crosvm returns when a VM requests a reboot. |
| 53 | const CROSVM_REBOOT_STATUS: i32 = 32; |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 54 | /// The exit status which crosvm returns when it crashes due to an error. |
| 55 | const CROSVM_CRASH_STATUS: i32 = 33; |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 56 | |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 57 | lazy_static! { |
| 58 | /// If the VM doesn't move to the Started state within this amount time, a hang-up error is |
| 59 | /// triggered. |
Alan Stokes | c3f2ac2 | 2022-06-23 12:19:46 +0100 | [diff] [blame] | 60 | 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] | 61 | // Nested virtualization is slow, so we need a longer timeout. |
| 62 | Duration::from_secs(100) |
| 63 | } else { |
| 64 | Duration::from_secs(10) |
| 65 | }; |
| 66 | } |
| 67 | |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 68 | /// Configuration for a VM to run with crosvm. |
| 69 | #[derive(Debug)] |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 70 | pub struct CrosvmConfig { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 71 | pub cid: Cid, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 72 | pub bootloader: Option<File>, |
| 73 | pub kernel: Option<File>, |
| 74 | pub initrd: Option<File>, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 75 | pub disks: Vec<DiskFile>, |
| 76 | pub params: Option<String>, |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 77 | pub protected: bool, |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 78 | pub memory_mib: Option<NonZeroU32>, |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 79 | pub cpus: Option<NonZeroU32>, |
| 80 | pub cpu_affinity: Option<String>, |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 81 | pub task_profiles: Vec<String>, |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 82 | pub console_fd: Option<File>, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 83 | pub log_fd: Option<File>, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 84 | pub ramdump: Option<File>, |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 85 | pub indirect_files: Vec<File>, |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 86 | pub platform_version: VersionReq, |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 87 | pub detect_hangup: bool, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 88 | } |
| 89 | |
| 90 | /// A disk image to pass to crosvm for a VM. |
| 91 | #[derive(Debug)] |
| 92 | pub struct DiskFile { |
| 93 | pub image: File, |
| 94 | pub writable: bool, |
| 95 | } |
| 96 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 97 | /// The lifecycle state which the payload in the VM has reported itself to be in. |
| 98 | /// |
| 99 | /// Note that the order of enum variants is significant; only forward transitions are allowed by |
| 100 | /// [`VmInstance::update_payload_state`]. |
| 101 | #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
| 102 | pub enum PayloadState { |
| 103 | Starting, |
| 104 | Started, |
| 105 | Ready, |
| 106 | Finished, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 107 | Hangup, // Hasn't reached to Ready before timeout expires |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 108 | } |
| 109 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 110 | /// The current state of the VM itself. |
| 111 | #[derive(Debug)] |
| 112 | pub enum VmState { |
| 113 | /// The VM has not yet tried to start. |
| 114 | NotStarted { |
| 115 | ///The configuration needed to start the VM, if it has not yet been started. |
| 116 | config: CrosvmConfig, |
| 117 | }, |
| 118 | /// The VM has been started. |
| 119 | Running { |
| 120 | /// The crosvm child process. |
| 121 | child: Arc<SharedChild>, |
| 122 | }, |
| 123 | /// The VM died or was killed. |
| 124 | Dead, |
| 125 | /// The VM failed to start. |
| 126 | Failed, |
| 127 | } |
| 128 | |
| 129 | impl VmState { |
| 130 | /// Tries to start the VM, if it is in the `NotStarted` state. |
| 131 | /// |
| 132 | /// Returns an error if the VM is in the wrong state, or fails to start. |
| 133 | fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> { |
| 134 | let state = mem::replace(self, VmState::Failed); |
| 135 | if let VmState::NotStarted { config } = state { |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 136 | let detect_hangup = config.detect_hangup; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 137 | let (failure_pipe_read, failure_pipe_write) = create_pipe()?; |
| 138 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 139 | // If this fails and returns an error, `self` will be left in the `Failed` state. |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 140 | let child = Arc::new(run_vm(config, failure_pipe_write)?); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 141 | |
| 142 | let child_clone = child.clone(); |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 143 | let instance_clone = instance.clone(); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 144 | thread::spawn(move || { |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 145 | instance_clone.monitor_vm_exit(child_clone, failure_pipe_read); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 146 | }); |
| 147 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 148 | if detect_hangup { |
| 149 | let child_clone = child.clone(); |
| 150 | thread::spawn(move || { |
| 151 | instance.monitor_payload_hangup(child_clone); |
| 152 | }); |
| 153 | } |
| 154 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 155 | // If it started correctly, update the state. |
| 156 | *self = VmState::Running { child }; |
| 157 | Ok(()) |
| 158 | } else { |
| 159 | *self = state; |
| 160 | bail!("VM already started or failed") |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// Information about a particular instance of a VM which may be running. |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 166 | #[derive(Debug)] |
| 167 | pub struct VmInstance { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 168 | /// The current state of the VM. |
| 169 | pub vm_state: Mutex<VmState>, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 170 | /// The CID assigned to the VM for vsock communication. |
| 171 | pub cid: Cid, |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 172 | /// Whether the VM is a protected VM. |
| 173 | pub protected: bool, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 174 | /// Directory of temporary files used by the VM while it is running. |
| 175 | pub temporary_directory: PathBuf, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 176 | /// The UID of the process which requested the VM. |
| 177 | pub requester_uid: u32, |
| 178 | /// The SID of the process which requested the VM. |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 179 | pub requester_sid: String, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 180 | /// The PID of the process which requested the VM. Note that this process may no longer exist |
| 181 | /// 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] | 182 | pub requester_debug_pid: i32, |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 183 | /// Callbacks to clients of the VM. |
| 184 | pub callbacks: VirtualMachineCallbacks, |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 185 | /// Input/output stream of the payload run in the VM. |
| 186 | pub stream: Mutex<Option<VsockStream>>, |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 187 | /// VirtualMachineService binder object for the VM. |
| 188 | pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>, |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 189 | /// The latest lifecycle state which the payload reported itself to be in. |
| 190 | payload_state: Mutex<PayloadState>, |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 191 | /// Represents the condition that payload_state was updated |
| 192 | payload_state_updated: Condvar, |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 193 | } |
| 194 | |
| 195 | impl VmInstance { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 196 | /// Validates the given config and creates a new `VmInstance` but doesn't start running it. |
| 197 | pub fn new( |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 198 | config: CrosvmConfig, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 199 | temporary_directory: PathBuf, |
Andrew Walbran | f6a1eb9 | 2021-04-01 11:16:02 +0000 | [diff] [blame] | 200 | requester_uid: u32, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 201 | requester_sid: String, |
| 202 | requester_debug_pid: i32, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 203 | ) -> Result<VmInstance, Error> { |
| 204 | validate_config(&config)?; |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 205 | let cid = config.cid; |
| 206 | let protected = config.protected; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 207 | Ok(VmInstance { |
| 208 | vm_state: Mutex::new(VmState::NotStarted { config }), |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 209 | cid, |
| 210 | protected, |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 211 | temporary_directory, |
Andrew Walbran | 0203449 | 2021-04-13 15:05:07 +0000 | [diff] [blame] | 212 | requester_uid, |
| 213 | requester_sid, |
| 214 | requester_debug_pid, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 215 | callbacks: Default::default(), |
| 216 | stream: Mutex::new(None), |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 217 | vm_service: Mutex::new(None), |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 218 | payload_state: Mutex::new(PayloadState::Starting), |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 219 | payload_state_updated: Condvar::new(), |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 220 | }) |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 221 | } |
| 222 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 223 | /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when |
| 224 | /// the `VmInstance` is dropped. |
| 225 | pub fn start(self: &Arc<Self>) -> Result<(), Error> { |
| 226 | self.vm_state.lock().unwrap().start(self.clone()) |
| 227 | } |
| 228 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 229 | /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens, |
| 230 | /// handles the event by updating the state, noityfing the event to clients by calling |
| 231 | /// callbacks, and removing temporary files for the VM. |
| 232 | 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] | 233 | let result = child.wait(); |
| 234 | match &result { |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 235 | Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e), |
| 236 | Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status), |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 237 | } |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 238 | |
| 239 | let mut vm_state = self.vm_state.lock().unwrap(); |
| 240 | *vm_state = VmState::Dead; |
| 241 | // Ensure that the mutex is released before calling the callbacks. |
| 242 | drop(vm_state); |
| 243 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 244 | // Read the pipe to see if any failure reason is written |
| 245 | let mut failure_reason = String::new(); |
| 246 | match failure_pipe_read.read_to_string(&mut failure_reason) { |
| 247 | Err(e) => error!("Error reading VM failure reason from pipe: {}", e), |
| 248 | Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason), |
| 249 | _ => (), |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 250 | }; |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 251 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 252 | // In case of hangup, the pipe doesn't give us any information because the hangup can't be |
| 253 | // detected on the VM side (otherwise, it isn't a hangup), but in the |
| 254 | // monitor_payload_hangup function below which updates the payload state to Hangup. |
| 255 | let failure_reason = |
| 256 | if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup { |
| 257 | Cow::from("HANGUP") |
| 258 | } else { |
| 259 | Cow::from(failure_reason) |
| 260 | }; |
| 261 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 262 | self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e)); |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 263 | self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_reason)); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 264 | |
| 265 | // Delete temporary files. |
| 266 | if let Err(e) = remove_dir_all(&self.temporary_directory) { |
Andrew Walbran | 806f154 | 2021-06-10 14:07:12 +0000 | [diff] [blame] | 267 | error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e); |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 268 | } |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 269 | } |
| 270 | |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 271 | /// Waits until payload is started, or timeout expires. When timeout occurs, kill |
| 272 | /// the VM to prevent indefinite hangup and update the payload_state accordingly. |
| 273 | fn monitor_payload_hangup(&self, child: Arc<SharedChild>) { |
| 274 | debug!("Starting to monitor hangup for Microdroid({})", child.id()); |
| 275 | let (_, result) = self |
| 276 | .payload_state_updated |
| 277 | .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| { |
| 278 | *s < PayloadState::Started |
| 279 | }) |
| 280 | .unwrap(); |
| 281 | let child_still_running = child.try_wait().ok() == Some(None); |
| 282 | if result.timed_out() && child_still_running { |
| 283 | error!( |
| 284 | "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.", |
| 285 | child.id(), |
| 286 | BOOT_HANGUP_TIMEOUT.as_secs() |
| 287 | ); |
| 288 | self.update_payload_state(PayloadState::Hangup).unwrap(); |
| 289 | if let Err(e) = self.kill() { |
| 290 | error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e); |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 295 | /// Returns the last reported state of the VM payload. |
| 296 | pub fn payload_state(&self) -> PayloadState { |
| 297 | *self.payload_state.lock().unwrap() |
| 298 | } |
| 299 | |
| 300 | /// Updates the payload state to the given value, if it is a valid state transition. |
| 301 | pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> { |
| 302 | let mut state_locked = self.payload_state.lock().unwrap(); |
| 303 | // Only allow forward transitions, e.g. from starting to started or finished, not back in |
| 304 | // the other direction. |
| 305 | if new_state > *state_locked { |
| 306 | *state_locked = new_state; |
Jiyong Park | a4eebde | 2022-07-12 18:01:12 +0900 | [diff] [blame] | 307 | self.payload_state_updated.notify_all(); |
Andrew Walbran | 6b65066 | 2021-09-07 13:13:23 +0000 | [diff] [blame] | 308 | Ok(()) |
| 309 | } else { |
| 310 | bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state) |
| 311 | } |
| 312 | } |
| 313 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 314 | /// Kills the crosvm instance, if it is running. |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 315 | pub fn kill(&self) -> Result<(), Error> { |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 316 | let vm_state = &*self.vm_state.lock().unwrap(); |
| 317 | if let VmState::Running { child } = vm_state { |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 318 | let id = child.id(); |
| 319 | debug!("Killing crosvm({})", id); |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 320 | // TODO: Talk to crosvm to shutdown cleanly. |
| 321 | if let Err(e) = child.kill() { |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 322 | bail!("Error killing crosvm({}) instance: {}", id, e); |
| 323 | } else { |
| 324 | Ok(()) |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 325 | } |
Inseob Kim | a446f80 | 2022-07-11 19:46:37 +0900 | [diff] [blame] | 326 | } else { |
| 327 | bail!("VM is not running") |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 328 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 329 | } |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 330 | |
| 331 | /// Checks if ramdump has been created. If so, send a notification to the user with the handle |
| 332 | /// to read the ramdump. |
| 333 | fn handle_ramdump(&self) -> Result<(), Error> { |
| 334 | let ramdump_path = self.temporary_directory.join("ramdump"); |
| 335 | if std::fs::metadata(&ramdump_path)?.len() > 0 { |
| 336 | let ramdump = File::open(&ramdump_path) |
| 337 | .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?; |
| 338 | self.callbacks.callback_on_ramdump(self.cid, ramdump); |
| 339 | } |
| 340 | Ok(()) |
| 341 | } |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 342 | } |
| 343 | |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 344 | fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason { |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 345 | if let Ok(status) = result { |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 346 | match failure_reason { |
| 347 | "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => { |
| 348 | return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH |
| 349 | } |
| 350 | "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => { |
| 351 | return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED |
| 352 | } |
| 353 | "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH, |
| 354 | "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => { |
| 355 | return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED |
| 356 | } |
Inseob Kim | 272f572 | 2022-06-13 17:14:51 +0900 | [diff] [blame] | 357 | "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => { |
| 358 | return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE |
| 359 | } |
| 360 | "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED, |
| 361 | "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => { |
| 362 | return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED |
| 363 | } |
| 364 | "MICRODROID_INVALID_PAYLOAD_CONFIG" => { |
| 365 | return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG |
| 366 | } |
| 367 | "MICRODROID_UNKNOWN_RUNTIME_ERROR" => { |
| 368 | return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR |
| 369 | } |
Jiyong Park | e6ed0f9 | 2022-06-22 00:13:00 +0900 | [diff] [blame] | 370 | "HANGUP" => return DeathReason::HANGUP, |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 371 | _ => {} |
| 372 | } |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 373 | match status.code() { |
| 374 | None => DeathReason::KILLED, |
| 375 | Some(0) => DeathReason::SHUTDOWN, |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 376 | Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR, |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 377 | Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT, |
Andrew Walbran | d15c563 | 2022-02-03 13:38:31 +0000 | [diff] [blame] | 378 | Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH, |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 379 | Some(_) => DeathReason::UNKNOWN, |
| 380 | } |
| 381 | } else { |
| 382 | DeathReason::INFRASTRUCTURE_ERROR |
| 383 | } |
| 384 | } |
| 385 | |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 386 | /// Starts an instance of `crosvm` to manage a new VM. |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 387 | fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> { |
Andrew Walbran | d3a8418 | 2021-09-07 14:48:52 +0000 | [diff] [blame] | 388 | validate_config(&config)?; |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 389 | |
| 390 | let mut command = Command::new(CROSVM_PATH); |
| 391 | // TODO(qwandor): Remove --disable-sandbox. |
Andrew Walbran | c92d35f | 2022-01-12 12:45:19 +0000 | [diff] [blame] | 392 | command |
| 393 | .arg("--extended-status") |
| 394 | .arg("run") |
| 395 | .arg("--disable-sandbox") |
| 396 | .arg("--cid") |
| 397 | .arg(config.cid.to_string()); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 398 | |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 399 | if config.protected { |
David Brazdil | 86c76fa | 2022-02-04 15:50:57 +0000 | [diff] [blame] | 400 | command.arg("--protected-vm"); |
Andrew Walbran | 0b5789f | 2022-02-04 13:57:57 +0000 | [diff] [blame] | 401 | |
| 402 | // 3 virtio-console devices + vsock = 4. |
| 403 | let virtio_pci_device_count = 4 + config.disks.len(); |
| 404 | // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be |
| 405 | // enough. |
| 406 | let swiotlb_size_mib = 2 * virtio_pci_device_count; |
| 407 | command.arg("--swiotlb").arg(swiotlb_size_mib.to_string()); |
Andrew Walbran | f865042 | 2021-06-09 15:54:09 +0000 | [diff] [blame] | 408 | } |
| 409 | |
Andrew Walbran | b15cd6e | 2021-07-05 16:38:07 +0000 | [diff] [blame] | 410 | if let Some(memory_mib) = config.memory_mib { |
| 411 | command.arg("--mem").arg(memory_mib.to_string()); |
| 412 | } |
| 413 | |
Jiyong Park | 032615f | 2022-01-10 13:55:34 +0900 | [diff] [blame] | 414 | if let Some(cpus) = config.cpus { |
| 415 | command.arg("--cpus").arg(cpus.to_string()); |
| 416 | } |
| 417 | |
| 418 | if let Some(cpu_affinity) = config.cpu_affinity { |
| 419 | command.arg("--cpu-affinity").arg(cpu_affinity); |
| 420 | } |
| 421 | |
Jiyong Park | dfe16d6 | 2022-04-20 17:32:12 +0900 | [diff] [blame] | 422 | if !config.task_profiles.is_empty() { |
| 423 | command.arg("--task-profiles").arg(config.task_profiles.join(",")); |
| 424 | } |
| 425 | |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 426 | // Keep track of what file descriptors should be mapped to the crosvm process. |
| 427 | let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect(); |
| 428 | |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 429 | // Setup the serial devices. |
| 430 | // 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] | 431 | // 2. uart device: used to report the reason for the VM failing. |
| 432 | // 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] | 433 | // 4. virtio-console device: used as the ramdump output |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 434 | // 5. virtio-console device: used as the logcat output |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 435 | // |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 436 | // When [console|log]_fd is not specified, the devices are attached to sink, which means what's |
| 437 | // written there is discarded. |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 438 | let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd); |
| 439 | let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd); |
| 440 | 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] | 441 | let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump); |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 442 | |
Jiyong Park | 747d636 | 2021-10-19 17:12:52 +0900 | [diff] [blame] | 443 | // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot |
| 444 | // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block |
| 445 | // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm |
| 446 | // doesn't have the issue. |
Jiyong Park | fa91d70 | 2021-10-18 23:51:39 +0900 | [diff] [blame] | 447 | // /dev/ttyS0 |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 448 | command.arg(format!("--serial={},hardware=serial,num=1", &console_arg)); |
| 449 | // /dev/ttyS1 |
| 450 | 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] | 451 | // /dev/hvc0 |
Jiyong Park | b8182bb | 2021-10-26 22:53:08 +0900 | [diff] [blame] | 452 | command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg)); |
Jiyong Park | 4afe201 | 2022-07-08 05:38:49 +0900 | [diff] [blame] | 453 | // /dev/hvc1 |
| 454 | command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg)); |
Jiyong Park | ae5a4ed | 2021-11-01 18:36:28 +0900 | [diff] [blame] | 455 | // /dev/hvc2 |
| 456 | command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg)); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 457 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 458 | if let Some(bootloader) = &config.bootloader { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 459 | command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 460 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 461 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 462 | if let Some(initrd) = &config.initrd { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 463 | command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 464 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 465 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 466 | if let Some(params) = &config.params { |
| 467 | command.arg("--params").arg(params); |
| 468 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 469 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 470 | for disk in &config.disks { |
Andrew Walbran | f5fbb7d | 2021-05-12 17:15:48 +0000 | [diff] [blame] | 471 | command |
| 472 | .arg(if disk.writable { "--rwdisk" } else { "--disk" }) |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 473 | .arg(add_preserved_fd(&mut preserved_fds, &disk.image)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 474 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 475 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 476 | if let Some(kernel) = &config.kernel { |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 477 | command.arg(add_preserved_fd(&mut preserved_fds, kernel)); |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 478 | } |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 479 | |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 480 | debug!("Preserving FDs {:?}", preserved_fds); |
| 481 | command.preserved_fds(preserved_fds); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 482 | |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 483 | info!("Running {:?}", command); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 484 | let result = SharedChild::spawn(&mut command)?; |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 485 | debug!("Spawned crosvm({}).", result.id()); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 486 | Ok(result) |
| 487 | } |
| 488 | |
| 489 | /// 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] | 490 | fn validate_config(config: &CrosvmConfig) -> Result<(), Error> { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 491 | if config.bootloader.is_none() && config.kernel.is_none() { |
| 492 | bail!("VM must have either a bootloader or a kernel image."); |
| 493 | } |
| 494 | if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) { |
| 495 | bail!("Can't have both bootloader and kernel/initrd image."); |
| 496 | } |
Jiyong Park | dcf1741 | 2022-02-08 15:07:23 +0900 | [diff] [blame] | 497 | let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap(); |
| 498 | if !config.platform_version.matches(&version) { |
| 499 | bail!( |
| 500 | "Incompatible platform version. The config is compatible with platform version(s) \ |
| 501 | {}, but the actual platform version is {}", |
| 502 | config.platform_version, |
| 503 | version |
| 504 | ); |
| 505 | } |
| 506 | |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 507 | Ok(()) |
| 508 | } |
| 509 | |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 510 | /// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form |
| 511 | /// "/proc/self/fd/N" where N is the file descriptor. |
| 512 | fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 513 | let fd = file.as_raw_fd(); |
Andrew Walbran | 02b8ec0 | 2021-06-22 13:07:02 +0000 | [diff] [blame] | 514 | preserved_fds.push(fd); |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 515 | format!("/proc/self/fd/{}", fd) |
Andrew Walbran | d6dce6f | 2021-03-05 16:39:08 +0000 | [diff] [blame] | 516 | } |
Andrew Walbran | b27681f | 2022-02-23 15:11:52 +0000 | [diff] [blame] | 517 | |
| 518 | /// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate |
| 519 | /// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device. |
| 520 | fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String { |
| 521 | if let Some(file) = file { |
| 522 | format!("type=file,path={}", add_preserved_fd(preserved_fds, file)) |
| 523 | } else { |
| 524 | "type=sink".to_string() |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side. |
| 529 | fn create_pipe() -> Result<(File, File), Error> { |
| 530 | let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?; |
| 531 | // SAFETY: We are the sole owners of these fds as they were just created. |
| 532 | let read_fd = unsafe { File::from_raw_fd(raw_read) }; |
| 533 | let write_fd = unsafe { File::from_raw_fd(raw_write) }; |
| 534 | Ok((read_fd, write_fd)) |
| 535 | } |