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