Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 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 the VirtualizationService. |
| 16 | |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 17 | use anyhow::{anyhow, Context}; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 18 | use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::IVfioHandler; |
| 19 | use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor; |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 20 | use binder::{self, ExceptionCode, Interface, IntoBinderResult}; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 21 | use lazy_static::lazy_static; |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 22 | use std::fs::{read_link, write, File}; |
| 23 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 24 | use std::mem::size_of; |
| 25 | use std::path::{Path, PathBuf}; |
| 26 | use rustutils::system_properties; |
| 27 | use zerocopy::{ |
| 28 | byteorder::{BigEndian, U32}, |
| 29 | FromBytes, |
| 30 | }; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 31 | |
| 32 | #[derive(Debug, Default)] |
| 33 | pub struct VfioHandler {} |
| 34 | |
| 35 | impl VfioHandler { |
| 36 | pub fn init() -> VfioHandler { |
| 37 | VfioHandler::default() |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl Interface for VfioHandler {} |
| 42 | |
| 43 | impl IVfioHandler for VfioHandler { |
Inseob Kim | f36347b | 2023-08-03 12:52:48 +0900 | [diff] [blame] | 44 | fn bindDevicesToVfioDriver( |
| 45 | &self, |
| 46 | devices: &[String], |
| 47 | dtbo: &ParcelFileDescriptor, |
| 48 | ) -> binder::Result<()> { |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 49 | // permission check is already done by IVirtualizationServiceInternal. |
| 50 | if !*IS_VFIO_SUPPORTED { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 51 | return Err(anyhow!("VFIO-platform not supported")) |
| 52 | .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 53 | } |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 54 | devices.iter().try_for_each(|x| bind_device(Path::new(x)))?; |
| 55 | |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 56 | write_dtbo(dtbo)?; |
| 57 | |
Inseob Kim | f36347b | 2023-08-03 12:52:48 +0900 | [diff] [blame] | 58 | Ok(()) |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 59 | } |
| 60 | } |
| 61 | |
| 62 | const DEV_VFIO_PATH: &str = "/dev/vfio/vfio"; |
| 63 | const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/"; |
| 64 | const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform"; |
| 65 | const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe"; |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 66 | const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 67 | |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 68 | /// The structure of DT table header in dtbo.img. |
| 69 | /// https://source.android.com/docs/core/architecture/dto/partitions |
| 70 | #[repr(C)] |
| 71 | #[derive(Debug, FromBytes)] |
| 72 | struct DtTableHeader { |
| 73 | /// DT_TABLE_MAGIC |
| 74 | magic: U32<BigEndian>, |
| 75 | /// includes dt_table_header + all dt_table_entry and all dtb/dtbo |
| 76 | _total_size: U32<BigEndian>, |
| 77 | /// sizeof(dt_table_header) |
| 78 | header_size: U32<BigEndian>, |
| 79 | /// sizeof(dt_table_entry) |
| 80 | dt_entry_size: U32<BigEndian>, |
| 81 | /// number of dt_table_entry |
| 82 | dt_entry_count: U32<BigEndian>, |
| 83 | /// offset to the first dt_table_entry from head of dt_table_header |
| 84 | dt_entries_offset: U32<BigEndian>, |
| 85 | /// flash page size we assume |
| 86 | _page_size: U32<BigEndian>, |
| 87 | /// DTBO image version, the current version is 0. The version will be |
| 88 | /// incremented when the dt_table_header struct is updated. |
| 89 | _version: U32<BigEndian>, |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 90 | } |
| 91 | |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 92 | /// The structure of each DT table entry (v0) in dtbo.img. |
| 93 | /// https://source.android.com/docs/core/architecture/dto/partitions |
| 94 | #[repr(C)] |
| 95 | #[derive(Debug, FromBytes)] |
| 96 | struct DtTableEntry { |
| 97 | /// size of each DT |
| 98 | dt_size: U32<BigEndian>, |
| 99 | /// offset from head of dt_table_header |
| 100 | dt_offset: U32<BigEndian>, |
| 101 | /// optional, must be zero if unused |
| 102 | _id: U32<BigEndian>, |
| 103 | /// optional, must be zero if unused |
| 104 | _rev: U32<BigEndian>, |
| 105 | /// optional, must be zero if unused |
| 106 | _custom: [U32<BigEndian>; 4], |
| 107 | } |
| 108 | |
| 109 | lazy_static! { |
| 110 | static ref IS_VFIO_SUPPORTED: bool = |
| 111 | Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists(); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 112 | } |
| 113 | |
| 114 | fn check_platform_device(path: &Path) -> binder::Result<()> { |
| 115 | if !path.exists() { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 116 | return Err(anyhow!("no such device {path:?}")) |
| 117 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 118 | } |
| 119 | |
| 120 | if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 121 | return Err(anyhow!("{path:?} is not a platform device")) |
| 122 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 123 | } |
| 124 | |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | fn get_device_iommu_group(path: &Path) -> Option<u64> { |
| 129 | let group_path = read_link(path.join("iommu_group")).ok()?; |
| 130 | let group = group_path.file_name()?; |
| 131 | group.to_str()?.parse().ok() |
| 132 | } |
| 133 | |
| 134 | fn is_bound_to_vfio_driver(path: &Path) -> bool { |
| 135 | let Ok(driver_path) = read_link(path.join("driver")) else { |
| 136 | return false; |
| 137 | }; |
| 138 | let Some(driver) = driver_path.file_name() else { |
| 139 | return false; |
| 140 | }; |
| 141 | driver.to_str().unwrap_or("") == "vfio-platform" |
| 142 | } |
| 143 | |
| 144 | fn bind_vfio_driver(path: &Path) -> binder::Result<()> { |
| 145 | if is_bound_to_vfio_driver(path) { |
| 146 | // already bound |
| 147 | return Ok(()); |
| 148 | } |
| 149 | |
| 150 | // unbind |
| 151 | let Some(device) = path.file_name() else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 152 | return Err(anyhow!("can't get device name from {path:?}")) |
| 153 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 154 | }; |
| 155 | let Some(device_str) = device.to_str() else { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 156 | return Err(anyhow!("invalid filename {device:?}")) |
| 157 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 158 | }; |
Inseob Kim | 55438b2 | 2023-08-09 20:16:01 +0900 | [diff] [blame] | 159 | let unbind_path = path.join("driver/unbind"); |
| 160 | if unbind_path.exists() { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 161 | write(&unbind_path, device_str.as_bytes()) |
| 162 | .with_context(|| format!("could not unbind {device_str}")) |
| 163 | .or_service_specific_exception(-1)?; |
Inseob Kim | 55438b2 | 2023-08-09 20:16:01 +0900 | [diff] [blame] | 164 | } |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 165 | |
| 166 | // bind to VFIO |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 167 | write(path.join("driver_override"), b"vfio-platform") |
| 168 | .with_context(|| format!("could not bind {device_str} to vfio-platform")) |
| 169 | .or_service_specific_exception(-1)?; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 170 | |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 171 | write(SYSFS_PLATFORM_DRIVERS_PROBE_PATH, device_str.as_bytes()) |
| 172 | .with_context(|| format!("could not write {device_str} to drivers-probe")) |
| 173 | .or_service_specific_exception(-1)?; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 174 | |
| 175 | // final check |
| 176 | if !is_bound_to_vfio_driver(path) { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 177 | return Err(anyhow!("{path:?} still not bound to vfio driver")) |
| 178 | .or_service_specific_exception(-1); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 179 | } |
| 180 | |
| 181 | if get_device_iommu_group(path).is_none() { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 182 | return Err(anyhow!("can't get iommu group for {path:?}")) |
| 183 | .or_service_specific_exception(-1); |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 184 | } |
| 185 | |
| 186 | Ok(()) |
| 187 | } |
| 188 | |
| 189 | fn bind_device(path: &Path) -> binder::Result<()> { |
Jiyong Park | 2227eaa | 2023-08-04 11:59:18 +0900 | [diff] [blame] | 190 | let path = path |
| 191 | .canonicalize() |
| 192 | .with_context(|| format!("can't canonicalize {path:?}")) |
| 193 | .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?; |
Inseob Kim | bdca047 | 2023-07-28 19:20:56 +0900 | [diff] [blame] | 194 | |
| 195 | check_platform_device(&path)?; |
| 196 | bind_vfio_driver(&path) |
| 197 | } |
Seungjae Yoo | db2d9cb | 2023-08-14 09:11:29 +0900 | [diff] [blame] | 198 | |
| 199 | fn get_dtbo_img_path() -> binder::Result<PathBuf> { |
| 200 | let slot_suffix = system_properties::read("ro.boot.slot_suffix") |
| 201 | .context("Failed to read ro.boot.slot_suffix") |
| 202 | .or_service_specific_exception(-1)? |
| 203 | .ok_or_else(|| anyhow!("slot_suffix is none")) |
| 204 | .or_service_specific_exception(-1)?; |
| 205 | Ok(PathBuf::from(format!("/dev/block/by-name/dtbo{slot_suffix}"))) |
| 206 | } |
| 207 | |
| 208 | fn read_values(file: &mut File, size: usize, offset: u64) -> binder::Result<Vec<u8>> { |
| 209 | file.seek(SeekFrom::Start(offset)) |
| 210 | .context("Cannot seek the offset") |
| 211 | .or_service_specific_exception(-1)?; |
| 212 | let mut buffer = vec![0_u8; size]; |
| 213 | file.read_exact(&mut buffer) |
| 214 | .context("Failed to read buffer") |
| 215 | .or_service_specific_exception(-1)?; |
| 216 | Ok(buffer) |
| 217 | } |
| 218 | |
| 219 | fn get_dt_table_header(file: &mut File) -> binder::Result<DtTableHeader> { |
| 220 | let values = read_values(file, size_of::<DtTableHeader>(), 0)?; |
| 221 | let dt_table_header = DtTableHeader::read_from(values.as_slice()) |
| 222 | .context("DtTableHeader is invalid") |
| 223 | .or_service_specific_exception(-1)?; |
| 224 | if dt_table_header.magic.get() != DT_TABLE_MAGIC |
| 225 | || dt_table_header.header_size.get() as usize != size_of::<DtTableHeader>() |
| 226 | { |
| 227 | return Err(anyhow!("DtTableHeader is invalid")).or_service_specific_exception(-1)?; |
| 228 | } |
| 229 | Ok(dt_table_header) |
| 230 | } |
| 231 | |
| 232 | fn get_dt_table_entry( |
| 233 | file: &mut File, |
| 234 | header: &DtTableHeader, |
| 235 | index: u32, |
| 236 | ) -> binder::Result<DtTableEntry> { |
| 237 | if index >= header.dt_entry_count.get() { |
| 238 | return Err(anyhow!("Invalid dtbo index {index}")).or_service_specific_exception(-1)?; |
| 239 | } |
| 240 | let Some(prev_dt_entry_total_size) = header.dt_entry_size.get().checked_mul(index) else { |
| 241 | return Err(anyhow!("Unexpected arithmetic result")) |
| 242 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE); |
| 243 | }; |
| 244 | let Some(dt_entry_offset) = |
| 245 | prev_dt_entry_total_size.checked_add(header.dt_entries_offset.get()) |
| 246 | else { |
| 247 | return Err(anyhow!("Unexpected arithmetic result")) |
| 248 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE); |
| 249 | }; |
| 250 | let values = read_values(file, size_of::<DtTableEntry>(), dt_entry_offset.into())?; |
| 251 | let dt_table_entry = DtTableEntry::read_from(values.as_slice()) |
| 252 | .with_context(|| format!("DtTableEntry at index {index} is invalid.")) |
| 253 | .or_service_specific_exception(-1)?; |
| 254 | Ok(dt_table_entry) |
| 255 | } |
| 256 | |
| 257 | fn filter_dtbo_from_img( |
| 258 | dtbo_img_file: &mut File, |
| 259 | entry: &DtTableEntry, |
| 260 | dtbo_fd: &ParcelFileDescriptor, |
| 261 | ) -> binder::Result<()> { |
| 262 | let dt_size = entry |
| 263 | .dt_size |
| 264 | .get() |
| 265 | .try_into() |
| 266 | .context("Failed to convert type") |
| 267 | .or_binder_exception(ExceptionCode::ILLEGAL_STATE)?; |
| 268 | let buffer = read_values(dtbo_img_file, dt_size, entry.dt_offset.get().into())?; |
| 269 | |
| 270 | let mut dtbo_fd = dtbo_fd |
| 271 | .as_ref() |
| 272 | .try_clone() |
| 273 | .context("Failed to clone File from ParcelFileDescriptor") |
| 274 | .or_binder_exception(ExceptionCode::BAD_PARCELABLE)?; |
| 275 | |
| 276 | // TODO(b/291191362): Filter dtbo.img, not writing all information. |
| 277 | dtbo_fd |
| 278 | .write_all(&buffer) |
| 279 | .context("Failed to write dtbo file") |
| 280 | .or_service_specific_exception(-1)?; |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | fn write_dtbo(dtbo_fd: &ParcelFileDescriptor) -> binder::Result<()> { |
| 285 | let dtbo_path = get_dtbo_img_path()?; |
| 286 | let mut dtbo_img = File::open(dtbo_path) |
| 287 | .context("Failed to open DTBO partition") |
| 288 | .or_service_specific_exception(-1)?; |
| 289 | |
| 290 | let dt_table_header = get_dt_table_header(&mut dtbo_img)?; |
| 291 | // TODO(b/291190552): Use vm_dtbo_idx from bootconfig. |
| 292 | let vm_dtbo_idx = 3; |
| 293 | let dt_table_entry = get_dt_table_entry(&mut dtbo_img, &dt_table_header, vm_dtbo_idx)?; |
| 294 | filter_dtbo_from_img(&mut dtbo_img, &dt_table_entry, dtbo_fd)?; |
| 295 | Ok(()) |
| 296 | } |