blob: a7e82da8d6304beac224a8b4763ddd171da6bd8f [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Functions for running instances of `crosvm`.
16
Andrew Walbrandae07162021-03-12 17:05:20 +000017use crate::aidl::VirtualMachineCallbacks;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000018use crate::Cid;
Jiyong Park1612b902022-08-22 14:47:39 +090019use anyhow::{anyhow, bail, Context, Error};
Andrew Walbran02b8ec02021-06-22 13:07:02 +000020use command_fds::CommandFdExt;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090021use lazy_static::lazy_static;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000022use log::{debug, error, info};
Jiyong Parkdcf17412022-02-08 15:07:23 +090023use semver::{Version, VersionReq};
Andrew Walbranb27681f2022-02-23 15:11:52 +000024use nix::{fcntl::OFlag, unistd::pipe2};
Andrew Walbrandae07162021-03-12 17:05:20 +000025use shared_child::SharedChild;
Jiyong Parke6ed0f92022-06-22 00:13:00 +090026use std::borrow::Cow;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000027use std::fs::{remove_dir_all, File};
Andrew Walbranb27681f2022-02-23 15:11:52 +000028use std::io::{self, Read};
Andrew Walbranf8d94112021-09-07 11:45:36 +000029use std::mem;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000030use std::num::NonZeroU32;
Andrew Walbranb27681f2022-02-23 15:11:52 +000031use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
Jiyong Park1612b902022-08-22 14:47:39 +090032use std::path::{Path, PathBuf};
Andrew Walbranc92d35f2022-01-12 12:45:19 +000033use std::process::{Command, ExitStatus};
Jiyong Parke6ed0f92022-06-22 00:13:00 +090034use std::sync::{Arc, Condvar, Mutex};
35use std::time::Duration;
Andrew Walbrandae07162021-03-12 17:05:20 +000036use std::thread;
Inseob Kim7f61fe72021-08-20 20:50:47 +090037use vsock::VsockStream;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000038use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
Alan Stokes0e82b502022-08-08 14:44:48 +010039use binder::Strong;
Inseob Kimc7d28c72021-10-25 14:28:10 +000040use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Jiyong Park1612b902022-08-22 14:47:39 +090041use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000042
43const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
44
Jiyong Parkdcf17412022-02-08 15:07:23 +090045/// 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.
49const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
50
Andrew Walbrand15c5632022-02-03 13:38:31 +000051/// The exit status which crosvm returns when it has an error starting a VM.
52const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000053/// The exit status which crosvm returns when a VM requests a reboot.
54const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000055/// The exit status which crosvm returns when it crashes due to an error.
56const CROSVM_CRASH_STATUS: i32 = 33;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000057
Jiyong Parke6ed0f92022-06-22 00:13:00 +090058lazy_static! {
59 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
60 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010061 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090062 // Nested virtualization is slow, so we need a longer timeout.
63 Duration::from_secs(100)
64 } else {
65 Duration::from_secs(10)
66 };
67}
68
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069/// Configuration for a VM to run with crosvm.
70#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000071pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000073 pub bootloader: Option<File>,
74 pub kernel: Option<File>,
75 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076 pub disks: Vec<DiskFile>,
77 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000078 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000079 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090080 pub cpus: Option<NonZeroU32>,
81 pub cpu_affinity: Option<String>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090082 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090083 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000084 pub log_fd: Option<File>,
Jiyong Parke558ab12022-07-07 20:18:55 +090085 pub ramdump: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000086 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090087 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090088 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089}
90
91/// A disk image to pass to crosvm for a VM.
92#[derive(Debug)]
93pub struct DiskFile {
94 pub image: File,
95 pub writable: bool,
96}
97
Andrew Walbran6b650662021-09-07 13:13:23 +000098/// The lifecycle state which the payload in the VM has reported itself to be in.
99///
100/// Note that the order of enum variants is significant; only forward transitions are allowed by
101/// [`VmInstance::update_payload_state`].
102#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
103pub enum PayloadState {
104 Starting,
105 Started,
106 Ready,
107 Finished,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900108 Hangup, // Hasn't reached to Ready before timeout expires
Andrew Walbran6b650662021-09-07 13:13:23 +0000109}
110
Andrew Walbranf8d94112021-09-07 11:45:36 +0000111/// The current state of the VM itself.
112#[derive(Debug)]
113pub enum VmState {
114 /// The VM has not yet tried to start.
115 NotStarted {
116 ///The configuration needed to start the VM, if it has not yet been started.
117 config: CrosvmConfig,
118 },
119 /// The VM has been started.
120 Running {
121 /// The crosvm child process.
122 child: Arc<SharedChild>,
123 },
124 /// The VM died or was killed.
125 Dead,
126 /// The VM failed to start.
127 Failed,
128}
129
130impl VmState {
131 /// Tries to start the VM, if it is in the `NotStarted` state.
132 ///
133 /// Returns an error if the VM is in the wrong state, or fails to start.
134 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
135 let state = mem::replace(self, VmState::Failed);
136 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900137 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000138 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
139
Andrew Walbranf8d94112021-09-07 11:45:36 +0000140 // If this fails and returns an error, `self` will be left in the `Failed` state.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000141 let child = Arc::new(run_vm(config, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000142
143 let child_clone = child.clone();
Jiyong Parka4eebde2022-07-12 18:01:12 +0900144 let instance_clone = instance.clone();
Andrew Walbranf8d94112021-09-07 11:45:36 +0000145 thread::spawn(move || {
Jiyong Parka4eebde2022-07-12 18:01:12 +0900146 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000147 });
148
Jiyong Parka4eebde2022-07-12 18:01:12 +0900149 if detect_hangup {
150 let child_clone = child.clone();
151 thread::spawn(move || {
152 instance.monitor_payload_hangup(child_clone);
153 });
154 }
155
Andrew Walbranf8d94112021-09-07 11:45:36 +0000156 // If it started correctly, update the state.
157 *self = VmState::Running { child };
158 Ok(())
159 } else {
160 *self = state;
161 bail!("VM already started or failed")
162 }
163 }
164}
165
166/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000167#[derive(Debug)]
168pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000169 /// The current state of the VM.
170 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000171 /// The CID assigned to the VM for vsock communication.
172 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000173 /// Whether the VM is a protected VM.
174 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000175 /// Directory of temporary files used by the VM while it is running.
176 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000177 /// The UID of the process which requested the VM.
178 pub requester_uid: u32,
179 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000180 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000181 /// The PID of the process which requested the VM. Note that this process may no longer exist
182 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000183 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000184 /// Callbacks to clients of the VM.
185 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900186 /// Input/output stream of the payload run in the VM.
187 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000188 /// VirtualMachineService binder object for the VM.
189 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000190 /// The latest lifecycle state which the payload reported itself to be in.
191 payload_state: Mutex<PayloadState>,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900192 /// Represents the condition that payload_state was updated
193 payload_state_updated: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000194}
195
196impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000197 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
198 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000199 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000200 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000201 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000202 requester_sid: String,
203 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000204 ) -> Result<VmInstance, Error> {
205 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000206 let cid = config.cid;
207 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000208 Ok(VmInstance {
209 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000210 cid,
211 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000212 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000213 requester_uid,
214 requester_sid,
215 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000216 callbacks: Default::default(),
217 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000218 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000219 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parka4eebde2022-07-12 18:01:12 +0900220 payload_state_updated: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000221 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000222 }
223
Andrew Walbranf8d94112021-09-07 11:45:36 +0000224 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
225 /// the `VmInstance` is dropped.
226 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
227 self.vm_state.lock().unwrap().start(self.clone())
228 }
229
Jiyong Parka4eebde2022-07-12 18:01:12 +0900230 /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
231 /// handles the event by updating the state, noityfing the event to clients by calling
232 /// callbacks, and removing temporary files for the VM.
233 fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000234 let result = child.wait();
235 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900236 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
237 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000238 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000239
240 let mut vm_state = self.vm_state.lock().unwrap();
241 *vm_state = VmState::Dead;
242 // Ensure that the mutex is released before calling the callbacks.
243 drop(vm_state);
244
Jiyong Parka4eebde2022-07-12 18:01:12 +0900245 // Read the pipe to see if any failure reason is written
246 let mut failure_reason = String::new();
247 match failure_pipe_read.read_to_string(&mut failure_reason) {
248 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
249 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
250 _ => (),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900251 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000252
Jiyong Parka4eebde2022-07-12 18:01:12 +0900253 // In case of hangup, the pipe doesn't give us any information because the hangup can't be
254 // detected on the VM side (otherwise, it isn't a hangup), but in the
255 // monitor_payload_hangup function below which updates the payload state to Hangup.
256 let failure_reason =
257 if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
258 Cow::from("HANGUP")
259 } else {
260 Cow::from(failure_reason)
261 };
262
Jiyong Parke558ab12022-07-07 20:18:55 +0900263 self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
Jiyong Parka4eebde2022-07-12 18:01:12 +0900264 self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_reason));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000265
266 // Delete temporary files.
267 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000268 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000269 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000270 }
271
Jiyong Parka4eebde2022-07-12 18:01:12 +0900272 /// Waits until payload is started, or timeout expires. When timeout occurs, kill
273 /// the VM to prevent indefinite hangup and update the payload_state accordingly.
274 fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
275 debug!("Starting to monitor hangup for Microdroid({})", child.id());
276 let (_, result) = self
277 .payload_state_updated
278 .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
279 *s < PayloadState::Started
280 })
281 .unwrap();
282 let child_still_running = child.try_wait().ok() == Some(None);
283 if result.timed_out() && child_still_running {
284 error!(
285 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
286 child.id(),
287 BOOT_HANGUP_TIMEOUT.as_secs()
288 );
289 self.update_payload_state(PayloadState::Hangup).unwrap();
290 if let Err(e) = self.kill() {
291 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
292 }
293 }
294 }
295
Andrew Walbran6b650662021-09-07 13:13:23 +0000296 /// Returns the last reported state of the VM payload.
297 pub fn payload_state(&self) -> PayloadState {
298 *self.payload_state.lock().unwrap()
299 }
300
301 /// Updates the payload state to the given value, if it is a valid state transition.
302 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
303 let mut state_locked = self.payload_state.lock().unwrap();
304 // Only allow forward transitions, e.g. from starting to started or finished, not back in
305 // the other direction.
306 if new_state > *state_locked {
307 *state_locked = new_state;
Jiyong Parka4eebde2022-07-12 18:01:12 +0900308 self.payload_state_updated.notify_all();
Andrew Walbran6b650662021-09-07 13:13:23 +0000309 Ok(())
310 } else {
311 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
312 }
313 }
314
Andrew Walbranf8d94112021-09-07 11:45:36 +0000315 /// Kills the crosvm instance, if it is running.
Inseob Kima446f802022-07-11 19:46:37 +0900316 pub fn kill(&self) -> Result<(), Error> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000317 let vm_state = &*self.vm_state.lock().unwrap();
318 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900319 let id = child.id();
320 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000321 // TODO: Talk to crosvm to shutdown cleanly.
322 if let Err(e) = child.kill() {
Inseob Kima446f802022-07-11 19:46:37 +0900323 bail!("Error killing crosvm({}) instance: {}", id, e);
324 } else {
325 Ok(())
Andrew Walbranf8d94112021-09-07 11:45:36 +0000326 }
Inseob Kima446f802022-07-11 19:46:37 +0900327 } else {
328 bail!("VM is not running")
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000329 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000330 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900331
332 /// Checks if ramdump has been created. If so, send a notification to the user with the handle
333 /// to read the ramdump.
334 fn handle_ramdump(&self) -> Result<(), Error> {
335 let ramdump_path = self.temporary_directory.join("ramdump");
336 if std::fs::metadata(&ramdump_path)?.len() > 0 {
337 let ramdump = File::open(&ramdump_path)
338 .context(format!("Failed to open ramdump {:?} for reading", &ramdump_path))?;
339 self.callbacks.callback_on_ramdump(self.cid, ramdump);
Jiyong Park1612b902022-08-22 14:47:39 +0900340
341 Self::send_ramdump_to_tombstoned(&ramdump_path)?;
Jiyong Parke558ab12022-07-07 20:18:55 +0900342 }
343 Ok(())
344 }
Jiyong Park1612b902022-08-22 14:47:39 +0900345
346 fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
347 let mut input = File::open(ramdump_path)
348 .context(format!("Failed to open raudmp {:?} for reading", ramdump_path))?;
349
350 let pid = std::process::id() as i32;
351 let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
352 .context("Failed to connect to tombstoned")?;
353 let mut output = conn
354 .text_output
355 .as_ref()
356 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
357
358 std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
359 info!("Ramdump {:?} sent to tombstoned", ramdump_path);
360
361 conn.notify_completion()?;
362 Ok(())
363 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000364}
365
Andrew Walbranb27681f2022-02-23 15:11:52 +0000366fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000367 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000368 match failure_reason {
369 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
370 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
371 }
372 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
373 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
374 }
375 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
376 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
377 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
378 }
Inseob Kim272f5722022-06-13 17:14:51 +0900379 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
380 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
381 }
382 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
383 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
384 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
385 }
386 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
387 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
388 }
389 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
390 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
391 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900392 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000393 _ => {}
394 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000395 match status.code() {
396 None => DeathReason::KILLED,
397 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000398 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000399 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000400 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000401 Some(_) => DeathReason::UNKNOWN,
402 }
403 } else {
404 DeathReason::INFRASTRUCTURE_ERROR
405 }
406}
407
Andrew Walbrand3a84182021-09-07 14:48:52 +0000408/// Starts an instance of `crosvm` to manage a new VM.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000409fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000410 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000411
412 let mut command = Command::new(CROSVM_PATH);
413 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000414 command
415 .arg("--extended-status")
416 .arg("run")
417 .arg("--disable-sandbox")
418 .arg("--cid")
419 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000420
Andrew Walbranf8650422021-06-09 15:54:09 +0000421 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000422 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000423
424 // 3 virtio-console devices + vsock = 4.
425 let virtio_pci_device_count = 4 + config.disks.len();
426 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
427 // enough.
428 let swiotlb_size_mib = 2 * virtio_pci_device_count;
429 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000430 }
431
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000432 if let Some(memory_mib) = config.memory_mib {
433 command.arg("--mem").arg(memory_mib.to_string());
434 }
435
Jiyong Park032615f2022-01-10 13:55:34 +0900436 if let Some(cpus) = config.cpus {
437 command.arg("--cpus").arg(cpus.to_string());
438 }
439
440 if let Some(cpu_affinity) = config.cpu_affinity {
441 command.arg("--cpu-affinity").arg(cpu_affinity);
442 }
443
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900444 if !config.task_profiles.is_empty() {
445 command.arg("--task-profiles").arg(config.task_profiles.join(","));
446 }
447
Jiyong Parkfa91d702021-10-18 23:51:39 +0900448 // Keep track of what file descriptors should be mapped to the crosvm process.
449 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
450
Jiyong Park747d6362021-10-19 17:12:52 +0900451 // Setup the serial devices.
452 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000453 // 2. uart device: used to report the reason for the VM failing.
454 // 3. virtio-console device: used as the console device where kmsg is redirected to
Jiyong Park4afe2012022-07-08 05:38:49 +0900455 // 4. virtio-console device: used as the ramdump output
Andrew Walbranb27681f2022-02-23 15:11:52 +0000456 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900457 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900458 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
459 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000460 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
461 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
462 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parke558ab12022-07-07 20:18:55 +0900463 let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900464
Jiyong Park747d6362021-10-19 17:12:52 +0900465 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
466 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
467 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
468 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900469 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000470 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
471 // /dev/ttyS1
472 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900473 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900474 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Park4afe2012022-07-08 05:38:49 +0900475 // /dev/hvc1
476 command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900477 // /dev/hvc2
478 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000479
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000480 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000481 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000482 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000483
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000484 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000485 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000486 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000487
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000488 if let Some(params) = &config.params {
489 command.arg("--params").arg(params);
490 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000491
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000492 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000493 command
494 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000495 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000496 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000497
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000498 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000499 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000500 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000501
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000502 debug!("Preserving FDs {:?}", preserved_fds);
503 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000504
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000505 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000506 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900507 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000508 Ok(result)
509}
510
511/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000512fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000513 if config.bootloader.is_none() && config.kernel.is_none() {
514 bail!("VM must have either a bootloader or a kernel image.");
515 }
516 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
517 bail!("Can't have both bootloader and kernel/initrd image.");
518 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900519 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
520 if !config.platform_version.matches(&version) {
521 bail!(
522 "Incompatible platform version. The config is compatible with platform version(s) \
523 {}, but the actual platform version is {}",
524 config.platform_version,
525 version
526 );
527 }
528
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000529 Ok(())
530}
531
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000532/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
533/// "/proc/self/fd/N" where N is the file descriptor.
534fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000535 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000536 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000537 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000538}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000539
540/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
541/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
542fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
543 if let Some(file) = file {
544 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
545 } else {
546 "type=sink".to_string()
547 }
548}
549
550/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
551fn create_pipe() -> Result<(File, File), Error> {
552 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
553 // SAFETY: We are the sole owners of these fds as they were just created.
554 let read_fd = unsafe { File::from_raw_fd(raw_read) };
555 let write_fd = unsafe { File::from_raw_fd(raw_write) };
556 Ok((read_fd, write_fd))
557}