• 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::{remove_temporary_files, Cid, VirtualMachineCallbacks};
18 use crate::atom::{get_num_cpus, write_vm_exited_stats_sync};
19 use crate::debug_config::DebugConfig;
20 use anyhow::{anyhow, bail, Context, Error, Result};
21 use command_fds::CommandFdExt;
22 use lazy_static::lazy_static;
23 use libc::{sysconf, _SC_CLK_TCK};
24 use log::{debug, error, info};
25 use semver::{Version, VersionReq};
26 use nix::{fcntl::OFlag, unistd::pipe2, unistd::Uid, unistd::User};
27 use regex::{Captures, Regex};
28 use rustutils::system_properties;
29 use shared_child::SharedChild;
30 use std::borrow::Cow;
31 use std::cmp::max;
32 use std::fmt;
33 use std::fs::{read_to_string, File};
34 use std::io::{self, Read};
35 use std::mem;
36 use std::num::{NonZeroU16, NonZeroU32};
37 use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
38 use std::os::unix::process::ExitStatusExt;
39 use std::path::{Path, PathBuf};
40 use std::process::{Command, ExitStatus};
41 use std::sync::{Arc, Condvar, Mutex};
42 use std::time::{Duration, SystemTime};
43 use std::thread::{self, JoinHandle};
44 use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::DeathReason::DeathReason;
45 use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
46     MemoryTrimLevel::MemoryTrimLevel,
47     VirtualMachineAppConfig::DebugLevel::DebugLevel
48 };
49 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IGlobalVmContext::IGlobalVmContext;
50 use binder::Strong;
51 use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
52 use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
53 use rpcbinder::RpcServer;
54 
55 /// external/crosvm
56 use base::AsRawDescriptor;
57 use base::UnixSeqpacketListener;
58 use vm_control::{BalloonControlCommand, VmRequest, VmResponse};
59 
60 const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
61 
62 /// Version of the platform that crosvm currently implements. The format follows SemVer. This
63 /// should be updated when there is a platform change in the crosvm side. Having this value here is
64 /// fine because virtualizationservice and crosvm are supposed to be updated together in the virt
65 /// APEX.
66 const CROSVM_PLATFORM_VERSION: &str = "1.0.0";
67 
68 /// The exit status which crosvm returns when it has an error starting a VM.
69 const CROSVM_START_ERROR_STATUS: i32 = 1;
70 /// The exit status which crosvm returns when a VM requests a reboot.
71 const CROSVM_REBOOT_STATUS: i32 = 32;
72 /// The exit status which crosvm returns when it crashes due to an error.
73 const CROSVM_CRASH_STATUS: i32 = 33;
74 /// The exit status which crosvm returns when vcpu is stalled.
75 const CROSVM_WATCHDOG_REBOOT_STATUS: i32 = 36;
76 /// The size of memory (in MiB) reserved for ramdump
77 const RAMDUMP_RESERVED_MIB: u32 = 17;
78 
79 const MILLIS_PER_SEC: i64 = 1000;
80 
81 const SYSPROP_CUSTOM_PVMFW_PATH: &str = "hypervisor.pvmfw.path";
82 
83 lazy_static! {
84     /// If the VM doesn't move to the Started state within this amount time, a hang-up error is
85     /// triggered.
86     static ref BOOT_HANGUP_TIMEOUT: Duration = if nested_virt::is_nested_virtualization().unwrap() {
87         // Nested virtualization is slow, so we need a longer timeout.
88         Duration::from_secs(300)
89     } else {
90         Duration::from_secs(30)
91     };
92 }
93 
94 /// Configuration for a VM to run with crosvm.
95 #[derive(Debug)]
96 pub struct CrosvmConfig {
97     pub cid: Cid,
98     pub name: String,
99     pub bootloader: Option<File>,
100     pub kernel: Option<File>,
101     pub initrd: Option<File>,
102     pub disks: Vec<DiskFile>,
103     pub params: Option<String>,
104     pub protected: bool,
105     pub debug_config: DebugConfig,
106     pub memory_mib: Option<NonZeroU32>,
107     pub cpus: Option<NonZeroU32>,
108     pub host_cpu_topology: bool,
109     pub task_profiles: Vec<String>,
110     pub console_fd: Option<File>,
111     pub log_fd: Option<File>,
112     pub ramdump: Option<File>,
113     pub indirect_files: Vec<File>,
114     pub platform_version: VersionReq,
115     pub detect_hangup: bool,
116     pub gdb_port: Option<NonZeroU16>,
117 }
118 
119 /// A disk image to pass to crosvm for a VM.
120 #[derive(Debug)]
121 pub struct DiskFile {
122     pub image: File,
123     pub writable: bool,
124 }
125 
126 /// The lifecycle state which the payload in the VM has reported itself to be in.
127 ///
128 /// Note that the order of enum variants is significant; only forward transitions are allowed by
129 /// [`VmInstance::update_payload_state`].
130 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
131 pub enum PayloadState {
132     Starting,
133     Started,
134     Ready,
135     Finished,
136     Hangup, // Hasn't reached to Ready before timeout expires
137 }
138 
139 /// The current state of the VM itself.
140 #[derive(Debug)]
141 pub enum VmState {
142     /// The VM has not yet tried to start.
143     NotStarted {
144         ///The configuration needed to start the VM, if it has not yet been started.
145         config: CrosvmConfig,
146     },
147     /// The VM has been started.
148     Running {
149         /// The crosvm child process.
150         child: Arc<SharedChild>,
151         /// The thread waiting for crosvm to finish.
152         monitor_vm_exit_thread: Option<JoinHandle<()>>,
153     },
154     /// The VM died or was killed.
155     Dead,
156     /// The VM failed to start.
157     Failed,
158 }
159 
160 /// RSS values of VM and CrosVM process itself.
161 #[derive(Copy, Clone, Debug, Default)]
162 pub struct Rss {
163     pub vm: i64,
164     pub crosvm: i64,
165 }
166 
167 /// Metrics regarding the VM.
168 #[derive(Debug, Default)]
169 pub struct VmMetric {
170     /// Recorded timestamp when the VM is started.
171     pub start_timestamp: Option<SystemTime>,
172     /// Update most recent guest_time periodically from /proc/[crosvm pid]/stat while VM is running.
173     pub cpu_guest_time: Option<i64>,
174     /// Update maximum RSS values periodically from /proc/[crosvm pid]/smaps while VM is running.
175     pub rss: Option<Rss>,
176 }
177 
178 impl VmState {
179     /// Tries to start the VM, if it is in the `NotStarted` state.
180     ///
181     /// Returns an error if the VM is in the wrong state, or fails to start.
start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error>182     fn start(&mut self, instance: Arc<VmInstance>) -> Result<(), Error> {
183         let state = mem::replace(self, VmState::Failed);
184         if let VmState::NotStarted { config } = state {
185             let detect_hangup = config.detect_hangup;
186             let (failure_pipe_read, failure_pipe_write) = create_pipe()?;
187 
188             // If this fails and returns an error, `self` will be left in the `Failed` state.
189             let child =
190                 Arc::new(run_vm(config, &instance.crosvm_control_socket_path, failure_pipe_write)?);
191 
192             let instance_monitor_status = instance.clone();
193             let child_monitor_status = child.clone();
194             thread::spawn(move || {
195                 instance_monitor_status.clone().monitor_vm_status(child_monitor_status);
196             });
197 
198             let child_clone = child.clone();
199             let instance_clone = instance.clone();
200             let monitor_vm_exit_thread = Some(thread::spawn(move || {
201                 instance_clone.monitor_vm_exit(child_clone, failure_pipe_read);
202             }));
203 
204             if detect_hangup {
205                 let child_clone = child.clone();
206                 thread::spawn(move || {
207                     instance.monitor_payload_hangup(child_clone);
208                 });
209             }
210 
211             // If it started correctly, update the state.
212             *self = VmState::Running { child, monitor_vm_exit_thread };
213             Ok(())
214         } else {
215             *self = state;
216             bail!("VM already started or failed")
217         }
218     }
219 }
220 
221 /// Internal struct that holds the handles to globally unique resources of a VM.
222 #[derive(Debug)]
223 pub struct VmContext {
224     #[allow(dead_code)] // Keeps the global context alive
225     global_context: Strong<dyn IGlobalVmContext>,
226     #[allow(dead_code)] // Keeps the server alive
227     vm_server: RpcServer,
228 }
229 
230 impl VmContext {
231     /// Construct new VmContext.
new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext232     pub fn new(global_context: Strong<dyn IGlobalVmContext>, vm_server: RpcServer) -> VmContext {
233         VmContext { global_context, vm_server }
234     }
235 }
236 
237 /// Information about a particular instance of a VM which may be running.
238 #[derive(Debug)]
239 pub struct VmInstance {
240     /// The current state of the VM.
241     pub vm_state: Mutex<VmState>,
242     /// Global resources allocated for this VM.
243     #[allow(dead_code)] // Keeps the context alive
244     vm_context: VmContext,
245     /// The CID assigned to the VM for vsock communication.
246     pub cid: Cid,
247     /// Path to crosvm control socket
248     crosvm_control_socket_path: PathBuf,
249     /// The name of the VM.
250     pub name: String,
251     /// Whether the VM is a protected VM.
252     pub protected: bool,
253     /// Directory of temporary files used by the VM while it is running.
254     pub temporary_directory: PathBuf,
255     /// The UID of the process which requested the VM.
256     pub requester_uid: u32,
257     /// The PID of the process which requested the VM. Note that this process may no longer exist
258     /// and the PID may have been reused for a different process, so this should not be trusted.
259     pub requester_debug_pid: i32,
260     /// Callbacks to clients of the VM.
261     pub callbacks: VirtualMachineCallbacks,
262     /// VirtualMachineService binder object for the VM.
263     pub vm_service: Mutex<Option<Strong<dyn IVirtualMachineService>>>,
264     /// Recorded metrics of VM such as timestamp or cpu / memory usage.
265     pub vm_metric: Mutex<VmMetric>,
266     /// The latest lifecycle state which the payload reported itself to be in.
267     payload_state: Mutex<PayloadState>,
268     /// Represents the condition that payload_state was updated
269     payload_state_updated: Condvar,
270     /// The human readable name of requester_uid
271     requester_uid_name: String,
272 }
273 
274 impl fmt::Display for VmInstance {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result275     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276         let adj = if self.protected { "Protected" } else { "Non-protected" };
277         write!(
278             f,
279             "{} virtual machine \"{}\" (owner: {}, cid: {})",
280             adj, self.name, self.requester_uid_name, self.cid
281         )
282     }
283 }
284 
285 impl VmInstance {
286     /// 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_debug_pid: i32, vm_context: VmContext, ) -> Result<VmInstance, Error>287     pub fn new(
288         config: CrosvmConfig,
289         temporary_directory: PathBuf,
290         requester_uid: u32,
291         requester_debug_pid: i32,
292         vm_context: VmContext,
293     ) -> Result<VmInstance, Error> {
294         validate_config(&config)?;
295         let cid = config.cid;
296         let name = config.name.clone();
297         let protected = config.protected;
298         let requester_uid_name = User::from_uid(Uid::from_raw(requester_uid))
299             .ok()
300             .flatten()
301             .map_or_else(|| format!("{}", requester_uid), |u| u.name);
302         let instance = VmInstance {
303             vm_state: Mutex::new(VmState::NotStarted { config }),
304             vm_context,
305             cid,
306             crosvm_control_socket_path: temporary_directory.join("crosvm.sock"),
307             name,
308             protected,
309             temporary_directory,
310             requester_uid,
311             requester_debug_pid,
312             callbacks: Default::default(),
313             vm_service: Mutex::new(None),
314             vm_metric: Mutex::new(Default::default()),
315             payload_state: Mutex::new(PayloadState::Starting),
316             payload_state_updated: Condvar::new(),
317             requester_uid_name,
318         };
319         info!("{} created", &instance);
320         Ok(instance)
321     }
322 
323     /// Starts an instance of `crosvm` to manage the VM. The `crosvm` instance will be killed when
324     /// the `VmInstance` is dropped.
start(self: &Arc<Self>) -> Result<(), Error>325     pub fn start(self: &Arc<Self>) -> Result<(), Error> {
326         let mut vm_metric = self.vm_metric.lock().unwrap();
327         vm_metric.start_timestamp = Some(SystemTime::now());
328         let ret = self.vm_state.lock().unwrap().start(self.clone());
329         if ret.is_ok() {
330             info!("{} started", &self);
331         }
332         ret.with_context(|| format!("{} failed to start", &self))
333     }
334 
335     /// Monitors the exit of the VM (i.e. termination of the `child` process). When that happens,
336     /// handles the event by updating the state, noityfing the event to clients by calling
337     /// callbacks, and removing temporary files for the VM.
monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File)338     fn monitor_vm_exit(&self, child: Arc<SharedChild>, mut failure_pipe_read: File) {
339         let result = child.wait();
340         match &result {
341             Err(e) => error!("Error waiting for crosvm({}) instance to die: {}", child.id(), e),
342             Ok(status) => {
343                 info!("crosvm({}) exited with status {}", child.id(), status);
344                 if let Some(exit_status_code) = status.code() {
345                     if exit_status_code == CROSVM_WATCHDOG_REBOOT_STATUS {
346                         info!("detected vcpu stall on crosvm");
347                     }
348                 }
349             }
350         }
351 
352         let mut vm_state = self.vm_state.lock().unwrap();
353         *vm_state = VmState::Dead;
354         // Ensure that the mutex is released before calling the callbacks.
355         drop(vm_state);
356         info!("{} exited", &self);
357 
358         // Read the pipe to see if any failure reason is written
359         let mut failure_reason = String::new();
360         match failure_pipe_read.read_to_string(&mut failure_reason) {
361             Err(e) => error!("Error reading VM failure reason from pipe: {}", e),
362             Ok(len) if len > 0 => info!("VM returned failure reason '{}'", &failure_reason),
363             _ => (),
364         };
365 
366         // In case of hangup, the pipe doesn't give us any information because the hangup can't be
367         // detected on the VM side (otherwise, it isn't a hangup), but in the
368         // monitor_payload_hangup function below which updates the payload state to Hangup.
369         let failure_reason =
370             if failure_reason.is_empty() && self.payload_state() == PayloadState::Hangup {
371                 Cow::from("HANGUP")
372             } else {
373                 Cow::from(failure_reason)
374             };
375 
376         self.handle_ramdump().unwrap_or_else(|e| error!("Error handling ramdump: {}", e));
377 
378         let death_reason = death_reason(&result, &failure_reason);
379         let exit_signal = exit_signal(&result);
380 
381         self.callbacks.callback_on_died(self.cid, death_reason);
382 
383         let vm_metric = self.vm_metric.lock().unwrap();
384         write_vm_exited_stats_sync(
385             self.requester_uid as i32,
386             &self.name,
387             death_reason,
388             exit_signal,
389             &vm_metric,
390         );
391 
392         // Delete temporary files. The folder itself is removed by VirtualizationServiceInternal.
393         remove_temporary_files(&self.temporary_directory).unwrap_or_else(|e| {
394             error!("Error removing temporary files from {:?}: {}", self.temporary_directory, e);
395         });
396     }
397 
398     /// Waits until payload is started, or timeout expires. When timeout occurs, kill
399     /// the VM to prevent indefinite hangup and update the payload_state accordingly.
monitor_payload_hangup(&self, child: Arc<SharedChild>)400     fn monitor_payload_hangup(&self, child: Arc<SharedChild>) {
401         debug!("Starting to monitor hangup for Microdroid({})", child.id());
402         let (_, result) = self
403             .payload_state_updated
404             .wait_timeout_while(self.payload_state.lock().unwrap(), *BOOT_HANGUP_TIMEOUT, |s| {
405                 *s < PayloadState::Started
406             })
407             .unwrap();
408         let child_still_running = child.try_wait().ok() == Some(None);
409         if result.timed_out() && child_still_running {
410             error!(
411                 "Microdroid({}) failed to start payload within {} secs timeout. Shutting down.",
412                 child.id(),
413                 BOOT_HANGUP_TIMEOUT.as_secs()
414             );
415             self.update_payload_state(PayloadState::Hangup).unwrap();
416             if let Err(e) = self.kill() {
417                 error!("Error stopping timed-out VM with CID {}: {:?}", child.id(), e);
418             }
419         }
420     }
421 
monitor_vm_status(&self, child: Arc<SharedChild>)422     fn monitor_vm_status(&self, child: Arc<SharedChild>) {
423         let pid = child.id();
424 
425         loop {
426             {
427                 // Check VM state
428                 let vm_state = &*self.vm_state.lock().unwrap();
429                 if let VmState::Dead = vm_state {
430                     break;
431                 }
432 
433                 let mut vm_metric = self.vm_metric.lock().unwrap();
434 
435                 // Get CPU Information
436                 if let Ok(guest_time) = get_guest_time(pid) {
437                     vm_metric.cpu_guest_time = Some(guest_time);
438                 } else {
439                     error!("Failed to parse /proc/[pid]/stat");
440                 }
441 
442                 // Get Memory Information
443                 if let Ok(rss) = get_rss(pid) {
444                     vm_metric.rss = match &vm_metric.rss {
445                         Some(x) => Some(Rss::extract_max(x, &rss)),
446                         None => Some(rss),
447                     }
448                 } else {
449                     error!("Failed to parse /proc/[pid]/smaps");
450                 }
451             }
452 
453             thread::sleep(Duration::from_secs(1));
454         }
455     }
456 
457     /// Returns the last reported state of the VM payload.
payload_state(&self) -> PayloadState458     pub fn payload_state(&self) -> PayloadState {
459         *self.payload_state.lock().unwrap()
460     }
461 
462     /// Updates the payload state to the given value, if it is a valid state transition.
update_payload_state(&self, new_state: PayloadState) -> Result<(), Error>463     pub fn update_payload_state(&self, new_state: PayloadState) -> Result<(), Error> {
464         let mut state_locked = self.payload_state.lock().unwrap();
465         // Only allow forward transitions, e.g. from starting to started or finished, not back in
466         // the other direction.
467         if new_state > *state_locked {
468             *state_locked = new_state;
469             self.payload_state_updated.notify_all();
470             Ok(())
471         } else {
472             bail!("Invalid payload state transition from {:?} to {:?}", *state_locked, new_state)
473         }
474     }
475 
476     /// Kills the crosvm instance, if it is running.
kill(&self) -> Result<(), Error>477     pub fn kill(&self) -> Result<(), Error> {
478         let monitor_vm_exit_thread = {
479             let vm_state = &mut *self.vm_state.lock().unwrap();
480             if let VmState::Running { child, monitor_vm_exit_thread } = vm_state {
481                 let id = child.id();
482                 debug!("Killing crosvm({})", id);
483                 // TODO: Talk to crosvm to shutdown cleanly.
484                 child.kill().with_context(|| format!("Error killing crosvm({id}) instance"))?;
485                 monitor_vm_exit_thread.take()
486             } else {
487                 bail!("VM is not running")
488             }
489         };
490 
491         // Wait for monitor_vm_exit() to finish. Must release vm_state lock
492         // first, as monitor_vm_exit() takes it as well.
493         monitor_vm_exit_thread.map(JoinHandle::join);
494 
495         // Now that the VM has been killed, shut down the VirtualMachineService
496         // server to eagerly free up the server threads.
497         self.vm_context.vm_server.shutdown()?;
498 
499         Ok(())
500     }
501 
502     /// Responds to memory-trimming notifications by inflating the virtio
503     /// balloon to reclaim guest memory.
trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error>504     pub fn trim_memory(&self, level: MemoryTrimLevel) -> Result<(), Error> {
505         let request = VmRequest::BalloonCommand(BalloonControlCommand::Stats {});
506         match vm_control::client::handle_request(&request, &self.crosvm_control_socket_path) {
507             Ok(VmResponse::BalloonStats { stats, balloon_actual: _ }) => {
508                 if let Some(total_memory) = stats.total_memory {
509                     // Reclaim up to 50% of total memory assuming worst case
510                     // most memory is anonymous and must be swapped to zram
511                     // with an approximate 2:1 compression ratio.
512                     let pct = match level {
513                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_CRITICAL => 50,
514                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_LOW => 30,
515                         MemoryTrimLevel::TRIM_MEMORY_RUNNING_MODERATE => 10,
516                         _ => bail!("Invalid memory trim level {:?}", level),
517                     };
518                     let command =
519                         BalloonControlCommand::Adjust { num_bytes: total_memory * pct / 100 };
520                     if let Err(e) = vm_control::client::handle_request(
521                         &VmRequest::BalloonCommand(command),
522                         &self.crosvm_control_socket_path,
523                     ) {
524                         bail!("Error sending balloon adjustment: {:?}", e);
525                     }
526                 }
527             }
528             Ok(VmResponse::Err(e)) => {
529                 // ENOTSUP is returned when the balloon protocol is not initialised. This
530                 // can occur for numerous reasons: Guest is still booting, guest doesn't
531                 // support ballooning, host doesn't support ballooning. We don't log or
532                 // raise an error in this case: trim is just a hint and we can ignore it.
533                 if e.errno() != libc::ENOTSUP {
534                     bail!("Errno return when requesting balloon stats: {}", e.errno())
535                 }
536             }
537             e => bail!("Error requesting balloon stats: {:?}", e),
538         }
539         Ok(())
540     }
541 
542     /// Checks if ramdump has been created. If so, send it to tombstoned.
handle_ramdump(&self) -> Result<(), Error>543     fn handle_ramdump(&self) -> Result<(), Error> {
544         let ramdump_path = self.temporary_directory.join("ramdump");
545         if !ramdump_path.as_path().try_exists()? {
546             return Ok(());
547         }
548         if std::fs::metadata(&ramdump_path)?.len() > 0 {
549             Self::send_ramdump_to_tombstoned(&ramdump_path)?;
550         }
551         Ok(())
552     }
553 
send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error>554     fn send_ramdump_to_tombstoned(ramdump_path: &Path) -> Result<(), Error> {
555         let mut input = File::open(ramdump_path)
556             .context(format!("Failed to open ramdump {:?} for reading", ramdump_path))?;
557 
558         let pid = std::process::id() as i32;
559         let conn = TombstonedConnection::connect(pid, DebuggerdDumpType::Tombstone)
560             .context("Failed to connect to tombstoned")?;
561         let mut output = conn
562             .text_output
563             .as_ref()
564             .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
565 
566         std::io::copy(&mut input, &mut output).context("Failed to send ramdump to tombstoned")?;
567         info!("Ramdump {:?} sent to tombstoned", ramdump_path);
568 
569         conn.notify_completion()?;
570         Ok(())
571     }
572 }
573 
574 impl Rss {
extract_max(x: &Rss, y: &Rss) -> Rss575     fn extract_max(x: &Rss, y: &Rss) -> Rss {
576         Rss { vm: max(x.vm, y.vm), crosvm: max(x.crosvm, y.crosvm) }
577     }
578 }
579 
580 // Get guest time from /proc/[crosvm pid]/stat
get_guest_time(pid: u32) -> Result<i64>581 fn get_guest_time(pid: u32) -> Result<i64> {
582     let file = read_to_string(format!("/proc/{}/stat", pid))?;
583     let data_list: Vec<_> = file.split_whitespace().collect();
584 
585     // Information about guest_time is at 43th place of the file split with the whitespace.
586     // Example of /proc/[pid]/stat :
587     // 6603 (kworker/104:1H-kblockd) I 2 0 0 0 -1 69238880 0 0 0 0 0 88 0 0 0 -20 1 0 1845 0 0
588     // 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 0 0 0 17 104 0 0 0 0 0 0 0 0 0 0 0 0 0
589     if data_list.len() < 43 {
590         bail!("Failed to parse command result for getting guest time : {}", file);
591     }
592 
593     let guest_time_ticks = data_list[42].parse::<i64>()?;
594     // SAFETY : It just returns an integer about CPU tick information.
595     let ticks_per_sec = unsafe { sysconf(_SC_CLK_TCK) };
596     Ok(guest_time_ticks * MILLIS_PER_SEC / ticks_per_sec)
597 }
598 
599 // Get rss from /proc/[crosvm pid]/smaps
get_rss(pid: u32) -> Result<Rss>600 fn get_rss(pid: u32) -> Result<Rss> {
601     let file = read_to_string(format!("/proc/{}/smaps", pid))?;
602     let lines: Vec<_> = file.split('\n').collect();
603 
604     let mut rss_vm_total = 0i64;
605     let mut rss_crosvm_total = 0i64;
606     let mut is_vm = false;
607     for line in lines {
608         if line.contains("crosvm_guest") {
609             is_vm = true;
610         } else if line.contains("Rss:") {
611             let data_list: Vec<_> = line.split_whitespace().collect();
612             if data_list.len() < 2 {
613                 bail!("Failed to parse command result for getting rss :\n{}", line);
614             }
615             let rss = data_list[1].parse::<i64>()?;
616 
617             if is_vm {
618                 rss_vm_total += rss;
619                 is_vm = false;
620             }
621             rss_crosvm_total += rss;
622         }
623     }
624 
625     Ok(Rss { vm: rss_vm_total, crosvm: rss_crosvm_total })
626 }
627 
death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason628 fn death_reason(result: &Result<ExitStatus, io::Error>, mut failure_reason: &str) -> DeathReason {
629     if let Some(position) = failure_reason.find('|') {
630         // Separator indicates extra context information is present after the failure name.
631         error!("Failure info: {}", &failure_reason[(position + 1)..]);
632         failure_reason = &failure_reason[..position];
633     }
634     if let Ok(status) = result {
635         match failure_reason {
636             "PVM_FIRMWARE_PUBLIC_KEY_MISMATCH" => {
637                 return DeathReason::PVM_FIRMWARE_PUBLIC_KEY_MISMATCH
638             }
639             "PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED" => {
640                 return DeathReason::PVM_FIRMWARE_INSTANCE_IMAGE_CHANGED
641             }
642             "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE" => {
643                 return DeathReason::MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE
644             }
645             "MICRODROID_PAYLOAD_HAS_CHANGED" => return DeathReason::MICRODROID_PAYLOAD_HAS_CHANGED,
646             "MICRODROID_PAYLOAD_VERIFICATION_FAILED" => {
647                 return DeathReason::MICRODROID_PAYLOAD_VERIFICATION_FAILED
648             }
649             "MICRODROID_INVALID_PAYLOAD_CONFIG" => {
650                 return DeathReason::MICRODROID_INVALID_PAYLOAD_CONFIG
651             }
652             "MICRODROID_UNKNOWN_RUNTIME_ERROR" => {
653                 return DeathReason::MICRODROID_UNKNOWN_RUNTIME_ERROR
654             }
655             "HANGUP" => return DeathReason::HANGUP,
656             _ => {}
657         }
658         match status.code() {
659             None => DeathReason::KILLED,
660             Some(0) => DeathReason::SHUTDOWN,
661             Some(CROSVM_START_ERROR_STATUS) => DeathReason::START_FAILED,
662             Some(CROSVM_REBOOT_STATUS) => DeathReason::REBOOT,
663             Some(CROSVM_CRASH_STATUS) => DeathReason::CRASH,
664             Some(CROSVM_WATCHDOG_REBOOT_STATUS) => DeathReason::WATCHDOG_REBOOT,
665             Some(_) => DeathReason::UNKNOWN,
666         }
667     } else {
668         DeathReason::INFRASTRUCTURE_ERROR
669     }
670 }
671 
exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32>672 fn exit_signal(result: &Result<ExitStatus, io::Error>) -> Option<i32> {
673     match result {
674         Ok(status) => status.signal(),
675         Err(_) => None,
676     }
677 }
678 
679 /// Starts an instance of `crosvm` to manage a new VM.
run_vm( config: CrosvmConfig, crosvm_control_socket_path: &Path, failure_pipe_write: File, ) -> Result<SharedChild, Error>680 fn run_vm(
681     config: CrosvmConfig,
682     crosvm_control_socket_path: &Path,
683     failure_pipe_write: File,
684 ) -> Result<SharedChild, Error> {
685     validate_config(&config)?;
686 
687     let mut command = Command::new(CROSVM_PATH);
688     // TODO(qwandor): Remove --disable-sandbox.
689     command
690         .arg("--extended-status")
691         // Configure the logger for the crosvm process to silence logs from the disk crate which
692         // don't provide much information to us (but do spamming us).
693         .arg("--log-level")
694         .arg("info,disk=warn")
695         .arg("run")
696         .arg("--disable-sandbox")
697         .arg("--cid")
698         .arg(config.cid.to_string());
699 
700     if system_properties::read_bool("hypervisor.memory_reclaim.supported", false)? {
701         command.arg("--balloon-page-reporting");
702     } else {
703         command.arg("--no-balloon");
704     }
705 
706     if config.protected {
707         match system_properties::read(SYSPROP_CUSTOM_PVMFW_PATH)? {
708             Some(pvmfw_path) if !pvmfw_path.is_empty() => {
709                 command.arg("--protected-vm-with-firmware").arg(pvmfw_path)
710             }
711             _ => command.arg("--protected-vm"),
712         };
713 
714         // 3 virtio-console devices + vsock = 4.
715         let virtio_pci_device_count = 4 + config.disks.len();
716         // crosvm virtio queue has 256 entries, so 2 MiB per device (2 pages per entry) should be
717         // enough.
718         let swiotlb_size_mib = 2 * virtio_pci_device_count as u32;
719         command.arg("--swiotlb").arg(swiotlb_size_mib.to_string());
720 
721         // Workaround to keep crash_dump from trying to read protected guest memory.
722         // Context in b/238324526.
723         command.arg("--unmap-guest-memory-on-fork");
724 
725         if config.ramdump.is_some() {
726             // Protected VM needs to reserve memory for ramdump here. Note that we reserve more
727             // memory for the restricted dma pool.
728             let ramdump_reserve = RAMDUMP_RESERVED_MIB + swiotlb_size_mib;
729             command.arg("--params").arg(format!("crashkernel={ramdump_reserve}M"));
730         }
731     } else if config.ramdump.is_some() {
732         command.arg("--params").arg(format!("crashkernel={RAMDUMP_RESERVED_MIB}M"));
733     }
734     if config.debug_config.debug_level == DebugLevel::NONE
735         && config.debug_config.should_prepare_console_output()
736     {
737         // bootconfig.normal will be used, but we need log.
738         command.arg("--params").arg("printk.devkmsg=on");
739         command.arg("--params").arg("console=hvc0");
740     }
741 
742     if let Some(memory_mib) = config.memory_mib {
743         command.arg("--mem").arg(memory_mib.to_string());
744     }
745 
746     if let Some(cpus) = config.cpus {
747         command.arg("--cpus").arg(cpus.to_string());
748     }
749 
750     if config.host_cpu_topology {
751         // TODO(b/266664564): replace with --host-cpu-topology once available
752         if let Some(cpus) = get_num_cpus() {
753             command.arg("--cpus").arg(cpus.to_string());
754         } else {
755             bail!("Could not determine the number of CPUs in the system");
756         }
757     }
758 
759     if !config.task_profiles.is_empty() {
760         command.arg("--task-profiles").arg(config.task_profiles.join(","));
761     }
762 
763     if let Some(gdb_port) = config.gdb_port {
764         command.arg("--gdb").arg(gdb_port.to_string());
765     }
766 
767     // Keep track of what file descriptors should be mapped to the crosvm process.
768     let mut preserved_fds = config.indirect_files.iter().map(|file| file.as_raw_fd()).collect();
769 
770     // Setup the serial devices.
771     // 1. uart device: used as the output device by bootloaders and as early console by linux
772     // 2. uart device: used to report the reason for the VM failing.
773     // 3. virtio-console device: used as the console device where kmsg is redirected to
774     // 4. virtio-console device: used as the ramdump output
775     // 5. virtio-console device: used as the logcat output
776     //
777     // When [console|log]_fd is not specified, the devices are attached to sink, which means what's
778     // written there is discarded.
779     let console_arg = format_serial_arg(&mut preserved_fds, &config.console_fd);
780     let log_arg = format_serial_arg(&mut preserved_fds, &config.log_fd);
781     let failure_serial_path = add_preserved_fd(&mut preserved_fds, &failure_pipe_write);
782     let ramdump_arg = format_serial_arg(&mut preserved_fds, &config.ramdump);
783 
784     // Warning: Adding more serial devices requires you to shift the PCI device ID of the boot
785     // disks in bootconfig.x86_64. This is because x86 crosvm puts serial devices and the block
786     // devices in the same PCI bus and serial devices comes before the block devices. Arm crosvm
787     // doesn't have the issue.
788     // /dev/ttyS0
789     command.arg(format!("--serial={},hardware=serial,num=1", &console_arg));
790     // /dev/ttyS1
791     command.arg(format!("--serial=type=file,path={},hardware=serial,num=2", &failure_serial_path));
792     // /dev/hvc0
793     command.arg(format!("--serial={},hardware=virtio-console,num=1", &console_arg));
794     // /dev/hvc1
795     command.arg(format!("--serial={},hardware=virtio-console,num=2", &ramdump_arg));
796     // /dev/hvc2
797     command.arg(format!("--serial={},hardware=virtio-console,num=3", &log_arg));
798 
799     if let Some(bootloader) = &config.bootloader {
800         command.arg("--bios").arg(add_preserved_fd(&mut preserved_fds, bootloader));
801     }
802 
803     if let Some(initrd) = &config.initrd {
804         command.arg("--initrd").arg(add_preserved_fd(&mut preserved_fds, initrd));
805     }
806 
807     if let Some(params) = &config.params {
808         command.arg("--params").arg(params);
809     }
810 
811     for disk in &config.disks {
812         command
813             .arg(if disk.writable { "--rwdisk" } else { "--disk" })
814             .arg(add_preserved_fd(&mut preserved_fds, &disk.image));
815     }
816 
817     if let Some(kernel) = &config.kernel {
818         command.arg(add_preserved_fd(&mut preserved_fds, kernel));
819     }
820 
821     let control_server_socket = UnixSeqpacketListener::bind(crosvm_control_socket_path)
822         .context("failed to create control server")?;
823     command
824         .arg("--socket")
825         .arg(add_preserved_fd(&mut preserved_fds, &control_server_socket.as_raw_descriptor()));
826 
827     debug!("Preserving FDs {:?}", preserved_fds);
828     command.preserved_fds(preserved_fds);
829 
830     print_crosvm_args(&command);
831 
832     let result = SharedChild::spawn(&mut command)?;
833     debug!("Spawned crosvm({}).", result.id());
834     Ok(result)
835 }
836 
837 /// Ensure that the configuration has a valid combination of fields set, or return an error if not.
validate_config(config: &CrosvmConfig) -> Result<(), Error>838 fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
839     if config.bootloader.is_none() && config.kernel.is_none() {
840         bail!("VM must have either a bootloader or a kernel image.");
841     }
842     if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
843         bail!("Can't have both bootloader and kernel/initrd image.");
844     }
845     let version = Version::parse(CROSVM_PLATFORM_VERSION).unwrap();
846     if !config.platform_version.matches(&version) {
847         bail!(
848             "Incompatible platform version. The config is compatible with platform version(s) \
849               {}, but the actual platform version is {}",
850             config.platform_version,
851             version
852         );
853     }
854 
855     Ok(())
856 }
857 
858 /// Print arguments of the crosvm command. In doing so, /proc/self/fd/XX is annotated with the
859 /// actual file path if the FD is backed by a regular file. If not, the /proc path is printed
860 /// unmodified.
print_crosvm_args(command: &Command)861 fn print_crosvm_args(command: &Command) {
862     let re = Regex::new(r"/proc/self/fd/[\d]+").unwrap();
863     info!(
864         "Running crosvm with args: {:?}",
865         command
866             .get_args()
867             .map(|s| s.to_string_lossy())
868             .map(|s| {
869                 re.replace_all(&s, |caps: &Captures| {
870                     let path = &caps[0];
871                     if let Ok(realpath) = std::fs::canonicalize(path) {
872                         format!("{} ({})", path, realpath.to_string_lossy())
873                     } else {
874                         path.to_owned()
875                     }
876                 })
877                 .into_owned()
878             })
879             .collect::<Vec<_>>()
880     );
881 }
882 
883 /// Adds the file descriptor for `file` to `preserved_fds`, and returns a string of the form
884 /// "/proc/self/fd/N" where N is the file descriptor.
add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String885 fn add_preserved_fd(preserved_fds: &mut Vec<RawFd>, file: &dyn AsRawFd) -> String {
886     let fd = file.as_raw_fd();
887     preserved_fds.push(fd);
888     format!("/proc/self/fd/{}", fd)
889 }
890 
891 /// Adds the file descriptor for `file` (if any) to `preserved_fds`, and returns the appropriate
892 /// 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>) -> String893 fn format_serial_arg(preserved_fds: &mut Vec<RawFd>, file: &Option<File>) -> String {
894     if let Some(file) = file {
895         format!("type=file,path={}", add_preserved_fd(preserved_fds, file))
896     } else {
897         "type=sink".to_string()
898     }
899 }
900 
901 /// Creates a new pipe with the `O_CLOEXEC` flag set, and returns the read side and write side.
create_pipe() -> Result<(File, File), Error>902 fn create_pipe() -> Result<(File, File), Error> {
903     let (raw_read, raw_write) = pipe2(OFlag::O_CLOEXEC)?;
904     // SAFETY: We are the sole owners of these fds as they were just created.
905     let read_fd = unsafe { File::from_raw_fd(raw_read) };
906     let write_fd = unsafe { File::from_raw_fd(raw_write) };
907     Ok((read_fd, write_fd))
908 }
909