blob: 23719a78c78ab015bb978574c991002cdb210f91 [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;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use anyhow::{bail, 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};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000032use std::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;
Inseob Kimc7d28c72021-10-25 14:28:10 +000039use android_system_virtualmachineservice::binder::Strong;
40use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000041
42const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
43
Jiyong Parkdcf17412022-02-08 15:07:23 +090044/// 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.
48const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
49
Andrew Walbrand15c5632022-02-03 13:38:31 +000050/// The exit status which crosvm returns when it has an error starting a VM.
51const CROSVM_ERROR_STATUS: i32 = 1;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000052/// The exit status which crosvm returns when a VM requests a reboot.
53const CROSVM_REBOOT_STATUS: i32 = 32;
Andrew Walbrand15c5632022-02-03 13:38:31 +000054/// The exit status which crosvm returns when it crashes due to an error.
55const CROSVM_CRASH_STATUS: i32 = 33;
Andrew Walbranc92d35f2022-01-12 12:45:19 +000056
Jiyong Parke6ed0f92022-06-22 00:13:00 +090057lazy_static! {
58 /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
59 /// triggered.
Alan Stokesc3f2ac22022-06-23 12:19:46 +010060 static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
Jiyong Parke6ed0f92022-06-22 00:13:00 +090061 // 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 Walbranf5fbb7d2021-05-12 17:15:48 +000068/// Configuration for a VM to run with crosvm.
69#[derive(Debug)]
Andrew Walbrand3a84182021-09-07 14:48:52 +000070pub struct CrosvmConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071 pub cid: Cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +000072 pub bootloader: Option<File>,
73 pub kernel: Option<File>,
74 pub initrd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075 pub disks: Vec<DiskFile>,
76 pub params: Option<String>,
Andrew Walbranf8650422021-06-09 15:54:09 +000077 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000078 pub memory_mib: Option<NonZeroU32>,
Jiyong Park032615f2022-01-10 13:55:34 +090079 pub cpus: Option<NonZeroU32>,
80 pub cpu_affinity: Option<String>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090081 pub task_profiles: Vec<String>,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090082 pub console_fd: Option<File>,
Andrew Walbrand3a84182021-09-07 14:48:52 +000083 pub log_fd: Option<File>,
84 pub indirect_files: Vec<File>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090085 pub platform_version: VersionReq,
Jiyong Parke6ed0f92022-06-22 00:13:00 +090086 pub detect_hangup: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087}
88
89/// A disk image to pass to crosvm for a VM.
90#[derive(Debug)]
91pub struct DiskFile {
92 pub image: File,
93 pub writable: bool,
94}
95
Andrew Walbran6b650662021-09-07 13:13:23 +000096/// The lifecycle state which the payload in the VM has reported itself to be in.
97///
98/// Note that the order of enum variants is significant; only forward transitions are allowed by
99/// [`VmInstance::update_payload_state`].
100#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
101pub enum PayloadState {
102 Starting,
103 Started,
104 Ready,
105 Finished,
106}
107
Andrew Walbranf8d94112021-09-07 11:45:36 +0000108/// The current state of the VM itself.
109#[derive(Debug)]
110pub enum VmState {
111 /// The VM has not yet tried to start.
112 NotStarted {
113 ///The configuration needed to start the VM, if it has not yet been started.
114 config: CrosvmConfig,
115 },
116 /// The VM has been started.
117 Running {
118 /// The crosvm child process.
119 child: Arc<SharedChild>,
120 },
121 /// The VM died or was killed.
122 Dead,
123 /// The VM failed to start.
124 Failed,
125}
126
127impl VmState {
128 /// Tries to start the VM, if it is in the `NotStarted` state.
129 ///
130 /// Returns an error if the VM is in the wrong state, or fails to start.
131 fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
132 let state = mem::replace(self, VmState::Failed);
133 if let VmState::NotStarted { config } = state {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900134 let detect_hangup = config.detect_hangup;
Andrew Walbranb27681f2022-02-23 15:11:52 +0000135 let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
136
Andrew Walbranf8d94112021-09-07 11:45:36 +0000137 // If this fails and returns an error, `self` will be left in the `Failed` state.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000138 let child = Arc::new(run_vm(config, failure_pipe_write)?);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000139
140 let child_clone = child.clone();
141 thread::spawn(move || {
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900142 instance.monitor(child_clone, failure_pipe_read, detect_hangup);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000143 });
144
145 // If it started correctly, update the state.
146 *self = VmState::Running { child };
147 Ok(())
148 } else {
149 *self = state;
150 bail!("VM already started or failed")
151 }
152 }
153}
154
155/// Information about a particular instance of a VM which may be running.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000156#[derive(Debug)]
157pub struct VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000158 /// The current state of the VM.
159 pub vm_state: Mutex<VmState>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000160 /// The CID assigned to the VM for vsock communication.
161 pub cid: Cid,
Andrew Walbranf8650422021-06-09 15:54:09 +0000162 /// Whether the VM is a protected VM.
163 pub protected: bool,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 /// Directory of temporary files used by the VM while it is running.
165 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000166 /// The UID of the process which requested the VM.
167 pub requester_uid: u32,
168 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +0000169 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000170 /// The PID of the process which requested the VM. Note that this process may no longer exist
171 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +0000172 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000173 /// Callbacks to clients of the VM.
174 pub callbacks: VirtualMachineCallbacks,
Inseob Kim7f61fe72021-08-20 20:50:47 +0900175 /// Input/output stream of the payload run in the VM.
176 pub stream: Mutex<Option<VsockStream>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000177 /// VirtualMachineService binder object for the VM.
178 pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
Andrew Walbran6b650662021-09-07 13:13:23 +0000179 /// The latest lifecycle state which the payload reported itself to be in.
180 payload_state: Mutex<PayloadState>,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900181 /// Represents the condition that payload_state becomes Started
182 payload_started: Condvar,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000183}
184
185impl VmInstance {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000186 /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
187 pub fn new(
Andrew Walbrand3a84182021-09-07 14:48:52 +0000188 config: CrosvmConfig,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000189 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000190 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000191 requester_sid: String,
192 requester_debug_pid: i32,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000193 ) -> Result<VmInstance, Error> {
194 validate_config(&config)?;
Andrew Walbrand3a84182021-09-07 14:48:52 +0000195 let cid = config.cid;
196 let protected = config.protected;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000197 Ok(VmInstance {
198 vm_state: Mutex::new(VmState::NotStarted { config }),
Andrew Walbrand3a84182021-09-07 14:48:52 +0000199 cid,
200 protected,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000201 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000202 requester_uid,
203 requester_sid,
204 requester_debug_pid,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000205 callbacks: Default::default(),
206 stream: Mutex::new(None),
Inseob Kimc7d28c72021-10-25 14:28:10 +0000207 vm_service: Mutex::new(None),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000208 payload_state: Mutex::new(PayloadState::Starting),
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900209 payload_started: Condvar::new(),
Andrew Walbranf8d94112021-09-07 11:45:36 +0000210 })
Andrew Walbrandae07162021-03-12 17:05:20 +0000211 }
212
Andrew Walbranf8d94112021-09-07 11:45:36 +0000213 /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
214 /// the `VmInstance` is dropped.
215 pub fn start(self: &Arc<Self>) -> Result<(), Error> {
216 self.vm_state.lock().unwrap().start(self.clone())
217 }
218
219 /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900220 /// calls any callbacks. If `detect_hangup` is optionally set to true, waits for the start of
221 /// payload in the crosvm process. If that doesn't occur within a BOOT_HANGUP_TIMEOUT, declare
222 /// it as a hangup and forcibly kill the process.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000223 ///
224 /// This takes a separate reference to the `SharedChild` rather than using the one in
225 /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900226 fn monitor(&self, child: Arc<SharedChild>, mut failure_pipe_read: File, detect_hangup: bool) {
227 let hungup = if detect_hangup {
228 // Wait until payload is started or the crosvm process terminates. The checking of the
229 // child process is needed because otherwise we will be waiting for a condition that
230 // will never be satisfied (because crosvm is the one who can make the condition true).
231 let state = self.payload_state.lock().unwrap();
232 let (_, result) = self
233 .payload_started
234 .wait_timeout_while(state, *BOOT_HANGUP_TIMEOUT, |state| {
235 *state < PayloadState::Started && child.try_wait().is_ok()
236 })
237 .unwrap();
238 if result.timed_out() {
239 error!(
240 "Microdroid failed to start payload within {} secs timeout. Shutting down",
241 BOOT_HANGUP_TIMEOUT.as_secs()
242 );
243 self.kill();
244 true
245 } else {
246 false
247 }
248 } else {
249 false
250 };
251
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000252 let result = child.wait();
253 match &result {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900254 Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
255 Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
Andrew Walbrandae07162021-03-12 17:05:20 +0000256 }
Andrew Walbranf8d94112021-09-07 11:45:36 +0000257
258 let mut vm_state = self.vm_state.lock().unwrap();
259 *vm_state = VmState::Dead;
260 // Ensure that the mutex is released before calling the callbacks.
261 drop(vm_state);
262
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900263 let failure_string = if hungup {
264 Cow::from("HANGUP")
265 } else {
266 let mut s = String::new();
267 match failure_pipe_read.read_to_string(&mut s) {
268 Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
269 Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &s),
270 _ => (),
271 };
272 Cow::from(s)
273 };
Andrew Walbranb27681f2022-02-23 15:11:52 +0000274
275 self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_string));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000276
277 // Delete temporary files.
278 if let Err(e) = remove_dir_all(&self.temporary_directory) {
Andrew Walbran806f1542021-06-10 14:07:12 +0000279 error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000280 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000281 }
282
Andrew Walbran6b650662021-09-07 13:13:23 +0000283 /// Returns the last reported state of the VM payload.
284 pub fn payload_state(&self) -> PayloadState {
285 *self.payload_state.lock().unwrap()
286 }
287
288 /// Updates the payload state to the given value, if it is a valid state transition.
289 pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
290 let mut state_locked = self.payload_state.lock().unwrap();
291 // Only allow forward transitions, e.g. from starting to started or finished, not back in
292 // the other direction.
293 if new_state > *state_locked {
294 *state_locked = new_state;
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900295 if new_state >= PayloadState::Started {
296 self.payload_started.notify_all();
297 }
Andrew Walbran6b650662021-09-07 13:13:23 +0000298 Ok(())
299 } else {
300 bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
301 }
302 }
303
Andrew Walbranf8d94112021-09-07 11:45:36 +0000304 /// Kills the crosvm instance, if it is running.
Andrew Walbrandae07162021-03-12 17:05:20 +0000305 pub fn kill(&self) {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000306 let vm_state = &*self.vm_state.lock().unwrap();
307 if let VmState::Running { child } = vm_state {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900308 let id = child.id();
309 debug!("Killing crosvm({})", id);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000310 // TODO: Talk to crosvm to shutdown cleanly.
311 if let Err(e) = child.kill() {
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900312 error!("Error killing crosvm({}) instance: {}", id, e);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000313 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000314 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000315 }
316}
317
Andrew Walbranb27681f2022-02-23 15:11:52 +0000318fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000319 if let Ok(status) = result {
Andrew Walbranb27681f2022-02-23 15:11:52 +0000320 match failure_reason {
321 "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
322 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
323 }
324 "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
325 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
326 }
327 "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
328 "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
329 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
330 }
Inseob Kim272f5722022-06-13 17:14:51 +0900331 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
332 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
333 }
334 "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
335 "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
336 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
337 }
338 "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
339 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
340 }
341 "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
342 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
343 }
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900344 "HANGUP" => return DeathReason::HANGUP,
Andrew Walbranb27681f2022-02-23 15:11:52 +0000345 _ => {}
346 }
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000347 match status.code() {
348 None => DeathReason::KILLED,
349 Some(0) => DeathReason::SHUTDOWN,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000350 Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000351 Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
Andrew Walbrand15c5632022-02-03 13:38:31 +0000352 Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000353 Some(_) => DeathReason::UNKNOWN,
354 }
355 } else {
356 DeathReason::INFRASTRUCTURE_ERROR
357 }
358}
359
Andrew Walbrand3a84182021-09-07 14:48:52 +0000360/// Starts an instance of `crosvm` to manage a new VM.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000361fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
Andrew Walbrand3a84182021-09-07 14:48:52 +0000362 validate_config(&config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000363
364 let mut command = Command::new(CROSVM_PATH);
365 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000366 command
367 .arg("--extended-status")
368 .arg("run")
369 .arg("--disable-sandbox")
370 .arg("--cid")
371 .arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000372
Andrew Walbranf8650422021-06-09 15:54:09 +0000373 if config.protected {
David Brazdil86c76fa2022-02-04 15:50:57 +0000374 command.arg("--protected-vm");
Andrew Walbran0b5789f2022-02-04 13:57:57 +0000375
376 // 3 virtio-console devices + vsock = 4.
377 let virtio_pci_device_count = 4 + config.disks.len();
378 // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
379 // enough.
380 let swiotlb_size_mib = 2 * virtio_pci_device_count;
381 command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
Andrew Walbranf8650422021-06-09 15:54:09 +0000382 }
383
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000384 if let Some(memory_mib) = config.memory_mib {
385 command.arg("--mem").arg(memory_mib.to_string());
386 }
387
Jiyong Park032615f2022-01-10 13:55:34 +0900388 if let Some(cpus) = config.cpus {
389 command.arg("--cpus").arg(cpus.to_string());
390 }
391
392 if let Some(cpu_affinity) = config.cpu_affinity {
393 command.arg("--cpu-affinity").arg(cpu_affinity);
394 }
395
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900396 if !config.task_profiles.is_empty() {
397 command.arg("--task-profiles").arg(config.task_profiles.join(","));
398 }
399
Jiyong Parkfa91d702021-10-18 23:51:39 +0900400 // Keep track of what file descriptors should be mapped to the crosvm process.
401 let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
402
Jiyong Park747d6362021-10-19 17:12:52 +0900403 // Setup the serial devices.
404 // 1. uart device: used as the output device by bootloaders and as early console by linux
Andrew Walbranb27681f2022-02-23 15:11:52 +0000405 // 2. uart device: used to report the reason for the VM failing.
406 // 3. virtio-console device: used as the console device where kmsg is redirected to
407 // 4. virtio-console device: used as the androidboot.console device (not used currently)
408 // 5. virtio-console device: used as the logcat output
Jiyong Park747d6362021-10-19 17:12:52 +0900409 //
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900410 // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
411 // written there is discarded.
Andrew Walbranb27681f2022-02-23 15:11:52 +0000412 let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
413 let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
414 let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
Jiyong Parkfa91d702021-10-18 23:51:39 +0900415
Jiyong Park747d6362021-10-19 17:12:52 +0900416 // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
417 // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
418 // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
419 // doesn't have the issue.
Jiyong Parkfa91d702021-10-18 23:51:39 +0900420 // /dev/ttyS0
Andrew Walbranb27681f2022-02-23 15:11:52 +0000421 command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
422 // /dev/ttyS1
423 command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
Jiyong Parkfa91d702021-10-18 23:51:39 +0900424 // /dev/hvc0
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900425 command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
Jiyong Parkae5a4ed2021-11-01 18:36:28 +0900426 // /dev/hvc1 (not used currently)
427 command.arg("--serial=type=sink,hardware=virtio-console,num=2");
428 // /dev/hvc2
429 command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000430
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000431 if let Some(bootloader) = &config.bootloader {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000432 command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000433 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000434
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000435 if let Some(initrd) = &config.initrd {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000436 command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000437 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000438
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000439 if let Some(params) = &config.params {
440 command.arg("--params").arg(params);
441 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000442
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000443 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000444 command
445 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000446 .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000447 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000448
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000449 if let Some(kernel) = &config.kernel {
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000450 command.arg(add_preserved_fd(&mut preserved_fds, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000451 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000452
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000453 debug!("Preserving FDs {:?}", preserved_fds);
454 command.preserved_fds(preserved_fds);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000455
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000456 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000457 let result = SharedChild::spawn(&mut command)?;
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900458 debug!("Spawned crosvm({}).", result.id());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000459 Ok(result)
460}
461
462/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000463fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000464 if config.bootloader.is_none() && config.kernel.is_none() {
465 bail!("VM must have either a bootloader or a kernel image.");
466 }
467 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
468 bail!("Can't have both bootloader and kernel/initrd image.");
469 }
Jiyong Parkdcf17412022-02-08 15:07:23 +0900470 let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
471 if !config.platform_version.matches(&version) {
472 bail!(
473 "Incompatible platform version. The config is compatible with platform version(s) \
474 {}, but the actual platform version is {}",
475 config.platform_version,
476 version
477 );
478 }
479
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000480 Ok(())
481}
482
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000483/// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
484/// "/proc/self/fd/N" where N is the file descriptor.
485fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000486 let fd = file.as_raw_fd();
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000487 preserved_fds.push(fd);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000488 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000489}
Andrew Walbranb27681f2022-02-23 15:11:52 +0000490
491/// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
492/// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
493fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
494 if let Some(file) = file {
495 format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
496 } else {
497 "type=sink".to_string()
498 }
499}
500
501/// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
502fn create_pipe() -> Result<(File, File), Error> {
503 let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
504 // SAFETY: We are the sole owners of these fds as they were just created.
505 let read_fd = unsafe { File::from_raw_fd(raw_read) };
506 let write_fd = unsafe { File::from_raw_fd(raw_write) };
507 Ok((read_fd, write_fd))
508}