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
15 //! Implementation of the AIDL interface of VfioHandler.
16
17 use anyhow::{anyhow, Context};
18 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IBoundDevice::{IBoundDevice, BnBoundDevice};
19 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::IVfioHandler;
20 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::VfioDev::VfioDev;
21 use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor;
22 use binder::{self, BinderFeatures, ExceptionCode, Interface, IntoBinderResult, Strong};
23 use log::error;
24 use std::fs::{read_link, write, File};
25 use std::io::{Read, Seek, SeekFrom, Write};
26 use std::mem::size_of;
27 use std::sync::LazyLock;
28 use std::path::{Path, PathBuf};
29 use rustutils::system_properties;
30 use zerocopy::{
31 byteorder::{BigEndian, U32},
32 FromZeroes,
33 FromBytes,
34 };
35
36 // Device bound to VFIO driver.
37 struct BoundDevice {
38 sysfs_path: String,
39 dtbo_label: String,
40 }
41
42 impl Interface for BoundDevice {}
43
44 impl IBoundDevice for BoundDevice {
getSysfsPath(&self) -> binder::Result<String>45 fn getSysfsPath(&self) -> binder::Result<String> {
46 Ok(self.sysfs_path.clone())
47 }
48
getDtboLabel(&self) -> binder::Result<String>49 fn getDtboLabel(&self) -> binder::Result<String> {
50 Ok(self.dtbo_label.clone())
51 }
52 }
53
54 impl Drop for BoundDevice {
drop(&mut self)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
62 impl BoundDevice {
new_binder(sysfs_path: String, dtbo_label: String) -> Strong<dyn IBoundDevice>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
68 #[derive(Debug, Default)]
69 pub struct VfioHandler {}
70
71 impl VfioHandler {
init() -> VfioHandler72 pub fn init() -> VfioHandler {
73 VfioHandler::default()
74 }
75 }
76
77 impl Interface for VfioHandler {}
78
79 impl IVfioHandler for VfioHandler {
bindDevicesToVfioDriver( &self, devices: &[VfioDev], ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>>80 fn bindDevicesToVfioDriver(
81 &self,
82 devices: &[VfioDev],
83 ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>> {
84 // permission check is already done by IVirtualizationServiceInternal.
85 if !*IS_VFIO_SUPPORTED {
86 return Err(anyhow!("VFIO-platform not supported"))
87 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
88 }
89 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<_>>>()
96 }
97
writeVmDtbo(&self, dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()>98 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)?;
103
104 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)?;
116 Ok(())
117 }
118 }
119
120 const DEV_VFIO_PATH: &str = "/dev/vfio/vfio";
121 const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
122 const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
123 const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe";
124 const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e;
125 const 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.
129 const DEFAULT_DRIVER: &str = "\n";
130
131 /// The structure of DT table header in dtbo.img.
132 /// https://source.android.com/docs/core/architecture/dto/partitions
133 #[repr(C)]
134 #[derive(Debug, FromZeroes, FromBytes)]
135 struct 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>,
153 }
154
155 /// The structure of each DT table entry (v0) in dtbo.img.
156 /// https://source.android.com/docs/core/architecture/dto/partitions
157 #[repr(C)]
158 #[derive(Debug, FromZeroes, FromBytes)]
159 struct 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
172 static IS_VFIO_SUPPORTED: LazyLock<bool> = LazyLock::new(|| {
173 Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists()
174 });
175
check_platform_device(path: &Path) -> binder::Result<()>176 fn check_platform_device(path: &Path) -> binder::Result<()> {
177 if !path.exists() {
178 return Err(anyhow!("no such device {path:?}"))
179 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
180 }
181
182 if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
183 return Err(anyhow!("{path:?} is not a platform device"))
184 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
185 }
186
187 Ok(())
188 }
189
get_device_iommu_group(path: &Path) -> Option<u64>190 fn get_device_iommu_group(path: &Path) -> Option<u64> {
191 let group_path = read_link(path.join("iommu_group")).ok()?;
192 let group = group_path.file_name()?;
193 group.to_str()?.parse().ok()
194 }
195
current_driver(path: &Path) -> Option<String>196 fn current_driver(path: &Path) -> Option<String> {
197 let driver_path = read_link(path.join("driver")).ok()?;
198 let bound_driver = driver_path.file_name()?;
199 bound_driver.to_str().map(str::to_string)
200 }
201
202 // Try to bind device driver by writing its name to driver_override and triggering driver probe.
try_bind_driver(path: &Path, driver: &str) -> binder::Result<()>203 fn try_bind_driver(path: &Path, driver: &str) -> binder::Result<()> {
204 if Some(driver) == current_driver(path).as_deref() {
205 // already bound
206 return Ok(());
207 }
208
209 // unbind
210 let Some(device) = path.file_name() else {
211 return Err(anyhow!("can't get device name from {path:?}"))
212 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
213 };
214 let Some(device_str) = device.to_str() else {
215 return Err(anyhow!("invalid filename {device:?}"))
216 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
217 };
218 let unbind_path = path.join("driver/unbind");
219 if unbind_path.exists() {
220 write(&unbind_path, device_str.as_bytes())
221 .with_context(|| format!("could not unbind {device_str}"))
222 .or_service_specific_exception(-1)?;
223 }
224 if path.join("driver").exists() {
225 return Err(anyhow!("could not unbind {device_str}")).or_service_specific_exception(-1);
226 }
227
228 // bind to new driver
229 write(path.join("driver_override"), driver.as_bytes())
230 .with_context(|| format!("could not bind {device_str} to '{driver}' driver"))
231 .or_service_specific_exception(-1)?;
232
233 write(SYSFS_PLATFORM_DRIVERS_PROBE_PATH, device_str.as_bytes())
234 .with_context(|| format!("could not write {device_str} to drivers-probe"))
235 .or_service_specific_exception(-1)?;
236
237 // final check
238 let new_driver = current_driver(path);
239 if new_driver.is_none() || Some(driver) != new_driver.as_deref() && driver != DEFAULT_DRIVER {
240 return Err(anyhow!("{path:?} still not bound to '{driver}' driver"))
241 .or_service_specific_exception(-1);
242 }
243
244 Ok(())
245 }
246
bind_device(path: &Path) -> binder::Result<()>247 fn bind_device(path: &Path) -> binder::Result<()> {
248 let path = path
249 .canonicalize()
250 .with_context(|| format!("can't canonicalize {path:?}"))
251 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
252
253 check_platform_device(&path)?;
254 try_bind_driver(&path, VFIO_PLATFORM_DRIVER_NAME)?;
255
256 if get_device_iommu_group(&path).is_none() {
257 Err(anyhow!("can't get iommu group for {path:?}")).or_service_specific_exception(-1)
258 } else {
259 Ok(())
260 }
261 }
262
unbind_device(path: &Path) -> binder::Result<()>263 fn unbind_device(path: &Path) -> binder::Result<()> {
264 let path = path
265 .canonicalize()
266 .with_context(|| format!("can't canonicalize {path:?}"))
267 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
268
269 check_platform_device(&path)?;
270 try_bind_driver(&path, DEFAULT_DRIVER)?;
271
272 if Some(VFIO_PLATFORM_DRIVER_NAME) == current_driver(&path).as_deref() {
273 Err(anyhow!("{path:?} still bound to vfio driver")).or_service_specific_exception(-1)
274 } else {
275 Ok(())
276 }
277 }
278
get_dtbo_img_path() -> binder::Result<PathBuf>279 fn get_dtbo_img_path() -> binder::Result<PathBuf> {
280 let slot_suffix = system_properties::read("ro.boot.slot_suffix")
281 .context("Failed to read ro.boot.slot_suffix")
282 .or_service_specific_exception(-1)?
283 .ok_or_else(|| anyhow!("slot_suffix is none"))
284 .or_service_specific_exception(-1)?;
285 Ok(PathBuf::from(format!("/dev/block/by-name/dtbo{slot_suffix}")))
286 }
287
read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>>288 fn read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>> {
289 file.seek(SeekFrom::Start(offset))
290 .context("Cannot seek the offset")
291 .or_service_specific_exception(-1)?;
292 let mut buffer = vec![0_u8; size];
293 file.read_exact(&mut buffer)
294 .context("Failed to read buffer")
295 .or_service_specific_exception(-1)?;
296 Ok(buffer)
297 }
298
get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader>299 fn get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader> {
300 let values = read_values(file, size_of::<DtTableHeader>(), 0)?;
301 let dt_table_header = DtTableHeader::read_from(values.as_slice())
302 .context("DtTableHeader is invalid")
303 .or_service_specific_exception(-1)?;
304 if dt_table_header.magic.get() != DT_TABLE_MAGIC
305 || dt_table_header.header_size.get() as usize != size_of::<DtTableHeader>()
306 {
307 return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1);
308 }
309 Ok(dt_table_header)
310 }
311
get_dt_table_entry( file: &mut File, header: &DtTableHeader, index: u32, ) -> binder::Result<DtTableEntry>312 fn get_dt_table_entry(
313 file: &mut File,
314 header: &DtTableHeader,
315 index: u32,
316 ) -> binder::Result<DtTableEntry> {
317 if index >= header.dt_entry_count.get() {
318 return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1);
319 }
320 let Some(prev_dt_entry_total_size) = header.dt_entry_size.get().checked_mul(index) else {
321 return Err(anyhow!("Unexpected arithmetic result"))
322 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
323 };
324 let Some(dt_entry_offset) =
325 prev_dt_entry_total_size.checked_add(header.dt_entries_offset.get())
326 else {
327 return Err(anyhow!("Unexpected arithmetic result"))
328 .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
329 };
330 let values = read_values(file, size_of::<DtTableEntry>(), dt_entry_offset.into())?;
331 let dt_table_entry = DtTableEntry::read_from(values.as_slice())
332 .with_context(|| format!("DtTableEntry at index {index} is invalid."))
333 .or_service_specific_exception(-1)?;
334 Ok(dt_table_entry)
335 }
336
write_vm_full_dtbo_from_img( dtbo_img_file: &mut File, entry: &DtTableEntry, dtbo_fd: &ParcelFileDescriptor, ) -> binder::Result<()>337 fn write_vm_full_dtbo_from_img(
338 dtbo_img_file: &mut File,
339 entry: &DtTableEntry,
340 dtbo_fd: &ParcelFileDescriptor,
341 ) -> binder::Result<()> {
342 let dt_size = entry
343 .dt_size
344 .get()
345 .try_into()
346 .context("Failed to convert type")
347 .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
348 let buffer = read_values(dtbo_img_file, dt_size, entry.dt_offset.get().into())?;
349
350 let mut dtbo_fd = File::from(
351 dtbo_fd
352 .as_ref()
353 .try_clone()
354 .context("Failed to create File from ParcelFileDescriptor")
355 .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
356 );
357
358 dtbo_fd
359 .write_all(&buffer)
360 .context("Failed to write dtbo file")
361 .or_service_specific_exception(-1)?;
362 Ok(())
363 }
364