blob: 484b57ba2a01b7e7b0001a6d43b1a2e4732ef3bf [file] [log] [blame]
Alice Wangc206b9b2023-08-28 14:13:51 +00001// 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 Wang734801c2023-09-05 11:46:50 +000015//! This module contains the functions to start, stop and communicate with the
Alice Wangc206b9b2023-08-28 14:13:51 +000016//! Service VM.
17
18use 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 Wanga4486592023-09-05 08:25:59 +000027use anyhow::{ensure, Context, Result};
28use log::{info, warn};
29use service_vm_comm::{Request, Response, VmType};
Alice Wangc206b9b2023-08-28 14:13:51 +000030use std::fs::{File, OpenOptions};
Alice Wanga4486592023-09-05 08:25:59 +000031use std::io::{BufWriter, Write};
Alice Wang17dc76e2023-09-06 09:43:52 +000032use std::path::{Path, PathBuf};
Alice Wanga4486592023-09-05 08:25:59 +000033use std::time::Duration;
Alice Wangc206b9b2023-08-28 14:13:51 +000034use vmclient::VmInstance;
Alice Wanga4486592023-09-05 08:25:59 +000035use vsock::{VsockListener, VsockStream, VMADDR_CID_HOST};
Alice Wangc206b9b2023-08-28 14:13:51 +000036
37const VIRT_DATA_DIR: &str = "/data/misc/apexdata/com.android.virt";
38const RIALTO_PATH: &str = "/apex/com.android.virt/etc/rialto.bin";
39const INSTANCE_IMG_NAME: &str = "service_vm_instance.img";
40const INSTANCE_IMG_SIZE_BYTES: i64 = 1 << 20; // 1MB
41const MEMORY_MB: i32 = 300;
Alice Wanga4486592023-09-05 08:25:59 +000042const WRITE_BUFFER_CAPACITY: usize = 512;
43const READ_TIMEOUT: Duration = Duration::from_secs(10);
44const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
Alice Wangc206b9b2023-08-28 14:13:51 +000045
Alice Wanga4486592023-09-05 08:25:59 +000046/// Service VM.
47pub 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 Wangc206b9b2023-08-28 14:13:51 +000052
Alice Wanga4486592023-09-05 08:25:59 +000053impl 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 Wang17dc76e2023-09-06 09:43:52 +000058 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 Wanga4486592023-09-05 08:25:59 +000066 // Sets up the vsock server on the host.
Alice Wang17dc76e2023-09-06 09:43:52 +000067 let vsock_listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, vm_type.port())?;
Alice Wangc206b9b2023-08-28 14:13:51 +000068
Alice Wanga4486592023-09-05 08:25:59 +000069 // Starts the service VM.
Alice Wanga4486592023-09-05 08:25:59 +000070 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
113impl 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 Wangc206b9b2023-08-28 14:13:51 +0000121}
122
Alice Wang17dc76e2023-09-06 09:43:52 +0000123fn 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 Wangc206b9b2023-08-28 14:13:51 +0000130 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 Wang17dc76e2023-09-06 09:43:52 +0000151 VmInstance::create(service.as_ref(), &config, console_out, console_in, log, callback)
Alice Wangc206b9b2023-08-28 14:13:51 +0000152 .context("Failed to create service VM")
153}
154
Alice Wang17dc76e2023-09-06 09:43:52 +0000155/// Returns the file descriptor of the instance image at the given path.
156/// This function is only exposed for testing.
157pub fn instance_img(
158 service: &dyn IVirtualizationService,
159 instance_img_path: PathBuf,
160) -> Result<ParcelFileDescriptor> {
Alice Wangc206b9b2023-08-28 14:13:51 +0000161 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}