• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 use crate::aidl::VirtualMachineCallbacks;
18 use crate::Cid;
19 use anyhow::{bail, Error};
20 use command_fds::CommandFdExt;
21 use log::{debug, error, info};
22 use semver::{Version, VersionReq};
23 use nix::{fcntl::OFlag, unistd::pipe2};
24 use shared_child::SharedChild;
25 use std::fs::{remove_dir_all, File};
26 use std::io::{self, Read};
27 use std::mem;
28 use std::num::NonZeroU32;
29 use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
30 use std::path::PathBuf;
31 use std::process::{Command, ExitStatus};
32 use std::sync::{Arc, Mutex};
33 use std::thread;
34 use vsock::VsockStream;
35 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DeathReason::DeathReason;
36 use android_system_virtualmachineservice::binder::Strong;
37 use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
38 
39 const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
40 
41 /// Version of the platform that crosvm currently implements. The format follows SemVer. This
42 /// should be updated when there is a platform change in the crosvm side. Having this value here is
43 /// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
44 /// APEX.
45 const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
46 
47 /// The exit status which crosvm returns when it has an error starting a VM.
48 const CROSVM_ERROR_STATUS: i32 = 1;
49 /// The exit status which crosvm returns when a VM requests a reboot.
50 const CROSVM_REBOOT_STATUS: i32 = 32;
51 /// The exit status which crosvm returns when it crashes due to an error.
52 const CROSVM_CRASH_STATUS: i32 = 33;
53 
54 /// Configuration for a VM to run with crosvm.
55 #[derive(Debug)]
56 pub struct CrosvmConfig {
57     pub cid: Cid,
58     pub bootloader: Option<File>,
59     pub kernel: Option<File>,
60     pub initrd: Option<File>,
61     pub disks: Vec<DiskFile>,
62     pub params: Option<String>,
63     pub protected: bool,
64     pub memory_mib: Option<NonZeroU32>,
65     pub cpus: Option<NonZeroU32>,
66     pub cpu_affinity: Option<String>,
67     pub task_profiles: Vec<String>,
68     pub console_fd: Option<File>,
69     pub log_fd: Option<File>,
70     pub indirect_files: Vec<File>,
71     pub platform_version: VersionReq,
72 }
73 
74 /// A disk image to pass to crosvm for a VM.
75 #[derive(Debug)]
76 pub struct DiskFile {
77     pub image: File,
78     pub writable: bool,
79 }
80 
81 /// The lifecycle state which the payload in the VM has reported itself to be in.
82 ///
83 /// Note that the order of enum variants is significant; only forward transitions are allowed by
84 /// [`VmInstance::update_payload_state`].
85 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
86 pub enum PayloadState {
87     Starting,
88     Started,
89     Ready,
90     Finished,
91 }
92 
93 /// The current state of the VM itself.
94 #[derive(Debug)]
95 pub enum VmState {
96     /// The VM has not yet tried to start.
97     NotStarted {
98         ///The configuration needed to start the VM, if it has not yet been started.
99         config: CrosvmConfig,
100     },
101     /// The VM has been started.
102     Running {
103         /// The crosvm child process.
104         child: Arc<SharedChild>,
105     },
106     /// The VM died or was killed.
107     Dead,
108     /// The VM failed to start.
109     Failed,
110 }
111 
112 impl VmState {
113     /// Tries to start the VM, if it is in the `NotStarted` state.
114     ///
115     /// Returns an error if the VM is in the wrong state, or fails to start.
start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error>116     fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
117         let state = mem::replace(self, VmState::Failed);
118         if let VmState::NotStarted { config } = state {
119             let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
120 
121             // If this fails and returns an error, `self` will be left in the `Failed` state.
122             let child = Arc::new(run_vm(config, failure_pipe_write)?);
123 
124             let child_clone = child.clone();
125             thread::spawn(move || {
126                 instance.monitor(child_clone, failure_pipe_read);
127             });
128 
129             // If it started correctly, update the state.
130             *self = VmState::Running { child };
131             Ok(())
132         } else {
133             *self = state;
134             bail!("VM already started or failed")
135         }
136     }
137 }
138 
139 /// Information about a particular instance of a VM which may be running.
140 #[derive(Debug)]
141 pub struct VmInstance {
142     /// The current state of the VM.
143     pub vm_state: Mutex<VmState>,
144     /// The CID assigned to the VM for vsock communication.
145     pub cid: Cid,
146     /// Whether the VM is a protected VM.
147     pub protected: bool,
148     /// Directory of temporary files used by the VM while it is running.
149     pub temporary_directory: PathBuf,
150     /// The UID of the process which requested the VM.
151     pub requester_uid: u32,
152     /// The SID of the process which requested the VM.
153     pub requester_sid: String,
154     /// The PID of the process which requested the VM. Note that this process may no longer exist
155     /// and the PID may have been reused for a different process, so this should not be trusted.
156     pub requester_debug_pid: i32,
157     /// Callbacks to clients of the VM.
158     pub callbacks: VirtualMachineCallbacks,
159     /// Input/output stream of the payload run in the VM.
160     pub stream: Mutex<Option<VsockStream>>,
161     /// VirtualMachineService binder object for the VM.
162     pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
163     /// The latest lifecycle state which the payload reported itself to be in.
164     payload_state: Mutex<PayloadState>,
165 }
166 
167 impl VmInstance {
168     /// Validates the given config and creates a new `VmInstance` but doesn't start running it.
new( config: CrosvmConfig, temporary_directory: PathBuf, requester_uid: u32, requester_sid: String, requester_debug_pid: i32, ) -> Result<VmInstance, Error>169     pub fn new(
170         config: CrosvmConfig,
171         temporary_directory: PathBuf,
172         requester_uid: u32,
173         requester_sid: String,
174         requester_debug_pid: i32,
175     ) -> Result<VmInstance, Error> {
176         validate_config(&config)?;
177         let cid = config.cid;
178         let protected = config.protected;
179         Ok(VmInstance {
180             vm_state: Mutex::new(VmState::NotStarted { config }),
181             cid,
182             protected,
183             temporary_directory,
184             requester_uid,
185             requester_sid,
186             requester_debug_pid,
187             callbacks: Default::default(),
188             stream: Mutex::new(None),
189             vm_service: Mutex::new(None),
190             payload_state: Mutex::new(PayloadState::Starting),
191         })
192     }
193 
194     /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
195     /// the `VmInstance` is dropped.
start(self: &Arc<Self>) -> Result<(), Error>196     pub fn start(self: &Arc<Self>) -> Result<(), Error> {
197         self.vm_state.lock().unwrap().start(self.clone())
198     }
199 
200     /// Waits for the crosvm child process to finish, then marks the VM as no longer running and
201     /// calls any callbacks.
202     ///
203     /// This takes a separate reference to the `SharedChild` rather than using the one in
204     /// `self.vm_state` to avoid holding the lock on `vm_state` while it is running.
monitor(&self, child: Arc<SharedChild>, mut failure_pipe_read: File)205     fn monitor(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
206         let result = child.wait();
207         match &result {
208             Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
209             Ok(status) => info!("crosvm({}) exited with status {}", child.id(), status),
210         }
211 
212         let mut vm_state = self.vm_state.lock().unwrap();
213         *vm_state = VmState::Dead;
214         // Ensure that the mutex is released before calling the callbacks.
215         drop(vm_state);
216 
217         let mut failure_string = String::new();
218         let failure_read_result = failure_pipe_read.read_to_string(&mut failure_string);
219         if let Err(e) = &failure_read_result {
220             error!("Error reading VM failure reason from pipe: {}", e);
221         }
222         if !failure_string.is_empty() {
223             info!("VM returned failure reason '{}'", failure_string);
224         }
225 
226         self.callbacks.callback_on_died(self.cid, death_reason(&result, &failure_string));
227 
228         // Delete temporary files.
229         if let Err(e) = remove_dir_all(&self.temporary_directory) {
230             error!("Error removing temporary directory {:?}: {}", self.temporary_directory, e);
231         }
232     }
233 
234     /// Returns the last reported state of the VM payload.
payload_state(&self) -> PayloadState235     pub fn payload_state(&self) -> PayloadState {
236         *self.payload_state.lock().unwrap()
237     }
238 
239     /// Updates the payload state to the given value, if it is a valid state transition.
update_payload_state(&self, new_state: PayloadState) -> Result<(), Error>240     pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
241         let mut state_locked = self.payload_state.lock().unwrap();
242         // Only allow forward transitions, e.g. from starting to started or finished, not back in
243         // the other direction.
244         if new_state > *state_locked {
245             *state_locked = new_state;
246             Ok(())
247         } else {
248             bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
249         }
250     }
251 
252     /// Kills the crosvm instance, if it is running.
kill(&self)253     pub fn kill(&self) {
254         let vm_state = &*self.vm_state.lock().unwrap();
255         if let VmState::Running { child } = vm_state {
256             let id = child.id();
257             debug!("Killing crosvm({})", id);
258             // TODO: Talk to crosvm to shutdown cleanly.
259             if let Err(e) = child.kill() {
260                 error!("Error killing crosvm({}) instance: {}", id, e);
261             }
262         }
263     }
264 }
265 
death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason266 fn death_reason(result: &Result<ExitStatus, io::Error>, failure_reason: &str) -> DeathReason {
267     if let Ok(status) = result {
268         match failure_reason {
269             "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
270                 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
271             }
272             "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
273                 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
274             }
275             "BOOTLOADER_PUBLIC_KEY_MISMATCH" => return DeathReason::BOOTLOADER_PUBLIC_KEY_MISMATCH,
276             "BOOTLOADER_INSTANCE_IMAGE_CHANGED" => {
277                 return DeathReason::BOOTLOADER_INSTANCE_IMAGE_CHANGED
278             }
279             _ => {}
280         }
281         match status.code() {
282             None => DeathReason::KILLED,
283             Some(0) => DeathReason::SHUTDOWN,
284             Some(CROSVM_ERROR_STATUS) => DeathReason::ERROR,
285             Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
286             Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
287             Some(_) => DeathReason::UNKNOWN,
288         }
289     } else {
290         DeathReason::INFRASTRUCTURE_ERROR
291     }
292 }
293 
294 /// Starts an instance of `crosvm` to manage a new VM.
run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error>295 fn run_vm(config: CrosvmConfig, failure_pipe_write: File) -> Result<SharedChild, Error> {
296     validate_config(&config)?;
297 
298     let mut command = Command::new(CROSVM_PATH);
299     // TODO(qwandor): Remove --disable-sandbox.
300     command
301         .arg("--extended-status")
302         .arg("run")
303         .arg("--disable-sandbox")
304         .arg("--cid")
305         .arg(config.cid.to_string());
306 
307     if config.protected {
308         command.arg("--protected-vm");
309 
310         // 3 virtio-console devices + vsock = 4.
311         let virtio_pci_device_count = 4 + config.disks.len();
312         // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
313         // enough.
314         let swiotlb_size_mib = 2 * virtio_pci_device_count;
315         command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
316     }
317 
318     if let Some(memory_mib) = config.memory_mib {
319         command.arg("--mem").arg(memory_mib.to_string());
320     }
321 
322     if let Some(cpus) = config.cpus {
323         command.arg("--cpus").arg(cpus.to_string());
324     }
325 
326     if let Some(cpu_affinity) = config.cpu_affinity {
327         command.arg("--cpu-affinity").arg(cpu_affinity);
328     }
329 
330     if !config.task_profiles.is_empty() {
331         command.arg("--task-profiles").arg(config.task_profiles.join(","));
332     }
333 
334     // Keep track of what file descriptors should be mapped to the crosvm process.
335     let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
336 
337     // Setup the serial devices.
338     // 1. uart device: used as the output device by bootloaders and as early console by linux
339     // 2. uart device: used to report the reason for the VM failing.
340     // 3. virtio-console device: used as the console device where kmsg is redirected to
341     // 4. virtio-console device: used as the androidboot.console device (not used currently)
342     // 5. virtio-console device: used as the logcat output
343     //
344     // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
345     // written there is discarded.
346     let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
347     let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
348     let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
349 
350     // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
351     // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
352     // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
353     // doesn't have the issue.
354     // /dev/ttyS0
355     command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
356     // /dev/ttyS1
357     command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
358     // /dev/hvc0
359     command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
360     // /dev/hvc1 (not used currently)
361     command.arg("--serial=type=sink,hardware=virtio-console,num=2");
362     // /dev/hvc2
363     command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
364 
365     if let Some(bootloader) = &config.bootloader {
366         command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
367     }
368 
369     if let Some(initrd) = &config.initrd {
370         command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
371     }
372 
373     if let Some(params) = &config.params {
374         command.arg("--params").arg(params);
375     }
376 
377     for disk in &config.disks {
378         command
379             .arg(if disk.writable { "--rwdisk" } else { "--disk" })
380             .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
381     }
382 
383     if let Some(kernel) = &config.kernel {
384         command.arg(add_preserved_fd(&mut preserved_fds, kernel));
385     }
386 
387     debug!("Preserving FDs {:?}", preserved_fds);
388     command.preserved_fds(preserved_fds);
389 
390     info!("Running {:?}", command);
391     let result = SharedChild::spawn(&mut command)?;
392     debug!("Spawned crosvm({}).", result.id());
393     Ok(result)
394 }
395 
396 /// Ensure that the configuration has a valid combination of fields set, or return an error if not.
validate_config(config: &CrosvmConfig) -> Result<(), Error>397 fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
398     if config.bootloader.is_none() && config.kernel.is_none() {
399         bail!("VM must have either a bootloader or a kernel image.");
400     }
401     if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
402         bail!("Can't have both bootloader and kernel/initrd image.");
403     }
404     let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
405     if !config.platform_version.matches(&version) {
406         bail!(
407             "Incompatible platform version. The config is compatible with platform version(s) \
408               {}, but the actual platform version is {}",
409             config.platform_version,
410             version
411         );
412     }
413 
414     Ok(())
415 }
416 
417 /// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
418 /// "/proc/self/fd/N" where N is the file descriptor.
add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String419 fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &File) -> String {
420     let fd = file.as_raw_fd();
421     preserved_fds.push(fd);
422     format!("/proc/self/fd/{}", fd)
423 }
424 
425 /// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
426 /// string for a crosvm `--serial` flag. If `file` is none, creates a dummy sink device.
format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String427 fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
428     if let Some(file) = file {
429         format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
430     } else {
431         "type=sink".to_string()
432     }
433 }
434 
435 /// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
create_pipe() -> Result<(File, File), Error>436 fn create_pipe() -> Result<(File, File), Error> {
437     let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
438     // SAFETY: We are the sole owners of these fds as they were just created.
439     let read_fd = unsafe { File::from_raw_fd(raw_read) };
440     let write_fd = unsafe { File::from_raw_fd(raw_write) };
441     Ok((read_fd, write_fd))
442 }
443