blob: ad15ed559e6fe13651ff21a183c4bdc3d4f47693 [file] [log] [blame]
Inseob Kimbdca0472023-07-28 19:20:56 +09001// 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 Park2227eaa2023-08-04 11:59:18 +090017use anyhow::{anyhow, Context};
Inseob Kimbdca0472023-07-28 19:20:56 +090018use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVfioHandler::IVfioHandler;
19use android_system_virtualizationservice_internal::binder::ParcelFileDescriptor;
Jiyong Park2227eaa2023-08-04 11:59:18 +090020use binder::{self, ExceptionCode, Interface, IntoBinderResult};
Inseob Kimbdca0472023-07-28 19:20:56 +090021use lazy_static::lazy_static;
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090022use std::fs::{read_link, write, File};
23use std::io::{Read, Seek, SeekFrom, Write};
24use std::mem::size_of;
25use std::path::{Path, PathBuf};
26use rustutils::system_properties;
27use zerocopy::{
28 byteorder::{BigEndian, U32},
29 FromBytes,
30};
Inseob Kimbdca0472023-07-28 19:20:56 +090031
32#[derive(Debug, Default)]
33pub struct VfioHandler {}
34
35impl VfioHandler {
36 pub fn init() -> VfioHandler {
37 VfioHandler::default()
38 }
39}
40
41impl Interface for VfioHandler {}
42
43impl IVfioHandler for VfioHandler {
Inseob Kimf36347b2023-08-03 12:52:48 +090044 fn bindDevicesToVfioDriver(
45 &self,
46 devices: &[String],
47 dtbo: &ParcelFileDescriptor,
48 ) -> binder::Result<()> {
Inseob Kimbdca0472023-07-28 19:20:56 +090049 // permission check is already done by IVirtualizationServiceInternal.
50 if !*IS_VFIO_SUPPORTED {
Jiyong Park2227eaa2023-08-04 11:59:18 +090051 return Err(anyhow!("VFIO-platform not supported"))
52 .or_binder_exception(ExceptionCode::UNSUPPORTED_OPERATION);
Inseob Kimbdca0472023-07-28 19:20:56 +090053 }
Inseob Kimbdca0472023-07-28 19:20:56 +090054 devices.iter().try_for_each(|x| bind_device(Path::new(x)))?;
55
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090056 write_dtbo(dtbo)?;
57
Inseob Kimf36347b2023-08-03 12:52:48 +090058 Ok(())
Inseob Kimbdca0472023-07-28 19:20:56 +090059 }
60}
61
62const DEV_VFIO_PATH: &str = "/dev/vfio/vfio";
63const SYSFS_PLATFORM_DEVICES_PATH: &str = "/sys/devices/platform/";
64const VFIO_PLATFORM_DRIVER_PATH: &str = "/sys/bus/platform/drivers/vfio-platform";
65const SYSFS_PLATFORM_DRIVERS_PROBE_PATH: &str = "/sys/bus/platform/drivers_probe";
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090066const DT_TABLE_MAGIC: u32 = 0xd7b7ab1e;
Inseob Kimbdca0472023-07-28 19:20:56 +090067
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090068/// 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)]
72struct 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 Kimbdca0472023-07-28 19:20:56 +090090}
91
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +090092/// 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)]
96struct 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
109lazy_static! {
110 static ref IS_VFIO_SUPPORTED: bool =
111 Path::new(DEV_VFIO_PATH).exists() && Path::new(VFIO_PLATFORM_DRIVER_PATH).exists();
Inseob Kimbdca0472023-07-28 19:20:56 +0900112}
113
114fn check_platform_device(path: &Path) -> binder::Result<()> {
115 if !path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900116 return Err(anyhow!("no such device {path:?}"))
117 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900118 }
119
120 if !path.starts_with(SYSFS_PLATFORM_DEVICES_PATH) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900121 return Err(anyhow!("{path:?} is not a platform device"))
122 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900123 }
124
125 Ok(())
126}
127
128fn 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
134fn 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
144fn 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 Park2227eaa2023-08-04 11:59:18 +0900152 return Err(anyhow!("can't get device name from {path:?}"))
153 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900154 };
155 let Some(device_str) = device.to_str() else {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900156 return Err(anyhow!("invalid filename {device:?}"))
157 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT);
Inseob Kimbdca0472023-07-28 19:20:56 +0900158 };
Inseob Kim55438b22023-08-09 20:16:01 +0900159 let unbind_path = path.join("driver/unbind");
160 if unbind_path.exists() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900161 write(&unbind_path, device_str.as_bytes())
162 .with_context(|| format!("could not unbind {device_str}"))
163 .or_service_specific_exception(-1)?;
Inseob Kim55438b22023-08-09 20:16:01 +0900164 }
Inseob Kimbdca0472023-07-28 19:20:56 +0900165
166 // bind to VFIO
Jiyong Park2227eaa2023-08-04 11:59:18 +0900167 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 Kimbdca0472023-07-28 19:20:56 +0900170
Jiyong Park2227eaa2023-08-04 11:59:18 +0900171 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 Kimbdca0472023-07-28 19:20:56 +0900174
175 // final check
176 if !is_bound_to_vfio_driver(path) {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900177 return Err(anyhow!("{path:?} still not bound to vfio driver"))
178 .or_service_specific_exception(-1);
Inseob Kimbdca0472023-07-28 19:20:56 +0900179 }
180
181 if get_device_iommu_group(path).is_none() {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900182 return Err(anyhow!("can't get iommu group for {path:?}"))
183 .or_service_specific_exception(-1);
Inseob Kimbdca0472023-07-28 19:20:56 +0900184 }
185
186 Ok(())
187}
188
189fn bind_device(path: &Path) -> binder::Result<()> {
Jiyong Park2227eaa2023-08-04 11:59:18 +0900190 let path = path
191 .canonicalize()
192 .with_context(|| format!("can't canonicalize {path:?}"))
193 .or_binder_exception(ExceptionCode::ILLEGAL_ARGUMENT)?;
Inseob Kimbdca0472023-07-28 19:20:56 +0900194
195 check_platform_device(&path)?;
196 bind_vfio_driver(&path)
197}
Seungjae Yoodb2d9cb2023-08-14 09:11:29 +0900198
199fn 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
208fn 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
219fn 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
232fn 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
257fn 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
284fn 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}