• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     FromBytes,
33 };
34 
35 // Device bound to VFIO driver.
36 struct BoundDevice {
37     sysfs_path: String,
38     dtbo_label: String,
39 }
40 
41 impl Interface for BoundDevice {}
42 
43 impl IBoundDevice for BoundDevice {
getSysfsPath(&self) -> binder::Result<String>44     fn getSysfsPath(&self) -> binder::Result<String> {
45         Ok(self.sysfs_path.clone())
46     }
47 
getDtboLabel(&self) -> binder::Result<String>48     fn getDtboLabel(&self) -> binder::Result<String> {
49         Ok(self.dtbo_label.clone())
50     }
51 }
52 
53 impl Drop for BoundDevice {
drop(&mut self)54     fn drop(&mut self) {
55         unbind_device(Path::new(&self.sysfs_path)).unwrap_or_else(|e| {
56             error!("did not restore {} driver: {}", self.sysfs_path, e);
57         });
58     }
59 }
60 
61 impl BoundDevice {
new_binder(sysfs_path: String, dtbo_label: String) -> Strong<dyn IBoundDevice>62     fn new_binder(sysfs_path: String, dtbo_label: String) -> Strong<dyn IBoundDevice> {
63         BnBoundDevice::new_binder(BoundDevice { sysfs_path, dtbo_label }, BinderFeatures::default())
64     }
65 }
66 
67 #[derive(Debug, Default)]
68 pub struct VfioHandler {}
69 
70 impl VfioHandler {
init() -> VfioHandler71     pub fn init() -> VfioHandler {
72         VfioHandler::default()
73     }
74 }
75 
76 impl Interface for VfioHandler {}
77 
78 impl IVfioHandler for VfioHandler {
bindDevicesToVfioDriver( &self, devices: &[VfioDev], ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>>79     fn bindDevicesToVfioDriver(
80         &self,
81         devices: &[VfioDev],
82     ) -> binder::Result<Vec<Strong<dyn IBoundDevice>>> {
83         // permission check is already done by IVirtualizationServiceInternal.
84         if !*IS_VFIO_SUPPORTED {
85             return Err(anyhow!("VFIO-platform not supported"))
86                 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
87         }
88         devices
89             .iter()
90             .map(|d| {
91                 bind_device(Path::new(&d.sysfsPath))?;
92                 Ok(BoundDevice::new_binder(d.sysfsPath.clone(), d.dtboLabel.clone()))
93             })
94             .collect::<binder::Result<Vec<_>>>()
95     }
96 
writeVmDtbo(&self, dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()>97     fn writeVmDtbo(&self, dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()> {
98         let dtbo_path = get_dtbo_img_path()?;
99         let mut dtbo_img = File::open(dtbo_path)
100             .context("Failed to open DTBO partition")
101             .or_service_specific_exception(-1)?;
102 
103         let dt_table_header = get_dt_table_header(&mut dtbo_img)?;
104         let vm_dtbo_idx = system_properties::read("ro.boot.hypervisor.vm_dtbo_idx")
105             .context("Failed to read vm_dtbo_idx")
106             .or_service_specific_exception(-1)?
107             .ok_or_else(|| anyhow!("vm_dtbo_idx is none"))
108             .or_service_specific_exception(-1)?;
109         let vm_dtbo_idx = vm_dtbo_idx
110             .parse()
111             .context("vm_dtbo_idx is not an integer")
112             .or_service_specific_exception(-1)?;
113         let dt_table_entry = get_dt_table_entry(&mut dtbo_img, &dt_table_header, vm_dtbo_idx)?;
114         write_vm_full_dtbo_from_img(&mut dtbo_img, &dt_table_entry, dtbo_fd)?;
115         Ok(())
116     }
117 }
118 
119 const DEV_VFIO_PATH: &str = "/dev/vfio/vfio";
120 const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
121 const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
122 const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe";
123 const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e;
124 const VFIO_PLATFORM_DRIVER_NAME: &str = "vfio-platform";
125 // To remove the override and match the device driver by "compatible" string again,
126 // driver_override file must be cleared. Writing an empty string (same as
127 // `echo -n "" > driver_override`) won't' clear the file, so append a newline char.
128 const DEFAULT_DRIVER: &str = "\n";
129 
130 /// The structure of DT table header in dtbo.img.
131 /// https://source.android.com/docs/core/architecture/dto/partitions
132 #[repr(C)]
133 #[derive(Debug, FromBytes)]
134 struct DtTableHeader {
135     /// DT_TABLE_MAGIC
136     magic: U32<BigEndian>,
137     /// includes dt_table_header + all dt_table_entry and all dtb/dtbo
138     _total_size: U32<BigEndian>,
139     /// sizeof(dt_table_header)
140     header_size: U32<BigEndian>,
141     /// sizeof(dt_table_entry)
142     dt_entry_size: U32<BigEndian>,
143     /// number of dt_table_entry
144     dt_entry_count: U32<BigEndian>,
145     /// offset to the first dt_table_entry from head of dt_table_header
146     dt_entries_offset: U32<BigEndian>,
147     /// flash page size we assume
148     _page_size: U32<BigEndian>,
149     /// DTBO image version, the current version is 0. The version will be
150     /// incremented when the dt_table_header struct is updated.
151     _version: U32<BigEndian>,
152 }
153 
154 /// The structure of each DT table entry (v0) in dtbo.img.
155 /// https://source.android.com/docs/core/architecture/dto/partitions
156 #[repr(C)]
157 #[derive(Debug, FromBytes)]
158 struct DtTableEntry {
159     /// size of each DT
160     dt_size: U32<BigEndian>,
161     /// offset from head of dt_table_header
162     dt_offset: U32<BigEndian>,
163     /// optional, must be zero if unused
164     _id: U32<BigEndian>,
165     /// optional, must be zero if unused
166     _rev: U32<BigEndian>,
167     /// optional, must be zero if unused
168     _custom: [U32<BigEndian>; 4],
169 }
170 
171 static IS_VFIO_SUPPORTED: LazyLock<bool> = LazyLock::new(|| {
172     Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists()
173 });
174 
check_platform_device(path: &Path) -> binder::Result<()>175 fn check_platform_device(path: &Path) -> binder::Result<()> {
176     if !path.exists() {
177         return Err(anyhow!("no such device {path:?}"))
178             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
179     }
180 
181     if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
182         return Err(anyhow!("{path:?} is not a platform device"))
183             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
184     }
185 
186     Ok(())
187 }
188 
get_device_iommu_group(path: &Path) -> Option<u64>189 fn get_device_iommu_group(path: &Path) -> Option<u64> {
190     let group_path = read_link(path.join("iommu_group")).ok()?;
191     let group = group_path.file_name()?;
192     group.to_str()?.parse().ok()
193 }
194 
current_driver(path: &Path) -> Option<String>195 fn current_driver(path: &Path) -> Option<String> {
196     let driver_path = read_link(path.join("driver")).ok()?;
197     let bound_driver = driver_path.file_name()?;
198     bound_driver.to_str().map(str::to_string)
199 }
200 
201 // 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<()>202 fn try_bind_driver(path: &Path, driver: &str) -> binder::Result<()> {
203     if Some(driver) == current_driver(path).as_deref() {
204         // already bound
205         return Ok(());
206     }
207 
208     // unbind
209     let Some(device) = path.file_name() else {
210         return Err(anyhow!("can't get device name from {path:?}"))
211             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
212     };
213     let Some(device_str) = device.to_str() else {
214         return Err(anyhow!("invalid filename {device:?}"))
215             .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
216     };
217     let unbind_path = path.join("driver/unbind");
218     if unbind_path.exists() {
219         write(&unbind_path, device_str.as_bytes())
220             .with_context(|| format!("could not unbind {device_str}"))
221             .or_service_specific_exception(-1)?;
222     }
223     if path.join("driver").exists() {
224         return Err(anyhow!("could not unbind {device_str}")).or_service_specific_exception(-1);
225     }
226 
227     // bind to new driver
228     write(path.join("driver_override"), driver.as_bytes())
229         .with_context(|| format!("could not bind {device_str} to '{driver}' driver"))
230         .or_service_specific_exception(-1)?;
231 
232     write(SYSFS_PLATFORM_DRIVERS_PROBE_PATH, device_str.as_bytes())
233         .with_context(|| format!("could not write {device_str} to drivers-probe"))
234         .or_service_specific_exception(-1)?;
235 
236     // final check
237     let new_driver = current_driver(path);
238     if new_driver.is_none() || Some(driver) != new_driver.as_deref() && driver != DEFAULT_DRIVER {
239         return Err(anyhow!("{path:?} still not bound to '{driver}' driver"))
240             .or_service_specific_exception(-1);
241     }
242 
243     Ok(())
244 }
245 
bind_device(path: &Path) -> binder::Result<()>246 fn bind_device(path: &Path) -> binder::Result<()> {
247     let path = path
248         .canonicalize()
249         .with_context(|| format!("can't canonicalize {path:?}"))
250         .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
251 
252     check_platform_device(&path)?;
253     try_bind_driver(&path, VFIO_PLATFORM_DRIVER_NAME)?;
254 
255     if get_device_iommu_group(&path).is_none() {
256         Err(anyhow!("can't get iommu group for {path:?}")).or_service_specific_exception(-1)
257     } else {
258         Ok(())
259     }
260 }
261 
unbind_device(path: &Path) -> binder::Result<()>262 fn unbind_device(path: &Path) -> binder::Result<()> {
263     let path = path
264         .canonicalize()
265         .with_context(|| format!("can't canonicalize {path:?}"))
266         .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
267 
268     check_platform_device(&path)?;
269     try_bind_driver(&path, DEFAULT_DRIVER)?;
270 
271     if Some(VFIO_PLATFORM_DRIVER_NAME) == current_driver(&path).as_deref() {
272         Err(anyhow!("{path:?} still bound to vfio driver")).or_service_specific_exception(-1)
273     } else {
274         Ok(())
275     }
276 }
277 
get_dtbo_img_path() -> binder::Result<PathBuf>278 fn get_dtbo_img_path() -> binder::Result<PathBuf> {
279     let slot_suffix = system_properties::read("ro.boot.slot_suffix")
280         .context("Failed to read ro.boot.slot_suffix")
281         .or_service_specific_exception(-1)?
282         .ok_or_else(|| anyhow!("slot_suffix is none"))
283         .or_service_specific_exception(-1)?;
284     Ok(PathBuf::from(format!("/dev/block/by-name/dtbo{slot_suffix}")))
285 }
286 
read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>>287 fn read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>> {
288     file.seek(SeekFrom::Start(offset))
289         .context("Cannot seek the offset")
290         .or_service_specific_exception(-1)?;
291     let mut buffer = vec![0_u8; size];
292     file.read_exact(&mut buffer)
293         .context("Failed to read buffer")
294         .or_service_specific_exception(-1)?;
295     Ok(buffer)
296 }
297 
get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader>298 fn get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader> {
299     let values = read_values(file, size_of::<DtTableHeader>(), 0)?;
300     let dt_table_header = DtTableHeader::read_from(values.as_slice())
301         .context("DtTableHeader is invalid")
302         .or_service_specific_exception(-1)?;
303     if dt_table_header.magic.get() != DT_TABLE_MAGIC
304         || dt_table_header.header_size.get() as usize != size_of::<DtTableHeader>()
305     {
306         return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1);
307     }
308     Ok(dt_table_header)
309 }
310 
get_dt_table_entry( file: &mut File, header: &DtTableHeader, index: u32, ) -> binder::Result<DtTableEntry>311 fn get_dt_table_entry(
312     file: &mut File,
313     header: &DtTableHeader,
314     index: u32,
315 ) -> binder::Result<DtTableEntry> {
316     if index >= header.dt_entry_count.get() {
317         return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1);
318     }
319     let Some(prev_dt_entry_total_size) = header.dt_entry_size.get().checked_mul(index) else {
320         return Err(anyhow!("Unexpected arithmetic result"))
321             .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
322     };
323     let Some(dt_entry_offset) =
324         prev_dt_entry_total_size.checked_add(header.dt_entries_offset.get())
325     else {
326         return Err(anyhow!("Unexpected arithmetic result"))
327             .or_binder_exception(ExceptionCode::ILLEGAL_STATE);
328     };
329     let values = read_values(file, size_of::<DtTableEntry>(), dt_entry_offset.into())?;
330     let dt_table_entry = DtTableEntry::read_from(values.as_slice())
331         .with_context(|| format!("DtTableEntry at index {index} is invalid."))
332         .or_service_specific_exception(-1)?;
333     Ok(dt_table_entry)
334 }
335 
write_vm_full_dtbo_from_img( dtbo_img_file: &mut File, entry: &DtTableEntry, dtbo_fd: &ParcelFileDescriptor, ) -> binder::Result<()>336 fn write_vm_full_dtbo_from_img(
337     dtbo_img_file: &mut File,
338     entry: &DtTableEntry,
339     dtbo_fd: &ParcelFileDescriptor,
340 ) -> binder::Result<()> {
341     let dt_size = entry
342         .dt_size
343         .get()
344         .try_into()
345         .context("Failed to convert type")
346         .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?;
347     let buffer = read_values(dtbo_img_file, dt_size, entry.dt_offset.get().into())?;
348 
349     let mut dtbo_fd = File::from(
350         dtbo_fd
351             .as_ref()
352             .try_clone()
353             .context("Failed to create File from ParcelFileDescriptor")
354             .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?,
355     );
356 
357     dtbo_fd
358         .write_all(&buffer)
359         .context("Failed to write dtbo file")
360         .or_service_specific_exception(-1)?;
361     Ok(())
362 }
363