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