blob: c0967af2b4a24e110b07f439faa3f981889b8713 [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};
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000018use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IBoundDevice::{IBoundDevice, BnBoundDevice};
Inseob Kimbdca0472023-07-28 19:20:56 +090019use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::IVfioHandler;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000020use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::VfioDev::VfioDev;
Inseob Kimbdca0472023-07-28 19:20:56 +090021use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000022use binder::{self, BinderFeatures, ExceptionCode, Interface, IntoBinderResult, Strong};
Inseob Kimbdca0472023-07-28 19:20:56 +090023use lazy_static::lazy_static;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000024use log::error;
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090025use std::fs::{read_link, write, File};
26use std::io::{Read, Seek, SeekFrom, Write};
27use std::mem::size_of;
28use std::path::{Path, PathBuf};
29use rustutils::system_properties;
30use zerocopy::{
31 byteorder::{BigEndian, U32},
Frederick Mayle2e779942023-10-15 18:27:31 +000032 FromZeroes,
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090033 FromBytes,
34};
Inseob Kimbdca0472023-07-28 19:20:56 +090035
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000036// Device bound to VFIO driver.
37struct BoundDevice {
38 sysfs_path: String,
39 dtbo_label: String,
40}
41
42impl Interface for BoundDevice {}
43
44impl IBoundDevice for BoundDevice {
45 fn getSysfsPath(&self) -> binder::Result<String> {
46 Ok(self.sysfs_path.clone())
47 }
48
49 fn getDtboLabel(&self) -> binder::Result<String> {
50 Ok(self.dtbo_label.clone())
51 }
52}
53
54impl Drop for BoundDevice {
55 fn drop(&mut self) {
56 unbind_device(Path::new(&self.sysfs_path)).unwrap_or_else(|e| {
57 error!("did not restore {} driver: {}", self.sysfs_path, e);
58 });
59 }
60}
61
62impl BoundDevice {
63 fn new_binder(sysfs_path: String, dtbo_label: String) -> Strong<dyn IBoundDevice> {
64 BnBoundDevice::new_binder(BoundDevice { sysfs_path, dtbo_label }, BinderFeatures::default())
65 }
66}
67
Inseob Kimbdca0472023-07-28 19:20:56 +090068#[derive(Debug, Default)]
69pub struct VfioHandler {}
70
71impl VfioHandler {
72 pub fn init() -> VfioHandler {
73 VfioHandler::default()
74 }
75}
76
77impl Interface for VfioHandler {}
78
79impl IVfioHandler for VfioHandler {
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000080 fn bindDevicesToVfioDriver(
81 &self,
82 devices: &[VfioDev],
83 ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>> {
Inseob Kimbdca0472023-07-28 19:20:56 +090084 // permission check is already done by IVirtualizationServiceInternal.
85 if !*IS_VFIO_SUPPORTED {
Jiyong Park2227eaa2023-08-04 11:59:18 +090086 return Err(anyhow!("VFIO-platform not supported"))
87 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
Inseob Kimbdca0472023-07-28 19:20:56 +090088 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +000089 devices
90 .iter()
91 .map(|d| {
92 bind_device(Path::new(&d.sysfsPath))?;
93 Ok(BoundDevice::new_binder(d.sysfsPath.clone(), d.dtboLabel.clone()))
94 })
95 .collect::<binder::Result<Vec<_>>>()
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090096 }
Inseob Kimbdca0472023-07-28 19:20:56 +090097
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +090098 fn writeVmDtbo(&self, dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()> {
99 let dtbo_path = get_dtbo_img_path()?;
100 let mut dtbo_img = File::open(dtbo_path)
101 .context("Failed to open DTBO partition")
102 .or_service_specific_exception(-1)?;
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900103
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900104 let dt_table_header = get_dt_table_header(&mut dtbo_img)?;
105 let vm_dtbo_idx = system_properties::read("ro.boot.hypervisor.vm_dtbo_idx")
106 .context("Failed to read vm_dtbo_idx")
107 .or_service_specific_exception(-1)?
108 .ok_or_else(|| anyhow!("vm_dtbo_idx is none"))
109 .or_service_specific_exception(-1)?;
110 let vm_dtbo_idx = vm_dtbo_idx
111 .parse()
112 .context("vm_dtbo_idx is not an integer")
113 .or_service_specific_exception(-1)?;
114 let dt_table_entry = get_dt_table_entry(&mut dtbo_img, &dt_table_header, vm_dtbo_idx)?;
115 write_vm_full_dtbo_from_img(&mut dtbo_img, &dt_table_entry, dtbo_fd)?;
Inseob Kimf36347b2023-08-03 12:52:48 +0900116 Ok(())
Inseob Kimbdca0472023-07-28 19:20:56 +0900117 }
118}
119
120const DEV_VFIO_PATH: &str = "/dev/vfio/vfio";
121const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
122const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
123const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe";
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900124const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000125const VFIO_PLATFORM_DRIVER_NAME: &str = "vfio-platform";
126// To remove the override and match the device driver by "compatible" string again,
127// driver_override file must be cleared. Writing an empty string (same as
128// `echo -n "" > driver_override`) won't' clear the file, so append a newline char.
129const DEFAULT_DRIVER: &str = "\n";
Inseob Kimbdca0472023-07-28 19:20:56 +0900130
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900131/// The structure of DT table header in dtbo.img.
132/// https://source.android.com/docs/core/architecture/dto/partitions
133#[repr(C)]
Frederick Mayle2e779942023-10-15 18:27:31 +0000134#[derive(Debug, FromZeroes, FromBytes)]
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900135struct DtTableHeader {
136 /// DT_TABLE_MAGIC
137 magic: U32<BigEndian>,
138 /// includes dt_table_header + all dt_table_entry and all dtb/dtbo
139 _total_size: U32<BigEndian>,
140 /// sizeof(dt_table_header)
141 header_size: U32<BigEndian>,
142 /// sizeof(dt_table_entry)
143 dt_entry_size: U32<BigEndian>,
144 /// number of dt_table_entry
145 dt_entry_count: U32<BigEndian>,
146 /// offset to the first dt_table_entry from head of dt_table_header
147 dt_entries_offset: U32<BigEndian>,
148 /// flash page size we assume
149 _page_size: U32<BigEndian>,
150 /// DTBO image version, the current version is 0. The version will be
151 /// incremented when the dt_table_header struct is updated.
152 _version: U32<BigEndian>,
Inseob Kimbdca0472023-07-28 19:20:56 +0900153}
154
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900155/// The structure of each DT table entry (v0) in dtbo.img.
156/// https://source.android.com/docs/core/architecture/dto/partitions
157#[repr(C)]
Frederick Mayle2e779942023-10-15 18:27:31 +0000158#[derive(Debug, FromZeroes, FromBytes)]
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900159struct DtTableEntry {
160 /// size of each DT
161 dt_size: U32<BigEndian>,
162 /// offset from head of dt_table_header
163 dt_offset: U32<BigEndian>,
164 /// optional, must be zero if unused
165 _id: U32<BigEndian>,
166 /// optional, must be zero if unused
167 _rev: U32<BigEndian>,
168 /// optional, must be zero if unused
169 _custom: [U32<BigEndian>; 4],
170}
171
172lazy_static! {
173 static ref IS_VFIO_SUPPORTED: bool =
174 Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists();
Inseob Kimbdca0472023-07-28 19:20:56 +0900175}
176
177fn check_platform_device(path: &Path) -> binder::Result<()> {
178 if !path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900179 return Err(anyhow!("no such device {path:?}"))
180 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900181 }
182
183 if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900184 return Err(anyhow!("{path:?} is not a platform device"))
185 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900186 }
187
188 Ok(())
189}
190
191fn get_device_iommu_group(path: &Path) -> Option<u64> {
192 let group_path = read_link(path.join("iommu_group")).ok()?;
193 let group = group_path.file_name()?;
194 group.to_str()?.parse().ok()
195}
196
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000197fn current_driver(path: &Path) -> Option<String> {
198 let driver_path = read_link(path.join("driver")).ok()?;
199 let bound_driver = driver_path.file_name()?;
200 bound_driver.to_str().map(str::to_string)
Inseob Kimbdca0472023-07-28 19:20:56 +0900201}
202
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000203// Try to bind device driver by writing its name to driver_override and triggering driver probe.
204fn try_bind_driver(path: &Path, driver: &str) -> binder::Result<()> {
205 if Some(driver) == current_driver(path).as_deref() {
Inseob Kimbdca0472023-07-28 19:20:56 +0900206 // already bound
207 return Ok(());
208 }
209
210 // unbind
211 let Some(device) = path.file_name() else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900212 return Err(anyhow!("can't get device name from {path:?}"))
213 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900214 };
215 let Some(device_str) = device.to_str() else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900216 return Err(anyhow!("invalid filename {device:?}"))
217 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900218 };
Inseob Kim55438b22023-08-09 20:16:01 +0900219 let unbind_path = path.join("driver/unbind");
220 if unbind_path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900221 write(&unbind_path, device_str.as_bytes())
222 .with_context(|| format!("could not unbind {device_str}"))
223 .or_service_specific_exception(-1)?;
Inseob Kim55438b22023-08-09 20:16:01 +0900224 }
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000225 if path.join("driver").exists() {
226 return Err(anyhow!("could not unbind {device_str}")).or_service_specific_exception(-1);
227 }
Inseob Kimbdca0472023-07-28 19:20:56 +0900228
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000229 // bind to new driver
230 write(path.join("driver_override"), driver.as_bytes())
231 .with_context(|| format!("could not bind {device_str} to '{driver}' driver"))
Jiyong Park2227eaa2023-08-04 11:59:18 +0900232 .or_service_specific_exception(-1)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900233
Jiyong Park2227eaa2023-08-04 11:59:18 +0900234 write(SYSFS_PLATFORM_DRIVERS_PROBE_PATH, device_str.as_bytes())
235 .with_context(|| format!("could not write {device_str} to drivers-probe"))
236 .or_service_specific_exception(-1)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900237
238 // final check
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000239 let new_driver = current_driver(path);
240 if new_driver.is_none() || Some(driver) != new_driver.as_deref() && driver != DEFAULT_DRIVER {
241 return Err(anyhow!("{path:?} still not bound to '{driver}' driver"))
Jiyong Park2227eaa2023-08-04 11:59:18 +0900242 .or_service_specific_exception(-1);
Inseob Kimbdca0472023-07-28 19:20:56 +0900243 }
244
245 Ok(())
246}
247
248fn bind_device(path: &Path) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900249 let path = path
250 .canonicalize()
251 .with_context(|| format!("can't canonicalize {path:?}"))
252 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900253
254 check_platform_device(&path)?;
Jakob Vukalovicd42aa2c2023-11-09 16:04:00 +0000255 try_bind_driver(&path, VFIO_PLATFORM_DRIVER_NAME)?;
256
257 if get_device_iommu_group(&path).is_none() {
258 Err(anyhow!("can't get iommu group for {path:?}")).or_service_specific_exception(-1)
259 } else {
260 Ok(())
261 }
262}
263
264fn unbind_device(path: &Path) -> binder::Result<()> {
265 let path = path
266 .canonicalize()
267 .with_context(|| format!("can't canonicalize {path:?}"))
268 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
269
270 check_platform_device(&path)?;
271 try_bind_driver(&path, DEFAULT_DRIVER)?;
272
273 if Some(VFIO_PLATFORM_DRIVER_NAME) == current_driver(&path).as_deref() {
274 Err(anyhow!("{path:?} still bound to vfio driver")).or_service_specific_exception(-1)
275 } else {
276 Ok(())
277 }
Inseob Kimbdca0472023-07-28 19:20:56 +0900278}
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900279
280fn get_dtbo_img_path() -> binder::Result<PathBuf> {
281 let slot_suffix = system_properties::read("ro.boot.slot_suffix")
282 .context("Failed to read ro.boot.slot_suffix")
283 .or_service_specific_exception(-1)?
284 .ok_or_else(|| anyhow!("slot_suffix is none"))
285 .or_service_specific_exception(-1)?;
286 Ok(PathBuf::from(format!("/dev/block/by-name/dtbo{slot_suffix}")))
287}
288
289fn read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>> {
290 file.seek(SeekFrom::Start(offset))
291 .context("Cannot seek the offset")
292 .or_service_specific_exception(-1)?;
293 let mut buffer = vec![0_u8; size];
294 file.read_exact(&mut buffer)
295 .context("Failed to read buffer")
296 .or_service_specific_exception(-1)?;
297 Ok(buffer)
298}
299
300fn get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader> {
301 let values = read_values(file, size_of::<DtTableHeader>(), 0)?;
302 let dt_table_header = DtTableHeader::read_from(values.as_slice())
303 .context("DtTableHeader is invalid")
304 .or_service_specific_exception(-1)?;
305 if dt_table_header.magic.get() != DT_TABLE_MAGIC
306 || dt_table_header.header_size.get() as usize != size_of::<DtTableHeader>()
307 {
Chariseee031edc2023-10-16 21:52:10 +0000308 return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1);
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900309 }
310 Ok(dt_table_header)
311}
312
313fn get_dt_table_entry(
314 file: &mut File,
315 header: &DtTableHeader,
316 index: u32,
317) -> binder::Result<DtTableEntry> {
318 if index >= header.dt_entry_count.get() {
Chariseee031edc2023-10-16 21:52:10 +0000319 return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1);
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900320 }
321 let Some(prev_dt_entry_total_size) = header.dt_entry_size.get().checked_mul(index) else {
322 return Err(anyhow!("Unexpected arithmetic result"))
323 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
324 };
325 let Some(dt_entry_offset) =
326 prev_dt_entry_total_size.checked_add(header.dt_entries_offset.get())
327 else {
328 return Err(anyhow!("Unexpected arithmetic result"))
329 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
330 };
331 let values = read_values(file, size_of::<DtTableEntry>(), dt_entry_offset.into())?;
332 let dt_table_entry = DtTableEntry::read_from(values.as_slice())
333 .with_context(|| format!("DtTableEntry at index {index} is invalid."))
334 .or_service_specific_exception(-1)?;
335 Ok(dt_table_entry)
336}
337
Seungjae Yoo9d3c20a2023-09-07 15:36:44 +0900338fn write_vm_full_dtbo_from_img(
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900339 dtbo_img_file: &mut File,
340 entry: &DtTableEntry,
341 dtbo_fd: &ParcelFileDescriptor,
342) -> binder::Result<()> {
343 let dt_size = entry
344 .dt_size
345 .get()
346 .try_into()
347 .context("Failed to convert type")
348 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
349 let buffer = read_values(dtbo_img_file, dt_size, entry.dt_offset.get().into())?;
350
Andrei Homescu11333c62023-11-09 04:26:39 +0000351 let mut dtbo_fd = File::from(
352 dtbo_fd
353 .as_ref()
354 .try_clone()
355 .context("Failed to create File from ParcelFileDescriptor")
356 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
357 );
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900358
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900359 dtbo_fd
360 .write_all(&buffer)
361 .context("Failed to write dtbo file")
362 .or_service_specific_exception(-1)?;
363 Ok(())
364}