blob: b8912cec2caefd2779ab005a0ba8c1121ee93fd4 [file] [log] [blame]
Jaewan Kimc6e023b2023-10-12 15:11:05 +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//! Validate device assignment written in crosvm DT with VM DTBO, and apply it
16//! to platform DT.
17//! Declared in separated libs for adding unit tests, which requires libstd.
18
19#[cfg(test)]
20extern crate alloc;
21
Jaewan Kim51ccfed2023-11-08 13:51:58 +090022use alloc::collections::{BTreeMap, BTreeSet};
Jaewan Kimc6e023b2023-10-12 15:11:05 +090023use alloc::ffi::CString;
24use alloc::fmt;
25use alloc::vec;
26use alloc::vec::Vec;
27use core::ffi::CStr;
28use core::iter::Iterator;
29use core::mem;
Jaewan Kim52477ae2023-11-21 21:20:52 +090030use hyp::DeviceAssigningHypervisor;
31use libfdt::{Fdt, FdtError, FdtNode, Phandle, Reg};
32use log::error;
Jaewan Kimc6e023b2023-10-12 15:11:05 +090033
Jaewan Kimc6e023b2023-10-12 15:11:05 +090034// TODO(b/308694211): Use cstr! from vmbase instead.
35macro_rules! cstr {
36 ($str:literal) => {{
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +000037 const S: &str = concat!($str, "\0");
38 const C: &::core::ffi::CStr = match ::core::ffi::CStr::from_bytes_with_nul(S.as_bytes()) {
39 Ok(v) => v,
40 Err(_) => panic!("string contains interior NUL"),
41 };
42 C
Jaewan Kimc6e023b2023-10-12 15:11:05 +090043 }};
44}
45
Jaewan Kimc6e023b2023-10-12 15:11:05 +090046// TODO(b/277993056): Keep constants derived from platform.dts in one place.
47const CELLS_PER_INTERRUPT: usize = 3; // from /intc node in platform.dts
48
49/// Errors in device assignment.
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum DeviceAssignmentError {
Jaewan Kim52477ae2023-11-21 21:20:52 +090052 /// Invalid VM DTBO
Jaewan Kimc6e023b2023-10-12 15:11:05 +090053 InvalidDtbo,
54 /// Invalid __symbols__
55 InvalidSymbols,
Jaewan Kim19b984f2023-12-04 15:16:50 +090056 /// Malformed <reg>. Can't parse.
57 MalformedReg,
58 /// Invalid <reg>. Failed to validate with HVC.
Jaewan Kim52477ae2023-11-21 21:20:52 +090059 InvalidReg,
Jaewan Kimc6e023b2023-10-12 15:11:05 +090060 /// Invalid <interrupts>
61 InvalidInterrupts,
Jaewan Kim19b984f2023-12-04 15:16:50 +090062 /// Malformed <iommus>
63 MalformedIommus,
Jaewan Kim51ccfed2023-11-08 13:51:58 +090064 /// Invalid <iommus>
65 InvalidIommus,
Jaewan Kim19b984f2023-12-04 15:16:50 +090066 /// Invalid phys IOMMU node
67 InvalidPhysIommu,
Jaewan Kima9200492023-11-21 20:45:31 +090068 /// Invalid pvIOMMU node
69 InvalidPvIommu,
Jaewan Kim51ccfed2023-11-08 13:51:58 +090070 /// Too many pvIOMMU
71 TooManyPvIommu,
Jaewan Kim19b984f2023-12-04 15:16:50 +090072 /// Duplicated phys IOMMU IDs exist
73 DuplicatedIommuIds,
Jaewan Kim51ccfed2023-11-08 13:51:58 +090074 /// Duplicated pvIOMMU IDs exist
75 DuplicatedPvIommuIds,
Jaewan Kimc6e023b2023-10-12 15:11:05 +090076 /// Unsupported overlay target syntax. Only supports <target-path> with full path.
77 UnsupportedOverlayTarget,
Jaewan Kim19b984f2023-12-04 15:16:50 +090078 /// Unsupported PhysIommu,
79 UnsupportedPhysIommu,
80 /// Unsupported (pvIOMMU id, vSID) duplication. Currently the pair should be unique.
81 UnsupportedPvIommusDuplication,
82 /// Unsupported (IOMMU token, SID) duplication. Currently the pair should be unique.
83 UnsupportedIommusDuplication,
Jaewan Kim51ccfed2023-11-08 13:51:58 +090084 /// Internal error
85 Internal,
Jaewan Kimc6e023b2023-10-12 15:11:05 +090086 /// Unexpected error from libfdt
87 UnexpectedFdtError(FdtError),
88}
89
90impl From<FdtError> for DeviceAssignmentError {
91 fn from(e: FdtError) -> Self {
92 DeviceAssignmentError::UnexpectedFdtError(e)
93 }
94}
95
96impl fmt::Display for DeviceAssignmentError {
97 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98 match self {
99 Self::InvalidDtbo => write!(f, "Invalid DTBO"),
100 Self::InvalidSymbols => write!(
101 f,
102 "Invalid property in /__symbols__. Must point to valid assignable device node."
103 ),
Jaewan Kim19b984f2023-12-04 15:16:50 +0900104 Self::MalformedReg => write!(f, "Malformed <reg>. Can't parse"),
105 Self::InvalidReg => write!(f, "Invalid <reg>. Failed to validate with hypervisor"),
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900106 Self::InvalidInterrupts => write!(f, "Invalid <interrupts>"),
Jaewan Kim19b984f2023-12-04 15:16:50 +0900107 Self::MalformedIommus => write!(f, "Malformed <iommus>. Can't parse."),
108 Self::InvalidIommus => {
109 write!(f, "Invalid <iommus>. Failed to validate with hypervisor")
110 }
111 Self::InvalidPhysIommu => write!(f, "Invalid phys IOMMU node"),
Jaewan Kima9200492023-11-21 20:45:31 +0900112 Self::InvalidPvIommu => write!(f, "Invalid pvIOMMU node"),
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900113 Self::TooManyPvIommu => write!(
114 f,
115 "Too many pvIOMMU node. Insufficient pre-populated pvIOMMUs in platform DT"
116 ),
Jaewan Kim19b984f2023-12-04 15:16:50 +0900117 Self::DuplicatedIommuIds => {
118 write!(f, "Duplicated IOMMU IDs exist. IDs must unique among iommu node")
119 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900120 Self::DuplicatedPvIommuIds => {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900121 write!(f, "Duplicated pvIOMMU IDs exist. IDs must unique among iommu node")
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900122 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900123 Self::UnsupportedOverlayTarget => {
124 write!(f, "Unsupported overlay target. Only supports 'target-path = \"/\"'")
125 }
Jaewan Kim19b984f2023-12-04 15:16:50 +0900126 Self::UnsupportedPhysIommu => {
127 write!(f, "Unsupported Phys IOMMU. Currently only supports #iommu-cells = <1>")
128 }
129 Self::UnsupportedPvIommusDuplication => {
130 write!(f, "Unsupported (pvIOMMU id, vSID) duplication. Currently the pair should be unique.")
131 }
132 Self::UnsupportedIommusDuplication => {
133 write!(f, "Unsupported (IOMMU token, SID) duplication. Currently the pair should be unique.")
134 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900135 Self::Internal => write!(f, "Internal error"),
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900136 Self::UnexpectedFdtError(e) => write!(f, "Unexpected Error from libfdt: {e}"),
137 }
138 }
139}
140
141pub type Result<T> = core::result::Result<T, DeviceAssignmentError>;
142
143/// Represents VM DTBO
144#[repr(transparent)]
145pub struct VmDtbo(Fdt);
146
147impl VmDtbo {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900148 /// Wraps a mutable slice containing a VM DTBO.
149 ///
150 /// Fails if the VM DTBO does not pass validation.
151 pub fn from_mut_slice(dtbo: &mut [u8]) -> Result<&mut Self> {
152 // This validates DTBO
153 let fdt = Fdt::from_mut_slice(dtbo)?;
154 // SAFETY: VmDtbo is a transparent wrapper around Fdt, so representation is the same.
155 Ok(unsafe { mem::transmute::<&mut Fdt, &mut Self>(fdt) })
156 }
157
158 // Locates device node path as if the given dtbo node path is assigned and VM DTBO is overlaid.
159 // For given dtbo node path, this concatenates <target-path> of the enclosing fragment and
160 // relative path from __overlay__ node.
161 //
162 // Here's an example with sample VM DTBO:
163 // / {
164 // fragment@rng {
165 // target-path = "/"; // Always 'target-path = "/"'. Disallows <target> or other path.
166 // __overlay__ {
167 // rng { ... }; // Actual device node is here. If overlaid, path would be "/rng"
168 // };
169 // };
170 // __symbols__ { // List of assignable devices
171 // // Each property describes an assigned device device information.
172 // // property name is the device label, and property value is the path in the VM DTBO.
173 // rng = "/fragment@rng/__overlay__/rng";
174 // };
175 // };
176 //
177 // Then locate_overlay_target_path(cstr!("/fragment@rng/__overlay__/rng")) is Ok("/rng")
178 //
179 // Contrary to fdt_overlay_target_offset(), this API enforces overlay target property
180 // 'target-path = "/"', so the overlay doesn't modify and/or append platform DT's existing
181 // node and/or properties. The enforcement is for compatibility reason.
Jaewan Kim19b984f2023-12-04 15:16:50 +0900182 fn locate_overlay_target_path(
183 &self,
184 dtbo_node_path: &CStr,
185 dtbo_node: &FdtNode,
186 ) -> Result<CString> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900187 let dtbo_node_path_bytes = dtbo_node_path.to_bytes();
188 if dtbo_node_path_bytes.first() != Some(&b'/') {
189 return Err(DeviceAssignmentError::UnsupportedOverlayTarget);
190 }
191
Jaewan Kim19b984f2023-12-04 15:16:50 +0900192 let fragment_node = dtbo_node.supernode_at_depth(1)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900193 let target_path = fragment_node
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +0000194 .getprop_str(cstr!("target-path"))?
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900195 .ok_or(DeviceAssignmentError::InvalidDtbo)?;
196 if target_path != cstr!("/") {
197 return Err(DeviceAssignmentError::UnsupportedOverlayTarget);
198 }
199
200 let mut components = dtbo_node_path_bytes
201 .split(|char| *char == b'/')
202 .filter(|&component| !component.is_empty())
203 .skip(1);
204 let overlay_node_name = components.next();
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +0000205 if overlay_node_name != Some(b"__overlay__") {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900206 return Err(DeviceAssignmentError::InvalidDtbo);
207 }
208 let mut overlaid_path = Vec::with_capacity(dtbo_node_path_bytes.len());
209 for component in components {
210 overlaid_path.push(b'/');
211 overlaid_path.extend_from_slice(component);
212 }
213 overlaid_path.push(b'\0');
214
215 Ok(CString::from_vec_with_nul(overlaid_path).unwrap())
216 }
Jaewan Kim19b984f2023-12-04 15:16:50 +0900217
218 fn parse_physical_iommus(physical_node: &FdtNode) -> Result<BTreeMap<Phandle, PhysIommu>> {
219 let mut phys_iommus = BTreeMap::new();
220 for (node, _) in physical_node.descendants() {
221 let Some(phandle) = node.get_phandle()? else {
222 continue; // Skips unreachable IOMMU node
223 };
224 let Some(iommu) = PhysIommu::parse(&node)? else {
225 continue; // Skip if not a PhysIommu.
226 };
227 if phys_iommus.insert(phandle, iommu).is_some() {
228 return Err(FdtError::BadPhandle.into());
229 }
230 }
231 Self::validate_physical_iommus(&phys_iommus)?;
232 Ok(phys_iommus)
233 }
234
235 fn validate_physical_iommus(phys_iommus: &BTreeMap<Phandle, PhysIommu>) -> Result<()> {
236 let unique_iommus: BTreeSet<_> = phys_iommus.values().cloned().collect();
237 if phys_iommus.len() != unique_iommus.len() {
238 return Err(DeviceAssignmentError::DuplicatedIommuIds);
239 }
240 Ok(())
241 }
242
243 fn validate_physical_devices(
244 physical_devices: &BTreeMap<Phandle, PhysicalDeviceInfo>,
245 ) -> Result<()> {
246 // Only need to validate iommus because <reg> will be validated together with PV <reg>
247 // see: DeviceAssignmentInfo::validate_all_regs().
248 let mut all_iommus = BTreeSet::new();
249 for physical_device in physical_devices.values() {
250 for iommu in &physical_device.iommus {
251 if !all_iommus.insert(iommu) {
252 error!("Unsupported phys IOMMU duplication found, <iommus> = {iommu:?}");
253 return Err(DeviceAssignmentError::UnsupportedIommusDuplication);
254 }
255 }
256 }
257 Ok(())
258 }
259
260 fn parse_physical_devices_with_iommus(
261 physical_node: &FdtNode,
262 phys_iommus: &BTreeMap<Phandle, PhysIommu>,
263 ) -> Result<BTreeMap<Phandle, PhysicalDeviceInfo>> {
264 let mut physical_devices = BTreeMap::new();
265 for (node, _) in physical_node.descendants() {
266 let Some(info) = PhysicalDeviceInfo::parse(&node, phys_iommus)? else {
267 continue;
268 };
269 if physical_devices.insert(info.target, info).is_some() {
270 return Err(DeviceAssignmentError::InvalidDtbo);
271 }
272 }
273 Self::validate_physical_devices(&physical_devices)?;
274 Ok(physical_devices)
275 }
276
277 /// Parses Physical devices in VM DTBO
278 fn parse_physical_devices(&self) -> Result<BTreeMap<Phandle, PhysicalDeviceInfo>> {
279 let Some(physical_node) = self.as_ref().node(cstr!("/host"))? else {
280 return Ok(BTreeMap::new());
281 };
282
283 let phys_iommus = Self::parse_physical_iommus(&physical_node)?;
284 Self::parse_physical_devices_with_iommus(&physical_node, &phys_iommus)
285 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900286}
287
Jaewan Kimc39974e2023-12-02 01:13:30 +0900288fn is_overlayable_node(dtbo_path: &CStr) -> bool {
289 dtbo_path
290 .to_bytes()
291 .split(|char| *char == b'/')
292 .filter(|&component| !component.is_empty())
293 .nth(1)
294 .map_or(false, |name| name == b"__overlay__")
295}
296
Jaewan Kimc730ebf2024-02-22 10:34:55 +0900297fn filter_dangling_symbols(fdt: &mut Fdt) -> Result<()> {
298 if let Some(symbols) = fdt.symbols()? {
299 let mut removed = vec![];
300 for prop in symbols.properties()? {
301 let path = CStr::from_bytes_with_nul(prop.value()?)
302 .map_err(|_| DeviceAssignmentError::Internal)?;
303 if fdt.node(path)?.is_none() {
304 let name = prop.name()?;
305 removed.push(CString::from(name));
306 }
307 }
308
309 let mut symbols = fdt.symbols_mut()?.unwrap();
310 for name in removed {
311 symbols.nop_property(&name)?;
312 }
313 }
314 Ok(())
315}
316
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900317impl AsRef<Fdt> for VmDtbo {
318 fn as_ref(&self) -> &Fdt {
319 &self.0
320 }
321}
322
323impl AsMut<Fdt> for VmDtbo {
324 fn as_mut(&mut self) -> &mut Fdt {
325 &mut self.0
326 }
327}
328
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900329#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
330struct PvIommu {
331 // ID from pvIOMMU node
332 id: u32,
333}
334
335impl PvIommu {
336 fn parse(node: &FdtNode) -> Result<Self> {
Jaewan Kima9200492023-11-21 20:45:31 +0900337 let iommu_cells = node
338 .getprop_u32(cstr!("#iommu-cells"))?
339 .ok_or(DeviceAssignmentError::InvalidPvIommu)?;
Jaewan Kim19b984f2023-12-04 15:16:50 +0900340 // Ensures #iommu-cells = <1>. It means that `<iommus>` entry contains pair of
Jaewan Kima9200492023-11-21 20:45:31 +0900341 // (pvIOMMU ID, vSID)
342 if iommu_cells != 1 {
343 return Err(DeviceAssignmentError::InvalidPvIommu);
344 }
345 let id = node.getprop_u32(cstr!("id"))?.ok_or(DeviceAssignmentError::InvalidPvIommu)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900346 Ok(Self { id })
347 }
348}
349
Jaewan Kima9200492023-11-21 20:45:31 +0900350#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
351struct Vsid(u32);
352
Jaewan Kim19b984f2023-12-04 15:16:50 +0900353#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
354struct Sid(u64);
355
356impl From<u32> for Sid {
357 fn from(sid: u32) -> Self {
358 Self(sid.into())
359 }
360}
361
362#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Jaewan Kim52477ae2023-11-21 21:20:52 +0900363struct DeviceReg {
364 addr: u64,
365 size: u64,
366}
367
368impl TryFrom<Reg<u64>> for DeviceReg {
369 type Error = DeviceAssignmentError;
370
371 fn try_from(reg: Reg<u64>) -> Result<Self> {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900372 Ok(Self { addr: reg.addr, size: reg.size.ok_or(DeviceAssignmentError::MalformedReg)? })
Jaewan Kim52477ae2023-11-21 21:20:52 +0900373 }
374}
375
376fn parse_node_reg(node: &FdtNode) -> Result<Vec<DeviceReg>> {
377 node.reg()?
Jaewan Kim19b984f2023-12-04 15:16:50 +0900378 .ok_or(DeviceAssignmentError::MalformedReg)?
Jaewan Kim52477ae2023-11-21 21:20:52 +0900379 .map(DeviceReg::try_from)
380 .collect::<Result<Vec<_>>>()
381}
382
383fn to_be_bytes(reg: &[DeviceReg]) -> Vec<u8> {
384 let mut reg_cells = vec![];
385 for x in reg {
386 reg_cells.extend_from_slice(&x.addr.to_be_bytes());
387 reg_cells.extend_from_slice(&x.size.to_be_bytes());
388 }
389 reg_cells
390}
391
Jaewan Kim19b984f2023-12-04 15:16:50 +0900392#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
393struct PhysIommu {
394 token: u64,
395}
396
397impl PhysIommu {
398 fn parse(node: &FdtNode) -> Result<Option<Self>> {
399 let Some(token) = node.getprop_u64(cstr!("android,pvmfw,token"))? else {
400 return Ok(None);
401 };
402 let Some(iommu_cells) = node.getprop_u32(cstr!("#iommu-cells"))? else {
403 return Err(DeviceAssignmentError::InvalidPhysIommu);
404 };
405 // Currently only supports #iommu-cells = <1>.
406 // In that case `<iommus>` entry contains pair of (pIOMMU phandle, Sid token)
407 if iommu_cells != 1 {
408 return Err(DeviceAssignmentError::UnsupportedPhysIommu);
409 }
410 Ok(Some(Self { token }))
411 }
412}
413
414#[derive(Debug)]
415struct PhysicalDeviceInfo {
416 target: Phandle,
417 reg: Vec<DeviceReg>,
418 iommus: Vec<(PhysIommu, Sid)>,
419}
420
421impl PhysicalDeviceInfo {
422 fn parse_iommus(
423 node: &FdtNode,
424 phys_iommus: &BTreeMap<Phandle, PhysIommu>,
425 ) -> Result<Vec<(PhysIommu, Sid)>> {
426 let mut iommus = vec![];
427 let Some(mut cells) = node.getprop_cells(cstr!("iommus"))? else {
428 return Ok(iommus);
429 };
430 while let Some(cell) = cells.next() {
431 // Parse pIOMMU ID
432 let phandle =
433 Phandle::try_from(cell).or(Err(DeviceAssignmentError::MalformedIommus))?;
434 let iommu = phys_iommus.get(&phandle).ok_or(DeviceAssignmentError::MalformedIommus)?;
435
436 // Parse Sid
437 let Some(cell) = cells.next() else {
438 return Err(DeviceAssignmentError::MalformedIommus);
439 };
440
441 iommus.push((*iommu, Sid::from(cell)));
442 }
443 Ok(iommus)
444 }
445
446 fn parse(node: &FdtNode, phys_iommus: &BTreeMap<Phandle, PhysIommu>) -> Result<Option<Self>> {
447 let Some(phandle) = node.getprop_u32(cstr!("android,pvmfw,target"))? else {
448 return Ok(None);
449 };
450 let target = Phandle::try_from(phandle)?;
451 let reg = parse_node_reg(node)?;
452 let iommus = Self::parse_iommus(node, phys_iommus)?;
453 Ok(Some(Self { target, reg, iommus }))
454 }
455}
456
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900457/// Assigned device information parsed from crosvm DT.
458/// Keeps everything in the owned data because underlying FDT will be reused for platform DT.
459#[derive(Debug, Eq, PartialEq)]
460struct AssignedDeviceInfo {
461 // Node path of assigned device (e.g. "/rng")
462 node_path: CString,
463 // DTBO node path of the assigned device (e.g. "/fragment@rng/__overlay__/rng")
464 dtbo_node_path: CString,
465 // <reg> property from the crosvm DT
Jaewan Kim52477ae2023-11-21 21:20:52 +0900466 reg: Vec<DeviceReg>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900467 // <interrupts> property from the crosvm DT
468 interrupts: Vec<u8>,
Jaewan Kima9200492023-11-21 20:45:31 +0900469 // Parsed <iommus> property from the crosvm DT. Tuple of PvIommu and vSID.
470 iommus: Vec<(PvIommu, Vsid)>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900471}
472
473impl AssignedDeviceInfo {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900474 fn validate_reg(
475 device_reg: &[DeviceReg],
476 physical_device_reg: &[DeviceReg],
Jaewan Kim52477ae2023-11-21 21:20:52 +0900477 hypervisor: &dyn DeviceAssigningHypervisor,
Jaewan Kim19b984f2023-12-04 15:16:50 +0900478 ) -> Result<()> {
479 if device_reg.len() != physical_device_reg.len() {
480 return Err(DeviceAssignmentError::InvalidReg);
481 }
482 // PV reg and physical reg should have 1:1 match in order.
483 for (reg, phys_reg) in device_reg.iter().zip(physical_device_reg.iter()) {
484 let addr = hypervisor.get_phys_mmio_token(reg.addr, reg.size).map_err(|e| {
485 error!("Failed to validate device <reg>, error={e:?}, reg={reg:x?}");
Jaewan Kim52477ae2023-11-21 21:20:52 +0900486 DeviceAssignmentError::InvalidReg
487 })?;
Jaewan Kim19b984f2023-12-04 15:16:50 +0900488 // Only check address because hypervisor guaranatees size match when success.
489 if phys_reg.addr != addr {
490 error!("Failed to validate device <reg>. No matching phys reg for reg={reg:x?}");
491 return Err(DeviceAssignmentError::InvalidReg);
492 }
Jaewan Kim52477ae2023-11-21 21:20:52 +0900493 }
Jaewan Kim19b984f2023-12-04 15:16:50 +0900494 Ok(())
Jaewan Kim52477ae2023-11-21 21:20:52 +0900495 }
496
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900497 fn parse_interrupts(node: &FdtNode) -> Result<Vec<u8>> {
498 // Validation: Validate if interrupts cell numbers are multiple of #interrupt-cells.
499 // We can't know how many interrupts would exist.
500 let interrupts_cells = node
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +0000501 .getprop_cells(cstr!("interrupts"))?
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900502 .ok_or(DeviceAssignmentError::InvalidInterrupts)?
503 .count();
504 if interrupts_cells % CELLS_PER_INTERRUPT != 0 {
505 return Err(DeviceAssignmentError::InvalidInterrupts);
506 }
507
508 // Once validated, keep the raw bytes so patch can be done with setprop()
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +0000509 Ok(node.getprop(cstr!("interrupts")).unwrap().unwrap().into())
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900510 }
511
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900512 // TODO(b/277993056): Also validate /__local_fixups__ to ensure that <iommus> has phandle.
Jaewan Kima9200492023-11-21 20:45:31 +0900513 fn parse_iommus(
514 node: &FdtNode,
515 pviommus: &BTreeMap<Phandle, PvIommu>,
516 ) -> Result<Vec<(PvIommu, Vsid)>> {
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900517 let mut iommus = vec![];
Jaewan Kima9200492023-11-21 20:45:31 +0900518 let Some(mut cells) = node.getprop_cells(cstr!("iommus"))? else {
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900519 return Ok(iommus);
520 };
Jaewan Kima9200492023-11-21 20:45:31 +0900521 while let Some(cell) = cells.next() {
522 // Parse pvIOMMU ID
Jaewan Kim19b984f2023-12-04 15:16:50 +0900523 let phandle =
524 Phandle::try_from(cell).or(Err(DeviceAssignmentError::MalformedIommus))?;
525 let pviommu = pviommus.get(&phandle).ok_or(DeviceAssignmentError::MalformedIommus)?;
Jaewan Kima9200492023-11-21 20:45:31 +0900526
527 // Parse vSID
528 let Some(cell) = cells.next() else {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900529 return Err(DeviceAssignmentError::MalformedIommus);
Jaewan Kima9200492023-11-21 20:45:31 +0900530 };
531 let vsid = Vsid(cell);
532
533 iommus.push((*pviommu, vsid));
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900534 }
535 Ok(iommus)
536 }
537
Jaewan Kim19b984f2023-12-04 15:16:50 +0900538 fn validate_iommus(
539 iommus: &[(PvIommu, Vsid)],
540 physical_device_iommu: &[(PhysIommu, Sid)],
541 hypervisor: &dyn DeviceAssigningHypervisor,
542 ) -> Result<()> {
543 if iommus.len() != physical_device_iommu.len() {
544 return Err(DeviceAssignmentError::InvalidIommus);
545 }
546 // pvIOMMU can be reordered, and hypervisor may not guarantee 1:1 mapping.
547 // So we need to mark what's matched or not.
548 let mut physical_device_iommu = physical_device_iommu.to_vec();
549 for (pviommu, vsid) in iommus {
550 let (id, sid) = hypervisor.get_phys_iommu_token(pviommu.id.into(), vsid.0.into())
551 .map_err(|e| {
552 error!("Failed to validate device <iommus>, error={e:?}, pviommu={pviommu:?}, vsid={vsid:?}");
553 DeviceAssignmentError::InvalidIommus
554 })?;
555
556 let pos = physical_device_iommu
557 .iter()
558 .position(|(phys_iommu, phys_sid)| (phys_iommu.token, phys_sid.0) == (id, sid));
559 match pos {
560 Some(pos) => physical_device_iommu.remove(pos),
561 None => {
562 error!("Failed to validate device <iommus>. No matching phys iommu or duplicated mapping for pviommu={pviommu:?}, vsid={vsid:?}");
563 return Err(DeviceAssignmentError::InvalidIommus);
564 }
565 };
566 }
567 Ok(())
568 }
569
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900570 fn parse(
571 fdt: &Fdt,
572 vm_dtbo: &VmDtbo,
573 dtbo_node_path: &CStr,
Jaewan Kim19b984f2023-12-04 15:16:50 +0900574 physical_devices: &BTreeMap<Phandle, PhysicalDeviceInfo>,
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900575 pviommus: &BTreeMap<Phandle, PvIommu>,
Jaewan Kim52477ae2023-11-21 21:20:52 +0900576 hypervisor: &dyn DeviceAssigningHypervisor,
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900577 ) -> Result<Option<Self>> {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900578 let dtbo_node =
579 vm_dtbo.as_ref().node(dtbo_node_path)?.ok_or(DeviceAssignmentError::InvalidSymbols)?;
580 let node_path = vm_dtbo.locate_overlay_target_path(dtbo_node_path, &dtbo_node)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900581
582 let Some(node) = fdt.node(&node_path)? else { return Ok(None) };
583
Jaewan Kim19b984f2023-12-04 15:16:50 +0900584 // Note: Currently can only assign devices backed by physical devices.
585 let phandle = dtbo_node.get_phandle()?.ok_or(DeviceAssignmentError::InvalidDtbo)?;
586 let physical_device =
587 physical_devices.get(&phandle).ok_or(DeviceAssignmentError::InvalidDtbo)?;
588
589 let reg = parse_node_reg(&node)?;
590 Self::validate_reg(&reg, &physical_device.reg, hypervisor)?;
591
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900592 let interrupts = Self::parse_interrupts(&node)?;
Jaewan Kim19b984f2023-12-04 15:16:50 +0900593
594 let iommus = Self::parse_iommus(&node, pviommus)?;
595 Self::validate_iommus(&iommus, &physical_device.iommus, hypervisor)?;
596
Jaewan Kim52477ae2023-11-21 21:20:52 +0900597 Ok(Some(Self { node_path, dtbo_node_path: dtbo_node_path.into(), reg, interrupts, iommus }))
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900598 }
599
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900600 fn patch(&self, fdt: &mut Fdt, pviommu_phandles: &BTreeMap<PvIommu, Phandle>) -> Result<()> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900601 let mut dst = fdt.node_mut(&self.node_path)?.unwrap();
Jaewan Kim52477ae2023-11-21 21:20:52 +0900602 dst.setprop(cstr!("reg"), &to_be_bytes(&self.reg))?;
Pierre-Clément Tosid701a0b2023-11-07 15:38:59 +0000603 dst.setprop(cstr!("interrupts"), &self.interrupts)?;
Jaewan Kima9200492023-11-21 20:45:31 +0900604 let mut iommus = Vec::with_capacity(8 * self.iommus.len());
605 for (pviommu, vsid) in &self.iommus {
606 let phandle = pviommu_phandles.get(pviommu).unwrap();
607 iommus.extend_from_slice(&u32::from(*phandle).to_be_bytes());
608 iommus.extend_from_slice(&vsid.0.to_be_bytes());
609 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900610 dst.setprop(cstr!("iommus"), &iommus)?;
611
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900612 Ok(())
613 }
614}
615
616#[derive(Debug, Default, Eq, PartialEq)]
617pub struct DeviceAssignmentInfo {
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900618 pviommus: BTreeSet<PvIommu>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900619 assigned_devices: Vec<AssignedDeviceInfo>,
620 filtered_dtbo_paths: Vec<CString>,
621}
622
623impl DeviceAssignmentInfo {
Chris Wailes9d09f572024-01-16 13:31:02 -0800624 const PVIOMMU_COMPATIBLE: &'static CStr = cstr!("pkvm,pviommu");
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900625
626 /// Parses pvIOMMUs in fdt
627 // Note: This will validate pvIOMMU ids' uniqueness, even when unassigned.
628 fn parse_pviommus(fdt: &Fdt) -> Result<BTreeMap<Phandle, PvIommu>> {
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900629 let mut pviommus = BTreeMap::new();
630 for compatible in fdt.compatible_nodes(Self::PVIOMMU_COMPATIBLE)? {
631 let Some(phandle) = compatible.get_phandle()? else {
632 continue; // Skips unreachable pvIOMMU node
633 };
634 let pviommu = PvIommu::parse(&compatible)?;
635 if pviommus.insert(phandle, pviommu).is_some() {
636 return Err(FdtError::BadPhandle.into());
637 }
638 }
639 Ok(pviommus)
640 }
641
Jaewan Kim19b984f2023-12-04 15:16:50 +0900642 fn validate_pviommu_topology(assigned_devices: &[AssignedDeviceInfo]) -> Result<()> {
643 let mut all_iommus = BTreeSet::new();
644 for assigned_device in assigned_devices {
645 for iommu in &assigned_device.iommus {
646 if !all_iommus.insert(iommu) {
647 error!("Unsupported pvIOMMU duplication found, <iommus> = {iommu:?}");
648 return Err(DeviceAssignmentError::UnsupportedPvIommusDuplication);
649 }
650 }
651 }
652 Ok(())
653 }
654
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900655 /// Parses fdt and vm_dtbo, and creates new DeviceAssignmentInfo
656 // TODO(b/277993056): Parse __local_fixups__
657 // TODO(b/277993056): Parse __fixups__
Jaewan Kim52477ae2023-11-21 21:20:52 +0900658 pub fn parse(
659 fdt: &Fdt,
660 vm_dtbo: &VmDtbo,
661 hypervisor: &dyn DeviceAssigningHypervisor,
662 ) -> Result<Option<Self>> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900663 let Some(symbols_node) = vm_dtbo.as_ref().symbols()? else {
664 // /__symbols__ should contain all assignable devices.
665 // If empty, then nothing can be assigned.
666 return Ok(None);
667 };
668
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900669 let pviommus = Self::parse_pviommus(fdt)?;
670 let unique_pviommus: BTreeSet<_> = pviommus.values().cloned().collect();
671 if pviommus.len() != unique_pviommus.len() {
672 return Err(DeviceAssignmentError::DuplicatedPvIommuIds);
673 }
674
Jaewan Kim19b984f2023-12-04 15:16:50 +0900675 let physical_devices = vm_dtbo.parse_physical_devices()?;
676
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900677 let mut assigned_devices = vec![];
678 let mut filtered_dtbo_paths = vec![];
679 for symbol_prop in symbols_node.properties()? {
680 let symbol_prop_value = symbol_prop.value()?;
681 let dtbo_node_path = CStr::from_bytes_with_nul(symbol_prop_value)
682 .or(Err(DeviceAssignmentError::InvalidSymbols))?;
Jaewan Kimc39974e2023-12-02 01:13:30 +0900683 if !is_overlayable_node(dtbo_node_path) {
684 continue;
685 }
Jaewan Kim19b984f2023-12-04 15:16:50 +0900686 let assigned_device = AssignedDeviceInfo::parse(
687 fdt,
688 vm_dtbo,
689 dtbo_node_path,
690 &physical_devices,
691 &pviommus,
692 hypervisor,
693 )?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900694 if let Some(assigned_device) = assigned_device {
695 assigned_devices.push(assigned_device);
696 } else {
697 filtered_dtbo_paths.push(dtbo_node_path.into());
698 }
699 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900700 if assigned_devices.is_empty() {
701 return Ok(None);
702 }
Jaewan Kimc39974e2023-12-02 01:13:30 +0900703
Jaewan Kim19b984f2023-12-04 15:16:50 +0900704 Self::validate_pviommu_topology(&assigned_devices)?;
705
Jaewan Kimc39974e2023-12-02 01:13:30 +0900706 // Clean up any nodes that wouldn't be overlaid but may contain reference to filtered nodes.
707 // Otherwise, `fdt_apply_overlay()` would fail because of missing phandle reference.
Jaewan Kimc39974e2023-12-02 01:13:30 +0900708 // TODO(b/277993056): Also filter other unused nodes/props in __local_fixups__
709 filtered_dtbo_paths.push(CString::new("/__local_fixups__/host").unwrap());
710
711 // Note: Any node without __overlay__ will be ignored by fdt_apply_overlay,
712 // so doesn't need to be filtered.
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900713
714 Ok(Some(Self { pviommus: unique_pviommus, assigned_devices, filtered_dtbo_paths }))
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900715 }
716
717 /// Filters VM DTBO to only contain necessary information for booting pVM
718 /// In detail, this will remove followings by setting nop node / nop property.
719 /// - Removes unassigned devices
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900720 // TODO(b/277993056): remove unused dependencies in VM DTBO.
721 // TODO(b/277993056): remove supernodes' properties.
722 // TODO(b/277993056): remove unused alises.
723 pub fn filter(&self, vm_dtbo: &mut VmDtbo) -> Result<()> {
724 let vm_dtbo = vm_dtbo.as_mut();
725
726 // Filters unused node in assigned devices
727 for filtered_dtbo_path in &self.filtered_dtbo_paths {
728 let node = vm_dtbo.node_mut(filtered_dtbo_path).unwrap().unwrap();
729 node.nop()?;
730 }
731
Jaewan Kim371f6c82024-02-24 01:33:37 +0900732 filter_dangling_symbols(vm_dtbo)
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900733 }
734
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900735 fn patch_pviommus(&self, fdt: &mut Fdt) -> Result<BTreeMap<PvIommu, Phandle>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000736 let mut compatible = fdt.root_mut().next_compatible(Self::PVIOMMU_COMPATIBLE)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900737 let mut pviommu_phandles = BTreeMap::new();
738
739 for pviommu in &self.pviommus {
740 let mut node = compatible.ok_or(DeviceAssignmentError::TooManyPvIommu)?;
741 let phandle = node.as_node().get_phandle()?.ok_or(DeviceAssignmentError::Internal)?;
742 node.setprop_inplace(cstr!("id"), &pviommu.id.to_be_bytes())?;
743 if pviommu_phandles.insert(*pviommu, phandle).is_some() {
744 return Err(DeviceAssignmentError::Internal);
745 }
746 compatible = node.next_compatible(Self::PVIOMMU_COMPATIBLE)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900747 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900748
749 // Filters pre-populated but unassigned pvIOMMUs.
750 while let Some(filtered_pviommu) = compatible {
751 compatible = filtered_pviommu.delete_and_next_compatible(Self::PVIOMMU_COMPATIBLE)?;
752 }
753
754 Ok(pviommu_phandles)
755 }
756
757 pub fn patch(&self, fdt: &mut Fdt) -> Result<()> {
758 let pviommu_phandles = self.patch_pviommus(fdt)?;
759
760 // Patches assigned devices
761 for device in &self.assigned_devices {
762 device.patch(fdt, &pviommu_phandles)?;
763 }
764
Jaewan Kimc730ebf2024-02-22 10:34:55 +0900765 // Removes any dangling references in __symbols__ (e.g. removed pvIOMMUs)
766 filter_dangling_symbols(fdt)
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900767 }
768}
769
770#[cfg(test)]
771mod tests {
772 use super::*;
Jaewan Kim52477ae2023-11-21 21:20:52 +0900773 use alloc::collections::{BTreeMap, BTreeSet};
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900774 use std::fs;
775
776 const VM_DTBO_FILE_PATH: &str = "test_pvmfw_devices_vm_dtbo.dtbo";
777 const VM_DTBO_WITHOUT_SYMBOLS_FILE_PATH: &str =
778 "test_pvmfw_devices_vm_dtbo_without_symbols.dtbo";
Jaewan Kim19b984f2023-12-04 15:16:50 +0900779 const VM_DTBO_WITH_DUPLICATED_IOMMUS_FILE_PATH: &str =
780 "test_pvmfw_devices_vm_dtbo_with_duplicated_iommus.dtbo";
Jaewan Kima67e36a2023-11-29 16:50:23 +0900781 const FDT_WITHOUT_IOMMUS_FILE_PATH: &str = "test_pvmfw_devices_without_iommus.dtb";
Jaewan Kim52477ae2023-11-21 21:20:52 +0900782 const FDT_WITHOUT_DEVICE_FILE_PATH: &str = "test_pvmfw_devices_without_device.dtb";
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900783 const FDT_FILE_PATH: &str = "test_pvmfw_devices_with_rng.dtb";
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900784 const FDT_WITH_MULTIPLE_DEVICES_IOMMUS_FILE_PATH: &str =
785 "test_pvmfw_devices_with_multiple_devices_iommus.dtb";
786 const FDT_WITH_IOMMU_SHARING: &str = "test_pvmfw_devices_with_iommu_sharing.dtb";
787 const FDT_WITH_IOMMU_ID_CONFLICT: &str = "test_pvmfw_devices_with_iommu_id_conflict.dtb";
Jaewan Kim19b984f2023-12-04 15:16:50 +0900788 const FDT_WITH_DUPLICATED_PVIOMMUS_FILE_PATH: &str =
789 "test_pvmfw_devices_with_duplicated_pviommus.dtb";
790 const FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH: &str =
791 "test_pvmfw_devices_with_multiple_reg_iommus.dtb";
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900792
Jaewan Kim52477ae2023-11-21 21:20:52 +0900793 #[derive(Debug, Default)]
794 struct MockHypervisor {
795 mmio_tokens: BTreeMap<(u64, u64), u64>,
796 iommu_tokens: BTreeMap<(u64, u64), (u64, u64)>,
797 }
798
799 impl DeviceAssigningHypervisor for MockHypervisor {
800 fn get_phys_mmio_token(&self, base_ipa: u64, size: u64) -> hyp::Result<u64> {
801 Ok(*self.mmio_tokens.get(&(base_ipa, size)).ok_or(hyp::Error::KvmError(
802 hyp::KvmError::InvalidParameter,
803 0xc6000012, /* VENDOR_HYP_KVM_DEV_REQ_MMIO_FUNC_ID */
804 ))?)
805 }
806
807 fn get_phys_iommu_token(&self, pviommu_id: u64, vsid: u64) -> hyp::Result<(u64, u64)> {
808 Ok(*self.iommu_tokens.get(&(pviommu_id, vsid)).ok_or(hyp::Error::KvmError(
809 hyp::KvmError::InvalidParameter,
810 0xc6000013, /* VENDOR_HYP_KVM_DEV_REQ_DMA_FUNC_ID */
811 ))?)
812 }
813 }
814
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900815 #[derive(Debug, Eq, PartialEq)]
816 struct AssignedDeviceNode {
817 path: CString,
818 reg: Vec<u8>,
819 interrupts: Vec<u8>,
Jaewan Kima67e36a2023-11-29 16:50:23 +0900820 iommus: Vec<u32>, // pvIOMMU id and vSID
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900821 }
822
823 impl AssignedDeviceNode {
824 fn parse(fdt: &Fdt, path: &CStr) -> Result<Self> {
825 let Some(node) = fdt.node(path)? else {
826 return Err(FdtError::NotFound.into());
827 };
828
Jaewan Kim19b984f2023-12-04 15:16:50 +0900829 let reg = node.getprop(cstr!("reg"))?.ok_or(DeviceAssignmentError::MalformedReg)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900830 let interrupts = node
831 .getprop(cstr!("interrupts"))?
832 .ok_or(DeviceAssignmentError::InvalidInterrupts)?;
833 let mut iommus = vec![];
Jaewan Kima9200492023-11-21 20:45:31 +0900834 if let Some(mut cells) = node.getprop_cells(cstr!("iommus"))? {
835 while let Some(pviommu_id) = cells.next() {
836 // pvIOMMU id
837 let phandle = Phandle::try_from(pviommu_id)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900838 let pviommu = fdt
839 .node_with_phandle(phandle)?
Jaewan Kim19b984f2023-12-04 15:16:50 +0900840 .ok_or(DeviceAssignmentError::MalformedIommus)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900841 let compatible = pviommu.getprop_str(cstr!("compatible"));
842 if compatible != Ok(Some(cstr!("pkvm,pviommu"))) {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900843 return Err(DeviceAssignmentError::MalformedIommus);
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900844 }
845 let id = pviommu
846 .getprop_u32(cstr!("id"))?
Jaewan Kim19b984f2023-12-04 15:16:50 +0900847 .ok_or(DeviceAssignmentError::MalformedIommus)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900848 iommus.push(id);
Jaewan Kima9200492023-11-21 20:45:31 +0900849
850 // vSID
851 let Some(vsid) = cells.next() else {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900852 return Err(DeviceAssignmentError::MalformedIommus);
Jaewan Kima9200492023-11-21 20:45:31 +0900853 };
854 iommus.push(vsid);
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900855 }
856 }
857 Ok(Self { path: path.into(), reg: reg.into(), interrupts: interrupts.into(), iommus })
858 }
859 }
860
861 fn collect_pviommus(fdt: &Fdt) -> Result<Vec<u32>> {
862 let mut pviommus = BTreeSet::new();
863 for pviommu in fdt.compatible_nodes(cstr!("pkvm,pviommu"))? {
864 if let Ok(Some(id)) = pviommu.getprop_u32(cstr!("id")) {
865 pviommus.insert(id);
866 }
867 }
868 Ok(pviommus.iter().cloned().collect())
869 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900870
871 fn into_fdt_prop(native_bytes: Vec<u32>) -> Vec<u8> {
872 let mut v = Vec::with_capacity(native_bytes.len() * 4);
873 for byte in native_bytes {
874 v.extend_from_slice(&byte.to_be_bytes());
875 }
876 v
877 }
878
Jaewan Kim52477ae2023-11-21 21:20:52 +0900879 impl From<[u64; 2]> for DeviceReg {
880 fn from(fdt_cells: [u64; 2]) -> Self {
881 DeviceReg { addr: fdt_cells[0], size: fdt_cells[1] }
882 }
883 }
884
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900885 #[test]
886 fn device_info_new_without_symbols() {
887 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
888 let mut vm_dtbo_data = fs::read(VM_DTBO_WITHOUT_SYMBOLS_FILE_PATH).unwrap();
889 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
890 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
891
Jaewan Kim52477ae2023-11-21 21:20:52 +0900892 let hypervisor: MockHypervisor = Default::default();
893 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap();
894 assert_eq!(device_info, None);
895 }
896
897 #[test]
898 fn device_info_new_without_device() {
899 let mut fdt_data = fs::read(FDT_WITHOUT_DEVICE_FILE_PATH).unwrap();
900 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
901 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
902 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
903
904 let hypervisor: MockHypervisor = Default::default();
905 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900906 assert_eq!(device_info, None);
907 }
908
909 #[test]
Jaewan Kima67e36a2023-11-29 16:50:23 +0900910 fn device_info_assigned_info_without_iommus() {
911 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
912 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
913 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
914 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
915
Jaewan Kim52477ae2023-11-21 21:20:52 +0900916 let hypervisor = MockHypervisor {
917 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
918 iommu_tokens: BTreeMap::new(),
919 };
920 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kima67e36a2023-11-29 16:50:23 +0900921
922 let expected = [AssignedDeviceInfo {
Jaewan Kimc39974e2023-12-02 01:13:30 +0900923 node_path: CString::new("/bus0/backlight").unwrap(),
924 dtbo_node_path: cstr!("/fragment@backlight/__overlay__/bus0/backlight").into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +0900925 reg: vec![[0x9, 0xFF].into()],
Jaewan Kima67e36a2023-11-29 16:50:23 +0900926 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
927 iommus: vec![],
928 }];
929
930 assert_eq!(device_info.assigned_devices, expected);
931 }
932
933 #[test]
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900934 fn device_info_assigned_info() {
935 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
936 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
937 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
938 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
939
Jaewan Kim52477ae2023-11-21 21:20:52 +0900940 let hypervisor = MockHypervisor {
941 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
942 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
943 };
944 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900945
946 let expected = [AssignedDeviceInfo {
947 node_path: CString::new("/rng").unwrap(),
948 dtbo_node_path: cstr!("/fragment@rng/__overlay__/rng").into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +0900949 reg: vec![[0x9, 0xFF].into()],
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900950 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +0900951 iommus: vec![(PvIommu { id: 0x4 }, Vsid(0xFF0))],
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900952 }];
953
954 assert_eq!(device_info.assigned_devices, expected);
955 }
956
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900957 #[test]
958 fn device_info_filter() {
959 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
960 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
961 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
962 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
963
Jaewan Kim52477ae2023-11-21 21:20:52 +0900964 let hypervisor = MockHypervisor {
965 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
966 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
967 };
968 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900969 device_info.filter(vm_dtbo).unwrap();
970
971 let vm_dtbo = vm_dtbo.as_mut();
972
Jaewan Kim371f6c82024-02-24 01:33:37 +0900973 let symbols = vm_dtbo.symbols().unwrap().unwrap();
974
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900975 let rng = vm_dtbo.node(cstr!("/fragment@rng/__overlay__/rng")).unwrap();
976 assert_ne!(rng, None);
Jaewan Kim371f6c82024-02-24 01:33:37 +0900977 let rng_symbol = symbols.getprop_str(cstr!("rng")).unwrap();
978 assert_eq!(Some(cstr!("/fragment@rng/__overlay__/rng")), rng_symbol);
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900979
980 let light = vm_dtbo.node(cstr!("/fragment@rng/__overlay__/light")).unwrap();
981 assert_eq!(light, None);
Jaewan Kim371f6c82024-02-24 01:33:37 +0900982 let light_symbol = symbols.getprop_str(cstr!("light")).unwrap();
983 assert_eq!(None, light_symbol);
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900984
Jaewan Kima67e36a2023-11-29 16:50:23 +0900985 let led = vm_dtbo.node(cstr!("/fragment@led/__overlay__/led")).unwrap();
986 assert_eq!(led, None);
Jaewan Kim371f6c82024-02-24 01:33:37 +0900987 let led_symbol = symbols.getprop_str(cstr!("led")).unwrap();
988 assert_eq!(None, led_symbol);
Jaewan Kima67e36a2023-11-29 16:50:23 +0900989
Jaewan Kimc39974e2023-12-02 01:13:30 +0900990 let backlight =
991 vm_dtbo.node(cstr!("/fragment@backlight/__overlay__/bus0/backlight")).unwrap();
Jaewan Kima67e36a2023-11-29 16:50:23 +0900992 assert_eq!(backlight, None);
Jaewan Kim371f6c82024-02-24 01:33:37 +0900993 let backlight_symbol = symbols.getprop_str(cstr!("backlight")).unwrap();
994 assert_eq!(None, backlight_symbol);
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900995 }
996
997 #[test]
998 fn device_info_patch() {
Jaewan Kima67e36a2023-11-29 16:50:23 +0900999 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001000 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1001 let mut data = vec![0_u8; fdt_data.len() + vm_dtbo_data.len()];
1002 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1003 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1004 let platform_dt = Fdt::create_empty_tree(data.as_mut_slice()).unwrap();
1005
Jaewan Kim52477ae2023-11-21 21:20:52 +09001006 let hypervisor = MockHypervisor {
1007 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
1008 iommu_tokens: BTreeMap::new(),
1009 };
1010 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001011 device_info.filter(vm_dtbo).unwrap();
1012
1013 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1014 unsafe {
1015 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1016 }
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001017 device_info.patch(platform_dt).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001018
Jaewan Kimc39974e2023-12-02 01:13:30 +09001019 let rng_node = platform_dt.node(cstr!("/bus0/backlight")).unwrap().unwrap();
1020 let phandle = rng_node.getprop_u32(cstr!("phandle")).unwrap();
1021 assert_ne!(None, phandle);
1022
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001023 // Note: Intentionally not using AssignedDeviceNode for matching all props.
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001024 type FdtResult<T> = libfdt::Result<T>;
1025 let expected: Vec<(FdtResult<&CStr>, FdtResult<Vec<u8>>)> = vec![
Jaewan Kima67e36a2023-11-29 16:50:23 +09001026 (Ok(cstr!("android,backlight,ignore-gctrl-reset")), Ok(Vec::new())),
1027 (Ok(cstr!("compatible")), Ok(Vec::from(*b"android,backlight\0"))),
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001028 (Ok(cstr!("interrupts")), Ok(into_fdt_prop(vec![0x0, 0xF, 0x4]))),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001029 (Ok(cstr!("iommus")), Ok(Vec::new())),
Jaewan Kimc39974e2023-12-02 01:13:30 +09001030 (Ok(cstr!("phandle")), Ok(into_fdt_prop(vec![phandle.unwrap()]))),
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001031 (Ok(cstr!("reg")), Ok(into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]))),
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001032 ];
1033
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001034 let mut properties: Vec<_> = rng_node
1035 .properties()
1036 .unwrap()
1037 .map(|prop| (prop.name(), prop.value().map(|x| x.into())))
1038 .collect();
1039 properties.sort_by(|a, b| {
1040 let lhs = a.0.unwrap_or_default();
1041 let rhs = b.0.unwrap_or_default();
1042 lhs.partial_cmp(rhs).unwrap()
1043 });
1044
1045 assert_eq!(properties, expected);
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001046 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001047
1048 #[test]
Jaewan Kimc730ebf2024-02-22 10:34:55 +09001049 fn device_info_patch_no_pviommus() {
1050 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
1051 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1052 let mut data = vec![0_u8; fdt_data.len() + vm_dtbo_data.len()];
1053 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1054 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1055 let platform_dt = Fdt::create_empty_tree(data.as_mut_slice()).unwrap();
1056
1057 let hypervisor = MockHypervisor {
1058 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
1059 iommu_tokens: BTreeMap::new(),
1060 };
1061 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
1062 device_info.filter(vm_dtbo).unwrap();
1063
1064 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1065 unsafe {
1066 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1067 }
1068 device_info.patch(platform_dt).unwrap();
1069
1070 let compatible = platform_dt.root().next_compatible(cstr!("pkvm,pviommu")).unwrap();
1071 assert_eq!(None, compatible);
1072
1073 if let Some(symbols) = platform_dt.symbols().unwrap() {
1074 for prop in symbols.properties().unwrap() {
1075 let path = CStr::from_bytes_with_nul(prop.value().unwrap()).unwrap();
1076 assert_ne!(None, platform_dt.node(path).unwrap());
1077 }
1078 }
1079 }
1080
1081 #[test]
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001082 fn device_info_overlay_iommu() {
Jaewan Kima67e36a2023-11-29 16:50:23 +09001083 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001084 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1085 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1086 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1087 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1088 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1089 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1090 platform_dt.unpack().unwrap();
1091
Jaewan Kim52477ae2023-11-21 21:20:52 +09001092 let hypervisor = MockHypervisor {
1093 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
1094 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1095 };
1096 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001097 device_info.filter(vm_dtbo).unwrap();
1098
1099 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1100 unsafe {
1101 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1102 }
1103 device_info.patch(platform_dt).unwrap();
1104
1105 let expected = AssignedDeviceNode {
1106 path: CString::new("/rng").unwrap(),
1107 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1108 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima9200492023-11-21 20:45:31 +09001109 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001110 };
1111
1112 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1113 assert_eq!(node, Ok(expected));
1114
1115 let pviommus = collect_pviommus(platform_dt);
1116 assert_eq!(pviommus, Ok(vec![0x4]));
1117 }
1118
1119 #[test]
1120 fn device_info_multiple_devices_iommus() {
1121 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_DEVICES_IOMMUS_FILE_PATH).unwrap();
1122 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1123 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1124 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1125 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1126 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1127 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1128 platform_dt.unpack().unwrap();
1129
Jaewan Kim52477ae2023-11-21 21:20:52 +09001130 let hypervisor = MockHypervisor {
1131 mmio_tokens: [
1132 ((0x9, 0xFF), 0x12F00000),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001133 ((0x10000, 0x1000), 0xF00000),
1134 ((0x20000, 0x1000), 0xF10000),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001135 ]
1136 .into(),
1137 iommu_tokens: [
1138 ((0x4, 0xFF0), (0x12E40000, 3)),
1139 ((0x40, 0xFFA), (0x40000, 0x4)),
1140 ((0x50, 0xFFB), (0x50000, 0x5)),
1141 ]
1142 .into(),
1143 };
1144 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001145 device_info.filter(vm_dtbo).unwrap();
1146
1147 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1148 unsafe {
1149 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1150 }
1151 device_info.patch(platform_dt).unwrap();
1152
1153 let expected_devices = [
1154 AssignedDeviceNode {
1155 path: CString::new("/rng").unwrap(),
1156 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1157 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001158 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001159 },
1160 AssignedDeviceNode {
1161 path: CString::new("/light").unwrap(),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001162 reg: into_fdt_prop(vec![0x0, 0x10000, 0x0, 0x1000, 0x0, 0x20000, 0x0, 0x1000]),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001163 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x5]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001164 iommus: vec![0x40, 0xFFA, 0x50, 0xFFB],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001165 },
1166 ];
1167
1168 for expected in expected_devices {
1169 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1170 assert_eq!(node, Ok(expected));
1171 }
1172 let pviommus = collect_pviommus(platform_dt);
Jaewan Kima67e36a2023-11-29 16:50:23 +09001173 assert_eq!(pviommus, Ok(vec![0x4, 0x40, 0x50]));
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001174 }
1175
1176 #[test]
1177 fn device_info_iommu_sharing() {
1178 let mut fdt_data = fs::read(FDT_WITH_IOMMU_SHARING).unwrap();
1179 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1180 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1181 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1182 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1183 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1184 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1185 platform_dt.unpack().unwrap();
1186
Jaewan Kim52477ae2023-11-21 21:20:52 +09001187 let hypervisor = MockHypervisor {
Jaewan Kim19b984f2023-12-04 15:16:50 +09001188 mmio_tokens: [((0x9, 0xFF), 0x12F00000), ((0x1000, 0x9), 0x12000000)].into(),
1189 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 3)), ((0x4, 0xFF1), (0x12E40000, 9))].into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001190 };
1191 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001192 device_info.filter(vm_dtbo).unwrap();
1193
1194 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1195 unsafe {
1196 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1197 }
1198 device_info.patch(platform_dt).unwrap();
1199
1200 let expected_devices = [
1201 AssignedDeviceNode {
1202 path: CString::new("/rng").unwrap(),
1203 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1204 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001205 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001206 },
1207 AssignedDeviceNode {
Jaewan Kima67e36a2023-11-29 16:50:23 +09001208 path: CString::new("/led").unwrap(),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001209 reg: into_fdt_prop(vec![0x0, 0x1000, 0x0, 0x9]),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001210 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x5]),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001211 iommus: vec![0x4, 0xFF1],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001212 },
1213 ];
1214
1215 for expected in expected_devices {
1216 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1217 assert_eq!(node, Ok(expected));
1218 }
1219
1220 let pviommus = collect_pviommus(platform_dt);
Jaewan Kima67e36a2023-11-29 16:50:23 +09001221 assert_eq!(pviommus, Ok(vec![0x4]));
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001222 }
1223
1224 #[test]
1225 fn device_info_iommu_id_conflict() {
1226 let mut fdt_data = fs::read(FDT_WITH_IOMMU_ID_CONFLICT).unwrap();
1227 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1228 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1229 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1230
Jaewan Kim52477ae2023-11-21 21:20:52 +09001231 let hypervisor = MockHypervisor {
Jaewan Kim19b984f2023-12-04 15:16:50 +09001232 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001233 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1234 };
1235 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001236
1237 assert_eq!(device_info, Err(DeviceAssignmentError::DuplicatedPvIommuIds));
1238 }
Jaewan Kim52477ae2023-11-21 21:20:52 +09001239
1240 #[test]
1241 fn device_info_invalid_reg() {
1242 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1243 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1244 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1245 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1246
1247 let hypervisor = MockHypervisor {
1248 mmio_tokens: BTreeMap::new(),
1249 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1250 };
1251 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1252
1253 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidReg));
1254 }
1255
1256 #[test]
Jaewan Kim19b984f2023-12-04 15:16:50 +09001257 fn device_info_invalid_reg_out_of_order() {
1258 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH).unwrap();
1259 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1260 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1261 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1262
1263 let hypervisor = MockHypervisor {
1264 mmio_tokens: [((0xF000, 0x1000), 0xF10000), ((0xF100, 0x1000), 0xF00000)].into(),
1265 iommu_tokens: [((0xFF0, 0xF0), (0x40000, 0x4)), ((0xFF1, 0xF1), (0x50000, 0x5))].into(),
1266 };
1267 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1268
1269 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidReg));
1270 }
1271
1272 #[test]
Jaewan Kim52477ae2023-11-21 21:20:52 +09001273 fn device_info_invalid_iommus() {
1274 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1275 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1276 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1277 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1278
1279 let hypervisor = MockHypervisor {
1280 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
1281 iommu_tokens: BTreeMap::new(),
1282 };
1283 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1284
1285 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidIommus));
1286 }
Jaewan Kim19b984f2023-12-04 15:16:50 +09001287
1288 #[test]
1289 fn device_info_duplicated_pv_iommus() {
1290 let mut fdt_data = fs::read(FDT_WITH_DUPLICATED_PVIOMMUS_FILE_PATH).unwrap();
1291 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1292 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1293 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1294
1295 let hypervisor = MockHypervisor {
1296 mmio_tokens: [((0x10000, 0x1000), 0xF00000), ((0x20000, 0xFF), 0xF10000)].into(),
1297 iommu_tokens: [((0xFF, 0xF), (0x40000, 0x4))].into(),
1298 };
1299 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1300
1301 assert_eq!(device_info, Err(DeviceAssignmentError::DuplicatedPvIommuIds));
1302 }
1303
1304 #[test]
1305 fn device_info_duplicated_iommus() {
1306 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1307 let mut vm_dtbo_data = fs::read(VM_DTBO_WITH_DUPLICATED_IOMMUS_FILE_PATH).unwrap();
1308 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1309 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1310
1311 let hypervisor = MockHypervisor {
1312 mmio_tokens: [((0x10000, 0x1000), 0xF00000), ((0x20000, 0xFF), 0xF10000)].into(),
1313 iommu_tokens: [((0xFF, 0xF), (0x40000, 0x4))].into(),
1314 };
1315 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1316
1317 assert_eq!(device_info, Err(DeviceAssignmentError::UnsupportedIommusDuplication));
1318 }
1319
1320 #[test]
1321 fn device_info_duplicated_iommu_mapping() {
1322 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH).unwrap();
1323 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1324 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1325 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1326
1327 let hypervisor = MockHypervisor {
1328 mmio_tokens: [((0xF000, 0x1000), 0xF00000), ((0xF100, 0x1000), 0xF10000)].into(),
1329 iommu_tokens: [((0xFF0, 0xF0), (0x40000, 0x4)), ((0xFF1, 0xF1), (0x40000, 0x4))].into(),
1330 };
1331 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1332
1333 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidIommus));
1334 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001335}