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 lazy_static::lazy_static;
24 use log::error;
25 use std::fs::{read_link, write, File};
26 use std::io::{Read, Seek, SeekFrom, Write};
27 use std::mem::size_of;
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 lazy_static! {
173     static ref IS_VFIO_SUPPORTED: bool =
174         Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists();
175 }
176 
check_platform_device(path: &Path) -> binder::Result<()>177 fn check_platform_device(path: &Path) -> binder::Result<()> {
178     if !path.exists() {
179         return Err(anyhow!("no such device {path:?}"))
180             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
181     }
182 
183     if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
184         return Err(anyhow!("{path:?} is not a platform device"))
185             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
186     }
187 
188     Ok(())
189 }
190 
get_device_iommu_group(path: &Path) -> Option<u64>191 fn 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 
current_driver(path: &Path) -> Option<String>197 fn 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)
201 }
202 
203 // 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<()>204 fn try_bind_driver(path: &Path, driver: &str) -> binder::Result<()> {
205     if Some(driver) == current_driver(path).as_deref() {
206         // already bound
207         return Ok(());
208     }
209 
210     // unbind
211     let Some(device) = path.file_name() else {
212         return Err(anyhow!("can't get device name from {path:?}"))
213             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
214     };
215     let Some(device_str) = device.to_str() else {
216         return Err(anyhow!("invalid filename {device:?}"))
217             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
218     };
219     let unbind_path = path.join("driver/unbind");
220     if unbind_path.exists() {
221         write(&unbind_path, device_str.as_bytes())
222             .with_context(|| format!("could not unbind {device_str}"))
223             .or_service_specific_exception(-1)?;
224     }
225     if path.join("driver").exists() {
226         return Err(anyhow!("could not unbind {device_str}")).or_service_specific_exception(-1);
227     }
228 
229     // 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"))
232         .or_service_specific_exception(-1)?;
233 
234     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)?;
237 
238     // final check
239     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"))
242             .or_service_specific_exception(-1);
243     }
244 
245     Ok(())
246 }
247 
bind_device(path: &Path) -> binder::Result<()>248 fn bind_device(path: &Path) -> binder::Result<()> {
249     let path = path
250         .canonicalize()
251         .with_context(|| format!("can't canonicalize {path:?}"))
252         .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
253 
254     check_platform_device(&path)?;
255     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 
unbind_device(path: &Path) -> binder::Result<()>264 fn 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     }
278 }
279 
get_dtbo_img_path() -> binder::Result<PathBuf>280 fn 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 
read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>>289 fn 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 
get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader>300 fn 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     {
308         return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1);
309     }
310     Ok(dt_table_header)
311 }
312 
get_dt_table_entry( file: &mut File, header: &DtTableHeader, index: u32, ) -> binder::Result<DtTableEntry>313 fn 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() {
319         return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1);
320     }
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 
write_vm_full_dtbo_from_img( dtbo_img_file: &mut File, entry: &DtTableEntry, dtbo_fd: &ParcelFileDescriptor, ) -> binder::Result<()>338 fn write_vm_full_dtbo_from_img(
339     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 
351     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     );
358 
359     dtbo_fd
360         .write_all(&buffer)
361         .context("Failed to write dtbo file")
362         .or_service_specific_exception(-1)?;
363     Ok(())
364 }
365