blob: 1c3c5d97ca06b0141d1dff14899400e3bde8140f [file] [log] [blame]
Inseob Kimbdca0472023-07-28 19:20:56 +09001// 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
15//! Implementation of the AIDL interface of the VirtualizationService.
16
Jiyong Park2227eaa2023-08-04 11:59:18 +090017use anyhow::{anyhow, Context};
Inseob Kimbdca0472023-07-28 19:20:56 +090018use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::IVfioHandler;
19use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor;
Jiyong Park2227eaa2023-08-04 11:59:18 +090020use binder::{self, ExceptionCode, Interface, IntoBinderResult};
Inseob Kimbdca0472023-07-28 19:20:56 +090021use lazy_static::lazy_static;
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090022use std::fs::{read_link, write, File};
23use std::io::{Read, Seek, SeekFrom, Write};
24use std::mem::size_of;
25use std::path::{Path, PathBuf};
26use rustutils::system_properties;
27use zerocopy::{
28 byteorder::{BigEndian, U32},
29 FromBytes,
30};
Inseob Kimbdca0472023-07-28 19:20:56 +090031
32#[derive(Debug, Default)]
33pub struct VfioHandler {}
34
35impl VfioHandler {
36 pub fn init() -> VfioHandler {
37 VfioHandler::default()
38 }
39}
40
41impl Interface for VfioHandler {}
42
43impl IVfioHandler for VfioHandler {
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090044 fn bindDevicesToVfioDriver(&self, devices: &[String]) -> binder::Result<()> {
Inseob Kimbdca0472023-07-28 19:20:56 +090045 // permission check is already done by IVirtualizationServiceInternal.
46 if !*IS_VFIO_SUPPORTED {
Jiyong Park2227eaa2023-08-04 11:59:18 +090047 return Err(anyhow!("VFIO-platform not supported"))
48 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
Inseob Kimbdca0472023-07-28 19:20:56 +090049 }
Inseob Kimbdca0472023-07-28 19:20:56 +090050 devices.iter().try_for_each(|x| bind_device(Path::new(x)))?;
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090051 Ok(())
52 }
Inseob Kimbdca0472023-07-28 19:20:56 +090053
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090054 fn writeVmDtbo(&self, dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()> {
55 let dtbo_path = get_dtbo_img_path()?;
56 let mut dtbo_img = File::open(dtbo_path)
57 .context("Failed to open DTBO partition")
58 .or_service_specific_exception(-1)?;
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090059
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090060 let dt_table_header = get_dt_table_header(&mut dtbo_img)?;
61 let vm_dtbo_idx = system_properties::read("ro.boot.hypervisor.vm_dtbo_idx")
62 .context("Failed to read vm_dtbo_idx")
63 .or_service_specific_exception(-1)?
64 .ok_or_else(|| anyhow!("vm_dtbo_idx is none"))
65 .or_service_specific_exception(-1)?;
66 let vm_dtbo_idx = vm_dtbo_idx
67 .parse()
68 .context("vm_dtbo_idx is not an integer")
69 .or_service_specific_exception(-1)?;
70 let dt_table_entry = get_dt_table_entry(&mut dtbo_img, &dt_table_header, vm_dtbo_idx)?;
71 write_vm_full_dtbo_from_img(&mut dtbo_img, &dt_table_entry, dtbo_fd)?;
Inseob Kimf36347b2023-08-03 12:52:48 +090072 Ok(())
Inseob Kimbdca0472023-07-28 19:20:56 +090073 }
74}
75
76const DEV_VFIO_PATH: &str = "/dev/vfio/vfio";
77const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
78const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
79const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe";
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090080const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e;
Inseob Kimbdca0472023-07-28 19:20:56 +090081
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090082/// The structure of DT table header in dtbo.img.
83/// https://source.android.com/docs/core/architecture/dto/partitions
84#[repr(C)]
Frederick Mayle893738e2023-10-15 03:50:34 +000085#[derive(Debug, FromBytes)]
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090086struct DtTableHeader {
87 /// DT_TABLE_MAGIC
88 magic: U32<BigEndian>,
89 /// includes dt_table_header + all dt_table_entry and all dtb/dtbo
90 _total_size: U32<BigEndian>,
91 /// sizeof(dt_table_header)
92 header_size: U32<BigEndian>,
93 /// sizeof(dt_table_entry)
94 dt_entry_size: U32<BigEndian>,
95 /// number of dt_table_entry
96 dt_entry_count: U32<BigEndian>,
97 /// offset to the first dt_table_entry from head of dt_table_header
98 dt_entries_offset: U32<BigEndian>,
99 /// flash page size we assume
100 _page_size: U32<BigEndian>,
101 /// DTBO image version, the current version is 0. The version will be
102 /// incremented when the dt_table_header struct is updated.
103 _version: U32<BigEndian>,
Inseob Kimbdca0472023-07-28 19:20:56 +0900104}
105
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900106/// The structure of each DT table entry (v0) in dtbo.img.
107/// https://source.android.com/docs/core/architecture/dto/partitions
108#[repr(C)]
Frederick Mayle893738e2023-10-15 03:50:34 +0000109#[derive(Debug, FromBytes)]
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900110struct DtTableEntry {
111 /// size of each DT
112 dt_size: U32<BigEndian>,
113 /// offset from head of dt_table_header
114 dt_offset: U32<BigEndian>,
115 /// optional, must be zero if unused
116 _id: U32<BigEndian>,
117 /// optional, must be zero if unused
118 _rev: U32<BigEndian>,
119 /// optional, must be zero if unused
120 _custom: [U32<BigEndian>; 4],
121}
122
123lazy_static! {
124 static ref IS_VFIO_SUPPORTED: bool =
125 Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists();
Inseob Kimbdca0472023-07-28 19:20:56 +0900126}
127
128fn check_platform_device(path: &Path) -> binder::Result<()> {
129 if !path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900130 return Err(anyhow!("no such device {path:?}"))
131 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900132 }
133
134 if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900135 return Err(anyhow!("{path:?} is not a platform device"))
136 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900137 }
138
139 Ok(())
140}
141
142fn get_device_iommu_group(path: &Path) -> Option<u64> {
143 let group_path = read_link(path.join("iommu_group")).ok()?;
144 let group = group_path.file_name()?;
145 group.to_str()?.parse().ok()
146}
147
148fn is_bound_to_vfio_driver(path: &Path) -> bool {
149 let Ok(driver_path) = read_link(path.join("driver")) else {
150 return false;
151 };
152 let Some(driver) = driver_path.file_name() else {
153 return false;
154 };
155 driver.to_str().unwrap_or("") == "vfio-platform"
156}
157
158fn bind_vfio_driver(path: &Path) -> binder::Result<()> {
159 if is_bound_to_vfio_driver(path) {
160 // already bound
161 return Ok(());
162 }
163
164 // unbind
165 let Some(device) = path.file_name() else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900166 return Err(anyhow!("can't get device name from {path:?}"))
167 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900168 };
169 let Some(device_str) = device.to_str() else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900170 return Err(anyhow!("invalid filename {device:?}"))
171 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900172 };
Inseob Kim55438b22023-08-09 20:16:01 +0900173 let unbind_path = path.join("driver/unbind");
174 if unbind_path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900175 write(&unbind_path, device_str.as_bytes())
176 .with_context(|| format!("could not unbind {device_str}"))
177 .or_service_specific_exception(-1)?;
Inseob Kim55438b22023-08-09 20:16:01 +0900178 }
Inseob Kimbdca0472023-07-28 19:20:56 +0900179
180 // bind to VFIO
Jiyong Park2227eaa2023-08-04 11:59:18 +0900181 write(path.join("driver_override"), b"vfio-platform")
182 .with_context(|| format!("could not bind {device_str} to vfio-platform"))
183 .or_service_specific_exception(-1)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900184
Jiyong Park2227eaa2023-08-04 11:59:18 +0900185 write(SYSFS_PLATFORM_DRIVERS_PROBE_PATH, device_str.as_bytes())
186 .with_context(|| format!("could not write {device_str} to drivers-probe"))
187 .or_service_specific_exception(-1)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900188
189 // final check
190 if !is_bound_to_vfio_driver(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900191 return Err(anyhow!("{path:?} still not bound to vfio driver"))
192 .or_service_specific_exception(-1);
Inseob Kimbdca0472023-07-28 19:20:56 +0900193 }
194
195 if get_device_iommu_group(path).is_none() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900196 return Err(anyhow!("can't get iommu group for {path:?}"))
197 .or_service_specific_exception(-1);
Inseob Kimbdca0472023-07-28 19:20:56 +0900198 }
199
200 Ok(())
201}
202
203fn bind_device(path: &Path) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900204 let path = path
205 .canonicalize()
206 .with_context(|| format!("can't canonicalize {path:?}"))
207 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900208
209 check_platform_device(&path)?;
210 bind_vfio_driver(&path)
211}
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900212
213fn get_dtbo_img_path() -> binder::Result<PathBuf> {
214 let slot_suffix = system_properties::read("ro.boot.slot_suffix")
215 .context("Failed to read ro.boot.slot_suffix")
216 .or_service_specific_exception(-1)?
217 .ok_or_else(|| anyhow!("slot_suffix is none"))
218 .or_service_specific_exception(-1)?;
219 Ok(PathBuf::from(format!("/dev/block/by-name/dtbo{slot_suffix}")))
220}
221
222fn read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>> {
223 file.seek(SeekFrom::Start(offset))
224 .context("Cannot seek the offset")
225 .or_service_specific_exception(-1)?;
226 let mut buffer = vec![0_u8; size];
227 file.read_exact(&mut buffer)
228 .context("Failed to read buffer")
229 .or_service_specific_exception(-1)?;
230 Ok(buffer)
231}
232
233fn get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader> {
234 let values = read_values(file, size_of::<DtTableHeader>(), 0)?;
235 let dt_table_header = DtTableHeader::read_from(values.as_slice())
236 .context("DtTableHeader is invalid")
237 .or_service_specific_exception(-1)?;
238 if dt_table_header.magic.get() != DT_TABLE_MAGIC
239 || dt_table_header.header_size.get() as usize != size_of::<DtTableHeader>()
240 {
241 return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1)?;
242 }
243 Ok(dt_table_header)
244}
245
246fn get_dt_table_entry(
247 file: &mut File,
248 header: &DtTableHeader,
249 index: u32,
250) -> binder::Result<DtTableEntry> {
251 if index >= header.dt_entry_count.get() {
252 return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1)?;
253 }
254 let Some(prev_dt_entry_total_size) = header.dt_entry_size.get().checked_mul(index) else {
255 return Err(anyhow!("Unexpected arithmetic result"))
256 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
257 };
258 let Some(dt_entry_offset) =
259 prev_dt_entry_total_size.checked_add(header.dt_entries_offset.get())
260 else {
261 return Err(anyhow!("Unexpected arithmetic result"))
262 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
263 };
264 let values = read_values(file, size_of::<DtTableEntry>(), dt_entry_offset.into())?;
265 let dt_table_entry = DtTableEntry::read_from(values.as_slice())
266 .with_context(|| format!("DtTableEntry at index {index} is invalid."))
267 .or_service_specific_exception(-1)?;
268 Ok(dt_table_entry)
269}
270
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900271fn write_vm_full_dtbo_from_img(
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900272 dtbo_img_file: &mut File,
273 entry: &DtTableEntry,
274 dtbo_fd: &ParcelFileDescriptor,
275) -> binder::Result<()> {
276 let dt_size = entry
277 .dt_size
278 .get()
279 .try_into()
280 .context("Failed to convert type")
281 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
282 let buffer = read_values(dtbo_img_file, dt_size, entry.dt_offset.get().into())?;
283
284 let mut dtbo_fd = dtbo_fd
285 .as_ref()
286 .try_clone()
287 .context("Failed to clone File from ParcelFileDescriptor")
288 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?;
289
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900290 dtbo_fd
291 .write_all(&buffer)
292 .context("Failed to write dtbo file")
293 .or_service_specific_exception(-1)?;
294 Ok(())
295}