blob: 2c47f9e75ffbb0214fa8518cc96bcc32c940e49c [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 Kim51ccfed2023-11-08 13:51:58 +0900708 filtered_dtbo_paths.push(CString::new("/__symbols__").unwrap());
Jaewan Kimc39974e2023-12-02 01:13:30 +0900709 // TODO(b/277993056): Also filter other unused nodes/props in __local_fixups__
710 filtered_dtbo_paths.push(CString::new("/__local_fixups__/host").unwrap());
711
712 // Note: Any node without __overlay__ will be ignored by fdt_apply_overlay,
713 // so doesn't need to be filtered.
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900714
715 Ok(Some(Self { pviommus: unique_pviommus, assigned_devices, filtered_dtbo_paths }))
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900716 }
717
718 /// Filters VM DTBO to only contain necessary information for booting pVM
719 /// In detail, this will remove followings by setting nop node / nop property.
720 /// - Removes unassigned devices
721 /// - Removes /__symbols__ node
722 // TODO(b/277993056): remove unused dependencies in VM DTBO.
723 // TODO(b/277993056): remove supernodes' properties.
724 // TODO(b/277993056): remove unused alises.
725 pub fn filter(&self, vm_dtbo: &mut VmDtbo) -> Result<()> {
726 let vm_dtbo = vm_dtbo.as_mut();
727
728 // Filters unused node in assigned devices
729 for filtered_dtbo_path in &self.filtered_dtbo_paths {
730 let node = vm_dtbo.node_mut(filtered_dtbo_path).unwrap().unwrap();
731 node.nop()?;
732 }
733
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900734 Ok(())
735 }
736
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900737 fn patch_pviommus(&self, fdt: &mut Fdt) -> Result<BTreeMap<PvIommu, Phandle>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000738 let mut compatible = fdt.root_mut().next_compatible(Self::PVIOMMU_COMPATIBLE)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900739 let mut pviommu_phandles = BTreeMap::new();
740
741 for pviommu in &self.pviommus {
742 let mut node = compatible.ok_or(DeviceAssignmentError::TooManyPvIommu)?;
743 let phandle = node.as_node().get_phandle()?.ok_or(DeviceAssignmentError::Internal)?;
744 node.setprop_inplace(cstr!("id"), &pviommu.id.to_be_bytes())?;
745 if pviommu_phandles.insert(*pviommu, phandle).is_some() {
746 return Err(DeviceAssignmentError::Internal);
747 }
748 compatible = node.next_compatible(Self::PVIOMMU_COMPATIBLE)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900749 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900750
751 // Filters pre-populated but unassigned pvIOMMUs.
752 while let Some(filtered_pviommu) = compatible {
753 compatible = filtered_pviommu.delete_and_next_compatible(Self::PVIOMMU_COMPATIBLE)?;
754 }
755
756 Ok(pviommu_phandles)
757 }
758
759 pub fn patch(&self, fdt: &mut Fdt) -> Result<()> {
760 let pviommu_phandles = self.patch_pviommus(fdt)?;
761
762 // Patches assigned devices
763 for device in &self.assigned_devices {
764 device.patch(fdt, &pviommu_phandles)?;
765 }
766
Jaewan Kimc730ebf2024-02-22 10:34:55 +0900767 // Removes any dangling references in __symbols__ (e.g. removed pvIOMMUs)
768 filter_dangling_symbols(fdt)
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900769 }
770}
771
772#[cfg(test)]
773mod tests {
774 use super::*;
Jaewan Kim52477ae2023-11-21 21:20:52 +0900775 use alloc::collections::{BTreeMap, BTreeSet};
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900776 use std::fs;
777
778 const VM_DTBO_FILE_PATH: &str = "test_pvmfw_devices_vm_dtbo.dtbo";
779 const VM_DTBO_WITHOUT_SYMBOLS_FILE_PATH: &str =
780 "test_pvmfw_devices_vm_dtbo_without_symbols.dtbo";
Jaewan Kim19b984f2023-12-04 15:16:50 +0900781 const VM_DTBO_WITH_DUPLICATED_IOMMUS_FILE_PATH: &str =
782 "test_pvmfw_devices_vm_dtbo_with_duplicated_iommus.dtbo";
Jaewan Kima67e36a2023-11-29 16:50:23 +0900783 const FDT_WITHOUT_IOMMUS_FILE_PATH: &str = "test_pvmfw_devices_without_iommus.dtb";
Jaewan Kim52477ae2023-11-21 21:20:52 +0900784 const FDT_WITHOUT_DEVICE_FILE_PATH: &str = "test_pvmfw_devices_without_device.dtb";
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900785 const FDT_FILE_PATH: &str = "test_pvmfw_devices_with_rng.dtb";
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900786 const FDT_WITH_MULTIPLE_DEVICES_IOMMUS_FILE_PATH: &str =
787 "test_pvmfw_devices_with_multiple_devices_iommus.dtb";
788 const FDT_WITH_IOMMU_SHARING: &str = "test_pvmfw_devices_with_iommu_sharing.dtb";
789 const FDT_WITH_IOMMU_ID_CONFLICT: &str = "test_pvmfw_devices_with_iommu_id_conflict.dtb";
Jaewan Kim19b984f2023-12-04 15:16:50 +0900790 const FDT_WITH_DUPLICATED_PVIOMMUS_FILE_PATH: &str =
791 "test_pvmfw_devices_with_duplicated_pviommus.dtb";
792 const FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH: &str =
793 "test_pvmfw_devices_with_multiple_reg_iommus.dtb";
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900794
Jaewan Kim52477ae2023-11-21 21:20:52 +0900795 #[derive(Debug, Default)]
796 struct MockHypervisor {
797 mmio_tokens: BTreeMap<(u64, u64), u64>,
798 iommu_tokens: BTreeMap<(u64, u64), (u64, u64)>,
799 }
800
801 impl DeviceAssigningHypervisor for MockHypervisor {
802 fn get_phys_mmio_token(&self, base_ipa: u64, size: u64) -> hyp::Result<u64> {
803 Ok(*self.mmio_tokens.get(&(base_ipa, size)).ok_or(hyp::Error::KvmError(
804 hyp::KvmError::InvalidParameter,
805 0xc6000012, /* VENDOR_HYP_KVM_DEV_REQ_MMIO_FUNC_ID */
806 ))?)
807 }
808
809 fn get_phys_iommu_token(&self, pviommu_id: u64, vsid: u64) -> hyp::Result<(u64, u64)> {
810 Ok(*self.iommu_tokens.get(&(pviommu_id, vsid)).ok_or(hyp::Error::KvmError(
811 hyp::KvmError::InvalidParameter,
812 0xc6000013, /* VENDOR_HYP_KVM_DEV_REQ_DMA_FUNC_ID */
813 ))?)
814 }
815 }
816
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900817 #[derive(Debug, Eq, PartialEq)]
818 struct AssignedDeviceNode {
819 path: CString,
820 reg: Vec<u8>,
821 interrupts: Vec<u8>,
Jaewan Kima67e36a2023-11-29 16:50:23 +0900822 iommus: Vec<u32>, // pvIOMMU id and vSID
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900823 }
824
825 impl AssignedDeviceNode {
826 fn parse(fdt: &Fdt, path: &CStr) -> Result<Self> {
827 let Some(node) = fdt.node(path)? else {
828 return Err(FdtError::NotFound.into());
829 };
830
Jaewan Kim19b984f2023-12-04 15:16:50 +0900831 let reg = node.getprop(cstr!("reg"))?.ok_or(DeviceAssignmentError::MalformedReg)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900832 let interrupts = node
833 .getprop(cstr!("interrupts"))?
834 .ok_or(DeviceAssignmentError::InvalidInterrupts)?;
835 let mut iommus = vec![];
Jaewan Kima9200492023-11-21 20:45:31 +0900836 if let Some(mut cells) = node.getprop_cells(cstr!("iommus"))? {
837 while let Some(pviommu_id) = cells.next() {
838 // pvIOMMU id
839 let phandle = Phandle::try_from(pviommu_id)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900840 let pviommu = fdt
841 .node_with_phandle(phandle)?
Jaewan Kim19b984f2023-12-04 15:16:50 +0900842 .ok_or(DeviceAssignmentError::MalformedIommus)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900843 let compatible = pviommu.getprop_str(cstr!("compatible"));
844 if compatible != Ok(Some(cstr!("pkvm,pviommu"))) {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900845 return Err(DeviceAssignmentError::MalformedIommus);
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900846 }
847 let id = pviommu
848 .getprop_u32(cstr!("id"))?
Jaewan Kim19b984f2023-12-04 15:16:50 +0900849 .ok_or(DeviceAssignmentError::MalformedIommus)?;
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900850 iommus.push(id);
Jaewan Kima9200492023-11-21 20:45:31 +0900851
852 // vSID
853 let Some(vsid) = cells.next() else {
Jaewan Kim19b984f2023-12-04 15:16:50 +0900854 return Err(DeviceAssignmentError::MalformedIommus);
Jaewan Kima9200492023-11-21 20:45:31 +0900855 };
856 iommus.push(vsid);
Jaewan Kim51ccfed2023-11-08 13:51:58 +0900857 }
858 }
859 Ok(Self { path: path.into(), reg: reg.into(), interrupts: interrupts.into(), iommus })
860 }
861 }
862
863 fn collect_pviommus(fdt: &Fdt) -> Result<Vec<u32>> {
864 let mut pviommus = BTreeSet::new();
865 for pviommu in fdt.compatible_nodes(cstr!("pkvm,pviommu"))? {
866 if let Ok(Some(id)) = pviommu.getprop_u32(cstr!("id")) {
867 pviommus.insert(id);
868 }
869 }
870 Ok(pviommus.iter().cloned().collect())
871 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900872
873 fn into_fdt_prop(native_bytes: Vec<u32>) -> Vec<u8> {
874 let mut v = Vec::with_capacity(native_bytes.len() * 4);
875 for byte in native_bytes {
876 v.extend_from_slice(&byte.to_be_bytes());
877 }
878 v
879 }
880
Jaewan Kim52477ae2023-11-21 21:20:52 +0900881 impl From<[u64; 2]> for DeviceReg {
882 fn from(fdt_cells: [u64; 2]) -> Self {
883 DeviceReg { addr: fdt_cells[0], size: fdt_cells[1] }
884 }
885 }
886
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900887 #[test]
888 fn device_info_new_without_symbols() {
889 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
890 let mut vm_dtbo_data = fs::read(VM_DTBO_WITHOUT_SYMBOLS_FILE_PATH).unwrap();
891 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
892 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
893
Jaewan Kim52477ae2023-11-21 21:20:52 +0900894 let hypervisor: MockHypervisor = Default::default();
895 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap();
896 assert_eq!(device_info, None);
897 }
898
899 #[test]
900 fn device_info_new_without_device() {
901 let mut fdt_data = fs::read(FDT_WITHOUT_DEVICE_FILE_PATH).unwrap();
902 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
903 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
904 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
905
906 let hypervisor: MockHypervisor = Default::default();
907 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900908 assert_eq!(device_info, None);
909 }
910
911 #[test]
Jaewan Kima67e36a2023-11-29 16:50:23 +0900912 fn device_info_assigned_info_without_iommus() {
913 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
914 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
915 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
916 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
917
Jaewan Kim52477ae2023-11-21 21:20:52 +0900918 let hypervisor = MockHypervisor {
919 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
920 iommu_tokens: BTreeMap::new(),
921 };
922 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kima67e36a2023-11-29 16:50:23 +0900923
924 let expected = [AssignedDeviceInfo {
Jaewan Kimc39974e2023-12-02 01:13:30 +0900925 node_path: CString::new("/bus0/backlight").unwrap(),
926 dtbo_node_path: cstr!("/fragment@backlight/__overlay__/bus0/backlight").into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +0900927 reg: vec![[0x9, 0xFF].into()],
Jaewan Kima67e36a2023-11-29 16:50:23 +0900928 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
929 iommus: vec![],
930 }];
931
932 assert_eq!(device_info.assigned_devices, expected);
933 }
934
935 #[test]
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900936 fn device_info_assigned_info() {
937 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
938 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
939 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
940 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
941
Jaewan Kim52477ae2023-11-21 21:20:52 +0900942 let hypervisor = MockHypervisor {
943 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
944 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
945 };
946 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900947
948 let expected = [AssignedDeviceInfo {
949 node_path: CString::new("/rng").unwrap(),
950 dtbo_node_path: cstr!("/fragment@rng/__overlay__/rng").into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +0900951 reg: vec![[0x9, 0xFF].into()],
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900952 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +0900953 iommus: vec![(PvIommu { id: 0x4 }, Vsid(0xFF0))],
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900954 }];
955
956 assert_eq!(device_info.assigned_devices, expected);
957 }
958
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900959 #[test]
960 fn device_info_filter() {
961 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
962 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
963 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
964 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
965
Jaewan Kim52477ae2023-11-21 21:20:52 +0900966 let hypervisor = MockHypervisor {
967 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
968 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
969 };
970 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900971 device_info.filter(vm_dtbo).unwrap();
972
973 let vm_dtbo = vm_dtbo.as_mut();
974
975 let rng = vm_dtbo.node(cstr!("/fragment@rng/__overlay__/rng")).unwrap();
976 assert_ne!(rng, None);
977
978 let light = vm_dtbo.node(cstr!("/fragment@rng/__overlay__/light")).unwrap();
979 assert_eq!(light, None);
980
Jaewan Kima67e36a2023-11-29 16:50:23 +0900981 let led = vm_dtbo.node(cstr!("/fragment@led/__overlay__/led")).unwrap();
982 assert_eq!(led, None);
983
Jaewan Kimc39974e2023-12-02 01:13:30 +0900984 let backlight =
985 vm_dtbo.node(cstr!("/fragment@backlight/__overlay__/bus0/backlight")).unwrap();
Jaewan Kima67e36a2023-11-29 16:50:23 +0900986 assert_eq!(backlight, None);
987
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900988 let symbols_node = vm_dtbo.symbols().unwrap();
989 assert_eq!(symbols_node, None);
990 }
991
992 #[test]
993 fn device_info_patch() {
Jaewan Kima67e36a2023-11-29 16:50:23 +0900994 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900995 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
996 let mut data = vec![0_u8; fdt_data.len() + vm_dtbo_data.len()];
997 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
998 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
999 let platform_dt = Fdt::create_empty_tree(data.as_mut_slice()).unwrap();
1000
Jaewan Kim52477ae2023-11-21 21:20:52 +09001001 let hypervisor = MockHypervisor {
1002 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
1003 iommu_tokens: BTreeMap::new(),
1004 };
1005 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001006 device_info.filter(vm_dtbo).unwrap();
1007
1008 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1009 unsafe {
1010 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1011 }
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001012 device_info.patch(platform_dt).unwrap();
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001013
Jaewan Kimc39974e2023-12-02 01:13:30 +09001014 let rng_node = platform_dt.node(cstr!("/bus0/backlight")).unwrap().unwrap();
1015 let phandle = rng_node.getprop_u32(cstr!("phandle")).unwrap();
1016 assert_ne!(None, phandle);
1017
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001018 // Note: Intentionally not using AssignedDeviceNode for matching all props.
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001019 type FdtResult<T> = libfdt::Result<T>;
1020 let expected: Vec<(FdtResult<&CStr>, FdtResult<Vec<u8>>)> = vec![
Jaewan Kima67e36a2023-11-29 16:50:23 +09001021 (Ok(cstr!("android,backlight,ignore-gctrl-reset")), Ok(Vec::new())),
1022 (Ok(cstr!("compatible")), Ok(Vec::from(*b"android,backlight\0"))),
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001023 (Ok(cstr!("interrupts")), Ok(into_fdt_prop(vec![0x0, 0xF, 0x4]))),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001024 (Ok(cstr!("iommus")), Ok(Vec::new())),
Jaewan Kimc39974e2023-12-02 01:13:30 +09001025 (Ok(cstr!("phandle")), Ok(into_fdt_prop(vec![phandle.unwrap()]))),
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001026 (Ok(cstr!("reg")), Ok(into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]))),
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001027 ];
1028
Jaewan Kim0bd637d2023-11-10 13:09:41 +09001029 let mut properties: Vec<_> = rng_node
1030 .properties()
1031 .unwrap()
1032 .map(|prop| (prop.name(), prop.value().map(|x| x.into())))
1033 .collect();
1034 properties.sort_by(|a, b| {
1035 let lhs = a.0.unwrap_or_default();
1036 let rhs = b.0.unwrap_or_default();
1037 lhs.partial_cmp(rhs).unwrap()
1038 });
1039
1040 assert_eq!(properties, expected);
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001041 }
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001042
1043 #[test]
Jaewan Kimc730ebf2024-02-22 10:34:55 +09001044 fn device_info_patch_no_pviommus() {
1045 let mut fdt_data = fs::read(FDT_WITHOUT_IOMMUS_FILE_PATH).unwrap();
1046 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1047 let mut data = vec![0_u8; fdt_data.len() + vm_dtbo_data.len()];
1048 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1049 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1050 let platform_dt = Fdt::create_empty_tree(data.as_mut_slice()).unwrap();
1051
1052 let hypervisor = MockHypervisor {
1053 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
1054 iommu_tokens: BTreeMap::new(),
1055 };
1056 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
1057 device_info.filter(vm_dtbo).unwrap();
1058
1059 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1060 unsafe {
1061 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1062 }
1063 device_info.patch(platform_dt).unwrap();
1064
1065 let compatible = platform_dt.root().next_compatible(cstr!("pkvm,pviommu")).unwrap();
1066 assert_eq!(None, compatible);
1067
1068 if let Some(symbols) = platform_dt.symbols().unwrap() {
1069 for prop in symbols.properties().unwrap() {
1070 let path = CStr::from_bytes_with_nul(prop.value().unwrap()).unwrap();
1071 assert_ne!(None, platform_dt.node(path).unwrap());
1072 }
1073 }
1074 }
1075
1076 #[test]
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001077 fn device_info_overlay_iommu() {
Jaewan Kima67e36a2023-11-29 16:50:23 +09001078 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001079 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1080 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1081 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1082 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1083 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1084 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1085 platform_dt.unpack().unwrap();
1086
Jaewan Kim52477ae2023-11-21 21:20:52 +09001087 let hypervisor = MockHypervisor {
1088 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
1089 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1090 };
1091 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001092 device_info.filter(vm_dtbo).unwrap();
1093
1094 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1095 unsafe {
1096 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1097 }
1098 device_info.patch(platform_dt).unwrap();
1099
1100 let expected = AssignedDeviceNode {
1101 path: CString::new("/rng").unwrap(),
1102 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1103 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima9200492023-11-21 20:45:31 +09001104 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001105 };
1106
1107 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1108 assert_eq!(node, Ok(expected));
1109
1110 let pviommus = collect_pviommus(platform_dt);
1111 assert_eq!(pviommus, Ok(vec![0x4]));
1112 }
1113
1114 #[test]
1115 fn device_info_multiple_devices_iommus() {
1116 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_DEVICES_IOMMUS_FILE_PATH).unwrap();
1117 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1118 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1119 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1120 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1121 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1122 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1123 platform_dt.unpack().unwrap();
1124
Jaewan Kim52477ae2023-11-21 21:20:52 +09001125 let hypervisor = MockHypervisor {
1126 mmio_tokens: [
1127 ((0x9, 0xFF), 0x12F00000),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001128 ((0x10000, 0x1000), 0xF00000),
1129 ((0x20000, 0x1000), 0xF10000),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001130 ]
1131 .into(),
1132 iommu_tokens: [
1133 ((0x4, 0xFF0), (0x12E40000, 3)),
1134 ((0x40, 0xFFA), (0x40000, 0x4)),
1135 ((0x50, 0xFFB), (0x50000, 0x5)),
1136 ]
1137 .into(),
1138 };
1139 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001140 device_info.filter(vm_dtbo).unwrap();
1141
1142 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1143 unsafe {
1144 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1145 }
1146 device_info.patch(platform_dt).unwrap();
1147
1148 let expected_devices = [
1149 AssignedDeviceNode {
1150 path: CString::new("/rng").unwrap(),
1151 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1152 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001153 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001154 },
1155 AssignedDeviceNode {
1156 path: CString::new("/light").unwrap(),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001157 reg: into_fdt_prop(vec![0x0, 0x10000, 0x0, 0x1000, 0x0, 0x20000, 0x0, 0x1000]),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001158 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x5]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001159 iommus: vec![0x40, 0xFFA, 0x50, 0xFFB],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001160 },
1161 ];
1162
1163 for expected in expected_devices {
1164 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1165 assert_eq!(node, Ok(expected));
1166 }
1167 let pviommus = collect_pviommus(platform_dt);
Jaewan Kima67e36a2023-11-29 16:50:23 +09001168 assert_eq!(pviommus, Ok(vec![0x4, 0x40, 0x50]));
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001169 }
1170
1171 #[test]
1172 fn device_info_iommu_sharing() {
1173 let mut fdt_data = fs::read(FDT_WITH_IOMMU_SHARING).unwrap();
1174 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1175 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1176 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1177 let mut platform_dt_data = pvmfw_fdt_template::RAW.to_vec();
1178 platform_dt_data.resize(pvmfw_fdt_template::RAW.len() * 2, 0);
1179 let platform_dt = Fdt::from_mut_slice(&mut platform_dt_data).unwrap();
1180 platform_dt.unpack().unwrap();
1181
Jaewan Kim52477ae2023-11-21 21:20:52 +09001182 let hypervisor = MockHypervisor {
Jaewan Kim19b984f2023-12-04 15:16:50 +09001183 mmio_tokens: [((0x9, 0xFF), 0x12F00000), ((0x1000, 0x9), 0x12000000)].into(),
1184 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 3)), ((0x4, 0xFF1), (0x12E40000, 9))].into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001185 };
1186 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor).unwrap().unwrap();
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001187 device_info.filter(vm_dtbo).unwrap();
1188
1189 // SAFETY: Damaged VM DTBO wouldn't be used after this unsafe block.
1190 unsafe {
1191 platform_dt.apply_overlay(vm_dtbo.as_mut()).unwrap();
1192 }
1193 device_info.patch(platform_dt).unwrap();
1194
1195 let expected_devices = [
1196 AssignedDeviceNode {
1197 path: CString::new("/rng").unwrap(),
1198 reg: into_fdt_prop(vec![0x0, 0x9, 0x0, 0xFF]),
1199 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x4]),
Jaewan Kima67e36a2023-11-29 16:50:23 +09001200 iommus: vec![0x4, 0xFF0],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001201 },
1202 AssignedDeviceNode {
Jaewan Kima67e36a2023-11-29 16:50:23 +09001203 path: CString::new("/led").unwrap(),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001204 reg: into_fdt_prop(vec![0x0, 0x1000, 0x0, 0x9]),
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001205 interrupts: into_fdt_prop(vec![0x0, 0xF, 0x5]),
Jaewan Kim19b984f2023-12-04 15:16:50 +09001206 iommus: vec![0x4, 0xFF1],
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001207 },
1208 ];
1209
1210 for expected in expected_devices {
1211 let node = AssignedDeviceNode::parse(platform_dt, &expected.path);
1212 assert_eq!(node, Ok(expected));
1213 }
1214
1215 let pviommus = collect_pviommus(platform_dt);
Jaewan Kima67e36a2023-11-29 16:50:23 +09001216 assert_eq!(pviommus, Ok(vec![0x4]));
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001217 }
1218
1219 #[test]
1220 fn device_info_iommu_id_conflict() {
1221 let mut fdt_data = fs::read(FDT_WITH_IOMMU_ID_CONFLICT).unwrap();
1222 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1223 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1224 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1225
Jaewan Kim52477ae2023-11-21 21:20:52 +09001226 let hypervisor = MockHypervisor {
Jaewan Kim19b984f2023-12-04 15:16:50 +09001227 mmio_tokens: [((0x9, 0xFF), 0x300)].into(),
Jaewan Kim52477ae2023-11-21 21:20:52 +09001228 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1229 };
1230 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
Jaewan Kim51ccfed2023-11-08 13:51:58 +09001231
1232 assert_eq!(device_info, Err(DeviceAssignmentError::DuplicatedPvIommuIds));
1233 }
Jaewan Kim52477ae2023-11-21 21:20:52 +09001234
1235 #[test]
1236 fn device_info_invalid_reg() {
1237 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1238 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1239 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1240 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1241
1242 let hypervisor = MockHypervisor {
1243 mmio_tokens: BTreeMap::new(),
1244 iommu_tokens: [((0x4, 0xFF0), (0x12E40000, 0x3))].into(),
1245 };
1246 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1247
1248 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidReg));
1249 }
1250
1251 #[test]
Jaewan Kim19b984f2023-12-04 15:16:50 +09001252 fn device_info_invalid_reg_out_of_order() {
1253 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH).unwrap();
1254 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1255 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1256 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1257
1258 let hypervisor = MockHypervisor {
1259 mmio_tokens: [((0xF000, 0x1000), 0xF10000), ((0xF100, 0x1000), 0xF00000)].into(),
1260 iommu_tokens: [((0xFF0, 0xF0), (0x40000, 0x4)), ((0xFF1, 0xF1), (0x50000, 0x5))].into(),
1261 };
1262 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1263
1264 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidReg));
1265 }
1266
1267 #[test]
Jaewan Kim52477ae2023-11-21 21:20:52 +09001268 fn device_info_invalid_iommus() {
1269 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1270 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1271 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1272 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1273
1274 let hypervisor = MockHypervisor {
1275 mmio_tokens: [((0x9, 0xFF), 0x12F00000)].into(),
1276 iommu_tokens: BTreeMap::new(),
1277 };
1278 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1279
1280 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidIommus));
1281 }
Jaewan Kim19b984f2023-12-04 15:16:50 +09001282
1283 #[test]
1284 fn device_info_duplicated_pv_iommus() {
1285 let mut fdt_data = fs::read(FDT_WITH_DUPLICATED_PVIOMMUS_FILE_PATH).unwrap();
1286 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1287 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1288 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1289
1290 let hypervisor = MockHypervisor {
1291 mmio_tokens: [((0x10000, 0x1000), 0xF00000), ((0x20000, 0xFF), 0xF10000)].into(),
1292 iommu_tokens: [((0xFF, 0xF), (0x40000, 0x4))].into(),
1293 };
1294 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1295
1296 assert_eq!(device_info, Err(DeviceAssignmentError::DuplicatedPvIommuIds));
1297 }
1298
1299 #[test]
1300 fn device_info_duplicated_iommus() {
1301 let mut fdt_data = fs::read(FDT_FILE_PATH).unwrap();
1302 let mut vm_dtbo_data = fs::read(VM_DTBO_WITH_DUPLICATED_IOMMUS_FILE_PATH).unwrap();
1303 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1304 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1305
1306 let hypervisor = MockHypervisor {
1307 mmio_tokens: [((0x10000, 0x1000), 0xF00000), ((0x20000, 0xFF), 0xF10000)].into(),
1308 iommu_tokens: [((0xFF, 0xF), (0x40000, 0x4))].into(),
1309 };
1310 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1311
1312 assert_eq!(device_info, Err(DeviceAssignmentError::UnsupportedIommusDuplication));
1313 }
1314
1315 #[test]
1316 fn device_info_duplicated_iommu_mapping() {
1317 let mut fdt_data = fs::read(FDT_WITH_MULTIPLE_REG_IOMMU_FILE_PATH).unwrap();
1318 let mut vm_dtbo_data = fs::read(VM_DTBO_FILE_PATH).unwrap();
1319 let fdt = Fdt::from_mut_slice(&mut fdt_data).unwrap();
1320 let vm_dtbo = VmDtbo::from_mut_slice(&mut vm_dtbo_data).unwrap();
1321
1322 let hypervisor = MockHypervisor {
1323 mmio_tokens: [((0xF000, 0x1000), 0xF00000), ((0xF100, 0x1000), 0xF10000)].into(),
1324 iommu_tokens: [((0xFF0, 0xF0), (0x40000, 0x4)), ((0xFF1, 0xF1), (0x40000, 0x4))].into(),
1325 };
1326 let device_info = DeviceAssignmentInfo::parse(fdt, vm_dtbo, &hypervisor);
1327
1328 assert_eq!(device_info, Err(DeviceAssignmentError::InvalidIommus));
1329 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001330}