Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 1 | // Copyright 2023, 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 | |
Alice Wang | 734801c | 2023-09-05 11:46:50 +0000 | [diff] [blame] | 15 | //! This module contains the functions to start, stop and communicate with the |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 16 | //! Service VM. |
| 17 | |
| 18 | use android_system_virtualizationservice::{ |
| 19 | aidl::android::system::virtualizationservice::{ |
| 20 | CpuTopology::CpuTopology, DiskImage::DiskImage, |
| 21 | IVirtualizationService::IVirtualizationService, Partition::Partition, |
| 22 | PartitionType::PartitionType, VirtualMachineConfig::VirtualMachineConfig, |
| 23 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
| 24 | }, |
| 25 | binder::ParcelFileDescriptor, |
| 26 | }; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 27 | use anyhow::{ensure, Context, Result}; |
| 28 | use log::{info, warn}; |
| 29 | use service_vm_comm::{Request, Response, VmType}; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 30 | use std::fs::{File, OpenOptions}; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 31 | use std::io::{BufWriter, Write}; |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 32 | use std::path::{Path, PathBuf}; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 33 | use std::time::Duration; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 34 | use vmclient::VmInstance; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 35 | use vsock::{VsockListener, VsockStream, VMADDR_CID_HOST}; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 36 | |
| 37 | const VIRT_DATA_DIR: &str = "/data/misc/apexdata/com.android.virt"; |
| 38 | const RIALTO_PATH: &str = "/apex/com.android.virt/etc/rialto.bin"; |
| 39 | const INSTANCE_IMG_NAME: &str = "service_vm_instance.img"; |
| 40 | const INSTANCE_IMG_SIZE_BYTES: i64 = 1 << 20; // 1MB |
| 41 | const MEMORY_MB: i32 = 300; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 42 | const WRITE_BUFFER_CAPACITY: usize = 512; |
| 43 | const READ_TIMEOUT: Duration = Duration::from_secs(10); |
| 44 | const WRITE_TIMEOUT: Duration = Duration::from_secs(10); |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 45 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 46 | /// Service VM. |
| 47 | pub struct ServiceVm { |
| 48 | vsock_stream: VsockStream, |
| 49 | /// VmInstance will be dropped when ServiceVm goes out of scope, which will kill the VM. |
| 50 | vm: VmInstance, |
| 51 | } |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 52 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 53 | impl ServiceVm { |
| 54 | /// Starts the service VM and returns its instance. |
| 55 | /// The same instance image is used for different VMs. |
| 56 | /// TODO(b/278858244): Allow only one service VM running at each time. |
| 57 | pub fn start() -> Result<Self> { |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 58 | let vm = vm_instance()?; |
| 59 | Self::start_vm(vm, VmType::ProtectedVm) |
| 60 | } |
| 61 | |
| 62 | /// Starts the given VM instance and sets up the vsock connection with it. |
| 63 | /// Returns a `ServiceVm` instance. |
| 64 | /// This function is exposed for testing. |
| 65 | pub fn start_vm(vm: VmInstance, vm_type: VmType) -> Result<Self> { |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 66 | // Sets up the vsock server on the host. |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 67 | let vsock_listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, vm_type.port())?; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 68 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 69 | // Starts the service VM. |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 70 | vm.start().context("Failed to start service VM")?; |
| 71 | info!("Service VM started"); |
| 72 | |
| 73 | // Accepts the connection from the service VM. |
| 74 | // TODO(b/299427101): Introduce a timeout for the accept. |
| 75 | let (vsock_stream, peer_addr) = vsock_listener.accept().context("Failed to accept")?; |
| 76 | info!("Accepted connection {:?}", vsock_stream); |
| 77 | ensure!( |
| 78 | peer_addr.cid() == u32::try_from(vm.cid()).unwrap(), |
| 79 | "The CID of the peer address {} doesn't match the service VM CID {}", |
| 80 | peer_addr, |
| 81 | vm.cid() |
| 82 | ); |
| 83 | vsock_stream.set_read_timeout(Some(READ_TIMEOUT))?; |
| 84 | vsock_stream.set_write_timeout(Some(WRITE_TIMEOUT))?; |
| 85 | |
| 86 | Ok(Self { vsock_stream, vm }) |
| 87 | } |
| 88 | |
| 89 | /// Processes the request in the service VM. |
| 90 | pub fn process_request(&mut self, request: &Request) -> Result<Response> { |
| 91 | self.write_request(request)?; |
| 92 | self.read_response() |
| 93 | } |
| 94 | |
| 95 | /// Sends the request to the service VM. |
| 96 | fn write_request(&mut self, request: &Request) -> Result<()> { |
| 97 | let mut buffer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, &mut self.vsock_stream); |
| 98 | ciborium::into_writer(request, &mut buffer)?; |
| 99 | buffer.flush().context("Failed to flush the buffer")?; |
| 100 | info!("Sent request to the service VM."); |
| 101 | Ok(()) |
| 102 | } |
| 103 | |
| 104 | /// Reads the response from the service VM. |
| 105 | fn read_response(&mut self) -> Result<Response> { |
| 106 | let response: Response = ciborium::from_reader(&mut self.vsock_stream) |
| 107 | .context("Failed to read the response from the service VM")?; |
| 108 | info!("Received response from the service VM."); |
| 109 | Ok(response) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl Drop for ServiceVm { |
| 114 | fn drop(&mut self) { |
| 115 | // Wait till the service VM finishes releasing all the resources. |
| 116 | match self.vm.wait_for_death_with_timeout(Duration::from_secs(10)) { |
| 117 | Some(e) => info!("Exit the service VM: {e:?}"), |
| 118 | None => warn!("Timed out waiting for service VM exit"), |
| 119 | } |
| 120 | } |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 121 | } |
| 122 | |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 123 | fn vm_instance() -> Result<VmInstance> { |
| 124 | let virtmgr = vmclient::VirtualizationService::new().context("Failed to spawn VirtMgr")?; |
| 125 | let service = virtmgr.connect().context("Failed to connect to VirtMgr")?; |
| 126 | info!("Connected to VirtMgr for service VM"); |
| 127 | |
| 128 | let instance_img_path = Path::new(VIRT_DATA_DIR).join(INSTANCE_IMG_NAME); |
| 129 | let instance_img = instance_img(service.as_ref(), instance_img_path)?; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 130 | let writable_partitions = vec![Partition { |
| 131 | label: "vm-instance".to_owned(), |
| 132 | image: Some(instance_img), |
| 133 | writable: true, |
| 134 | }]; |
| 135 | let rialto = File::open(RIALTO_PATH).context("Failed to open Rialto kernel binary")?; |
| 136 | let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig { |
| 137 | name: String::from("Service VM"), |
| 138 | bootloader: Some(ParcelFileDescriptor::new(rialto)), |
| 139 | disks: vec![DiskImage { image: None, partitions: writable_partitions, writable: true }], |
| 140 | protectedVm: true, |
| 141 | memoryMib: MEMORY_MB, |
| 142 | cpuTopology: CpuTopology::ONE_CPU, |
| 143 | platformVersion: "~1.0".to_string(), |
| 144 | gdbPort: 0, // No gdb |
| 145 | ..Default::default() |
| 146 | }); |
| 147 | let console_out = None; |
| 148 | let console_in = None; |
| 149 | let log = None; |
| 150 | let callback = None; |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 151 | VmInstance::create(service.as_ref(), &config, console_out, console_in, log, callback) |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 152 | .context("Failed to create service VM") |
| 153 | } |
| 154 | |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 155 | /// Returns the file descriptor of the instance image at the given path. |
| 156 | /// This function is only exposed for testing. |
| 157 | pub fn instance_img( |
| 158 | service: &dyn IVirtualizationService, |
| 159 | instance_img_path: PathBuf, |
| 160 | ) -> Result<ParcelFileDescriptor> { |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 161 | if instance_img_path.exists() { |
| 162 | // TODO(b/298174584): Try to recover if the service VM is triggered by rkpd. |
| 163 | return Ok(OpenOptions::new() |
| 164 | .read(true) |
| 165 | .write(true) |
| 166 | .open(instance_img_path) |
| 167 | .map(ParcelFileDescriptor::new)?); |
| 168 | } |
| 169 | let instance_img = OpenOptions::new() |
| 170 | .create(true) |
| 171 | .read(true) |
| 172 | .write(true) |
| 173 | .open(instance_img_path) |
| 174 | .map(ParcelFileDescriptor::new)?; |
| 175 | service.initializeWritablePartition( |
| 176 | &instance_img, |
| 177 | INSTANCE_IMG_SIZE_BYTES, |
| 178 | PartitionType::ANDROID_VM_INSTANCE, |
| 179 | )?; |
| 180 | Ok(instance_img) |
| 181 | } |