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