blob: 41ae5e5b22a7f4c0bd15d9b528912a137c0c0905 [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, 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//! High-level FDT functions.
16
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090017use crate::bootargs::BootArgsIterator;
Jaewan Kim52477ae2023-11-21 21:20:52 +090018use crate::device_assignment::{DeviceAssignmentInfo, VmDtbo};
Jiyong Park00ceff32023-03-13 05:43:23 +000019use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090020use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090024use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090025use core::cmp::max;
26use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000027use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000028use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090029use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000031use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000032use fdtpci::PciMemoryFlags;
33use fdtpci::PciRangeType;
34use libfdt::AddressRange;
35use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000036use libfdt::Fdt;
37use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080038use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000039use libfdt::FdtNodeMut;
Jiyong Park83316122023-03-21 09:39:39 +090040use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000041use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090042use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000043use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000044use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000045use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000046use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000047use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000048use vmbase::memory::SIZE_4KB;
49use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000050use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000051use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000052
Alice Wangabc7d632023-06-14 09:10:14 +000053/// An enumeration of errors that can occur during the FDT validation.
54#[derive(Clone, Debug)]
55pub enum FdtValidationError {
56 /// Invalid CPU count.
57 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080058 /// Invalid VCpufreq Range.
59 InvalidVcpufreq(u64, u64),
Alice Wangabc7d632023-06-14 09:10:14 +000060}
61
62impl fmt::Display for FdtValidationError {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 match self {
65 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
David Dai9bdb10c2024-02-01 22:42:54 -080066 Self::InvalidVcpufreq(addr, size) => write!(f, "Invalid vcpufreq regs: {addr}, {size}"),
Alice Wangabc7d632023-06-14 09:10:14 +000067 }
68 }
69}
70
Jiyong Park6a8789a2023-03-21 14:50:59 +090071/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
72/// not an error.
73fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090074 let addr = cstr!("kernel-address");
75 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000076
Jiyong Parkb87f3302023-03-21 10:03:11 +090077 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000078 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
79 let addr = addr as usize;
80 let size = size as usize;
81
82 return Ok(Some(addr..(addr + size)));
83 }
84 }
85
86 Ok(None)
87}
88
Jiyong Park6a8789a2023-03-21 14:50:59 +090089/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
90/// error as there can be initrd-less VM.
91fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090092 let start = cstr!("linux,initrd-start");
93 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000094
95 if let Some(chosen) = fdt.chosen()? {
96 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
97 return Ok(Some((start as usize)..(end as usize)));
98 }
99 }
100
101 Ok(None)
102}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000103
Jiyong Park9c63cd12023-03-21 17:53:07 +0900104fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
105 let start = u32::try_from(initrd_range.start).unwrap();
106 let end = u32::try_from(initrd_range.end).unwrap();
107
108 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
109 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
110 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
111 Ok(())
112}
113
Jiyong Parke9d87e82023-03-21 19:28:40 +0900114fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
115 if let Some(chosen) = fdt.chosen()? {
116 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
117 // We need to copy the string to heap because the original fdt will be invalidated
118 // by the templated DT
119 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
120 return Ok(Some(copy));
121 }
122 }
123 Ok(None)
124}
125
126fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
127 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900128 // This function is called before the verification is done. So, we just copy the bootargs to
129 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
130 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900131 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
132}
133
Alice Wang0d527472023-06-13 14:55:38 +0000134/// Reads and validates the memory range in the DT.
135///
136/// Only one memory range is expected with the crosvm setup for now.
137fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
138 let mut memory = fdt.memory().map_err(|e| {
139 error!("Failed to read memory range from DT: {e}");
140 RebootReason::InvalidFdt
141 })?;
142 let range = memory.next().ok_or_else(|| {
143 error!("The /memory node in the DT contains no range.");
144 RebootReason::InvalidFdt
145 })?;
146 if memory.next().is_some() {
147 warn!(
148 "The /memory node in the DT contains more than one memory range, \
149 while only one is expected."
150 );
151 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900152 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000153 if base != MEM_START {
154 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000155 return Err(RebootReason::InvalidFdt);
156 }
157
Jiyong Park6a8789a2023-03-21 14:50:59 +0900158 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000159 if size % GUEST_PAGE_SIZE != 0 {
160 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
161 return Err(RebootReason::InvalidFdt);
162 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000163
Jiyong Park6a8789a2023-03-21 14:50:59 +0900164 if size == 0 {
165 error!("Memory size is 0");
166 return Err(RebootReason::InvalidFdt);
167 }
Alice Wang0d527472023-06-13 14:55:38 +0000168 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000169}
170
Jiyong Park9c63cd12023-03-21 17:53:07 +0900171fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000172 let addr = u64::try_from(MEM_START).unwrap();
173 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900174 fdt.node_mut(cstr!("/memory"))?
175 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000176 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900177}
178
David Dai9bdb10c2024-02-01 22:42:54 -0800179//TODO: Need to add info for cpu capacity
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000180#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800181struct CpuInfo {
182 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
183}
184
185impl CpuInfo {
186 const MAX_OPPTABLES: usize = 16;
187}
188
189fn read_opp_info_from(
190 opp_node: FdtNode,
191) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
192 let mut table = ArrayVec::new();
193 for subnode in opp_node.subnodes()? {
194 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
195 table.push(prop);
196 }
197
198 Ok(table)
199}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900200
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000201fn read_cpu_info_from(fdt: &Fdt) -> libfdt::Result<ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>> {
202 let mut cpus = ArrayVec::new();
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000203 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800204 for cpu in cpu_nodes.by_ref().take(cpus.capacity()) {
205 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
206 let opptable_info = if let Some(phandle) = opp_phandle {
207 let phandle = phandle.try_into()?;
208 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
209 Some(read_opp_info_from(node)?)
210 } else {
211 None
212 };
213 let info = CpuInfo { opptable_info };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000214 cpus.push(info);
Jiyong Park6a8789a2023-03-21 14:50:59 +0900215 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000216 if cpu_nodes.next().is_some() {
217 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
218 }
219
220 Ok(cpus)
Jiyong Park9c63cd12023-03-21 17:53:07 +0900221}
222
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000223fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
224 if cpus.is_empty() {
225 return Err(FdtValidationError::InvalidCpuCount(0));
226 }
227
228 Ok(())
229}
230
David Dai9bdb10c2024-02-01 22:42:54 -0800231fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
232 if let Some(node) = fdt.node(cstr!("/cpufreq"))? {
233 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
234 let reg = regs.next().ok_or(FdtError::NotFound)?;
235 return Ok(Some(VcpufreqInfo { addr: reg.addr, size: reg.size.unwrap() }));
236 };
237
238 Ok(None)
239}
240
241fn validate_vcpufreq_info(
242 vcpufreq_info: &VcpufreqInfo,
243 cpus: &[CpuInfo],
244) -> Result<(), FdtValidationError> {
245 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
246 const VCPUFREQ_SIZE: u64 = 0x8;
247
248 let base = vcpufreq_info.addr;
249 let size = vcpufreq_info.size;
250 if base != VCPUFREQ_BASE_ADDR {
251 error!("vcpufreq base address {:#x} is not {:#x}", base, VCPUFREQ_BASE_ADDR);
252 return Err(FdtValidationError::InvalidVcpufreq(base, size));
253 };
254 let expected_size = VCPUFREQ_SIZE * cpus.len() as u64;
255 if size != expected_size {
256 error!("vcpufreq reg size {:#x} is not {:#x}", size, expected_size);
257 return Err(FdtValidationError::InvalidVcpufreq(base, size));
258 };
259
260 Ok(())
261}
262
263fn patch_opptable(
264 node: FdtNodeMut,
265 opptable: ArrayVec<[u64; DeviceTreeInfo::MAX_CPUS]>,
266) -> libfdt::Result<()> {
267 let oppcompat = cstr!("operating-points-v2");
268 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
269 let mut next_subnode = next.first_subnode()?;
270
271 for entry in opptable {
272 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
273 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
274 next_subnode = subnode.next_subnode()?;
275 }
276
277 while let Some(current) = next_subnode {
278 next_subnode = current.delete_and_next_subnode()?;
279 }
280 Ok(())
281}
282
283// TODO(ptosi): Rework FdtNodeMut and replace this function.
284fn get_nth_compatible<'a>(
285 fdt: &'a mut Fdt,
286 n: usize,
287 compat: &CStr,
288) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
289 let mut node = fdt.root_mut()?.next_compatible(compat)?;
290 for _ in 0..n {
291 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
292 }
293 Ok(node)
294}
295
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000296fn patch_cpus(fdt: &mut Fdt, cpus: &[CpuInfo]) -> libfdt::Result<()> {
297 const COMPAT: &CStr = cstr!("arm,arm-v8");
David Dai9bdb10c2024-02-01 22:42:54 -0800298 for (idx, cpu) in cpus.iter().enumerate() {
299 let cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
300 if let Some(opptable) = cpu.opptable_info {
301 patch_opptable(cur, opptable)?;
302 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900303 }
David Dai9bdb10c2024-02-01 22:42:54 -0800304 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900305 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000306 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900307 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900308 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000309}
310
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900311/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900312fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900313 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900314 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900315 for property in avf_node.properties()? {
316 let name = property.name()?;
317 let value = property.value()?;
318 property_map.insert(
319 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
320 value.to_vec(),
321 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900322 }
323 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900324 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900325}
326
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900327/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
328/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
329fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900330 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900331 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900332 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900333) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900334 let mut root_vm_dt = vm_dt.root_mut()?;
335 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900336 // TODO(b/318431677): Validate nodes beyond /avf.
337 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900338 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900339 if let Some(ref_value) = avf_node.getprop(name)? {
340 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900341 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900342 "Property mismatches while applying overlay VM reference DT. \
343 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
344 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900345 );
346 return Err(FdtError::BadValue);
347 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900348 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900349 }
350 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900351 Ok(())
352}
353
Jiyong Park00ceff32023-03-13 05:43:23 +0000354#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000355struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900356 ranges: [PciAddrRange; 2],
357 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
358 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000359}
360
Jiyong Park6a8789a2023-03-21 14:50:59 +0900361impl PciInfo {
362 const IRQ_MASK_CELLS: usize = 4;
363 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100364 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000365}
366
Jiyong Park6a8789a2023-03-21 14:50:59 +0900367type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
368type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
369type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000370
371/// Iterator that takes N cells as a chunk
372struct CellChunkIterator<'a, const N: usize> {
373 cells: CellIterator<'a>,
374}
375
376impl<'a, const N: usize> CellChunkIterator<'a, N> {
377 fn new(cells: CellIterator<'a>) -> Self {
378 Self { cells }
379 }
380}
381
382impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
383 type Item = [u32; N];
384 fn next(&mut self) -> Option<Self::Item> {
385 let mut ret: Self::Item = [0; N];
386 for i in ret.iter_mut() {
387 *i = self.cells.next()?;
388 }
389 Some(ret)
390 }
391}
392
Jiyong Park6a8789a2023-03-21 14:50:59 +0900393/// Read pci host controller ranges, irq maps, and irq map masks from DT
394fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
395 let node =
396 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
397
398 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
399 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
400 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
401
402 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000403 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
404 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
405
406 if chunks.next().is_some() {
407 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
408 return Err(FdtError::NoSpace);
409 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900410
411 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000412 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
413 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
414
415 if chunks.next().is_some() {
416 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
417 return Err(FdtError::NoSpace);
418 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900419
420 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
421}
422
Jiyong Park0ee65392023-03-27 20:52:45 +0900423fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900424 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900425 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900426 }
427 for irq_mask in pci_info.irq_masks.iter() {
428 validate_pci_irq_mask(irq_mask)?;
429 }
430 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
431 validate_pci_irq_map(irq_map, idx)?;
432 }
433 Ok(())
434}
435
Jiyong Park0ee65392023-03-27 20:52:45 +0900436fn validate_pci_addr_range(
437 range: &PciAddrRange,
438 memory_range: &Range<usize>,
439) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900440 let mem_flags = PciMemoryFlags(range.addr.0);
441 let range_type = mem_flags.range_type();
442 let prefetchable = mem_flags.prefetchable();
443 let bus_addr = range.addr.1;
444 let cpu_addr = range.parent_addr;
445 let size = range.size;
446
447 if range_type != PciRangeType::Memory64 {
448 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
449 return Err(RebootReason::InvalidFdt);
450 }
451 if prefetchable {
452 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
453 return Err(RebootReason::InvalidFdt);
454 }
455 // Enforce ID bus-to-cpu mappings, as used by crosvm.
456 if bus_addr != cpu_addr {
457 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
458 return Err(RebootReason::InvalidFdt);
459 }
460
Jiyong Park0ee65392023-03-27 20:52:45 +0900461 let Some(bus_end) = bus_addr.checked_add(size) else {
462 error!("PCI address range size {:#x} overflows", size);
463 return Err(RebootReason::InvalidFdt);
464 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000465 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900466 error!("PCI address end {:#x} is outside of translatable range", bus_end);
467 return Err(RebootReason::InvalidFdt);
468 }
469
470 let memory_start = memory_range.start.try_into().unwrap();
471 let memory_end = memory_range.end.try_into().unwrap();
472
473 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
474 error!(
475 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
476 bus_addr, bus_end, memory_start, memory_end
477 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900478 return Err(RebootReason::InvalidFdt);
479 }
480
481 Ok(())
482}
483
484fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000485 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
486 const IRQ_MASK_ADDR_ME: u32 = 0x0;
487 const IRQ_MASK_ADDR_LO: u32 = 0x0;
488 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900489 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000490 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900491 if *irq_mask != EXPECTED {
492 error!("Invalid PCI irq mask {:#?}", irq_mask);
493 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000494 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900495 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000496}
497
Jiyong Park6a8789a2023-03-21 14:50:59 +0900498fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000499 const PCI_DEVICE_IDX: usize = 11;
500 const PCI_IRQ_ADDR_ME: u32 = 0;
501 const PCI_IRQ_ADDR_LO: u32 = 0;
502 const PCI_IRQ_INTC: u32 = 1;
503 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
504 const GIC_SPI: u32 = 0;
505 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
506
Jiyong Park6a8789a2023-03-21 14:50:59 +0900507 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
508 let pci_irq_number = irq_map[3];
509 let _controller_phandle = irq_map[4]; // skipped.
510 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
511 // interrupt-cells is <3> for GIC
512 let gic_peripheral_interrupt_type = irq_map[7];
513 let gic_irq_number = irq_map[8];
514 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000515
Jiyong Park6a8789a2023-03-21 14:50:59 +0900516 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
517 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000518
Jiyong Park6a8789a2023-03-21 14:50:59 +0900519 if pci_addr != expected_pci_addr {
520 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
521 {:#x} {:#x} {:#x}",
522 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
523 return Err(RebootReason::InvalidFdt);
524 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000525
Jiyong Park6a8789a2023-03-21 14:50:59 +0900526 if pci_irq_number != PCI_IRQ_INTC {
527 error!(
528 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
529 pci_irq_number, PCI_IRQ_INTC
530 );
531 return Err(RebootReason::InvalidFdt);
532 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000533
Jiyong Park6a8789a2023-03-21 14:50:59 +0900534 if gic_addr != (0, 0) {
535 error!(
536 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
537 {:#x} {:#x}",
538 gic_addr.0, gic_addr.1, 0, 0
539 );
540 return Err(RebootReason::InvalidFdt);
541 }
542
543 if gic_peripheral_interrupt_type != GIC_SPI {
544 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
545 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
546 return Err(RebootReason::InvalidFdt);
547 }
548
549 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
550 if gic_irq_number != irq_nr {
551 error!(
552 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
553 gic_irq_number, irq_nr
554 );
555 return Err(RebootReason::InvalidFdt);
556 }
557
558 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
559 error!(
560 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
561 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
562 );
563 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000564 }
565 Ok(())
566}
567
Jiyong Park9c63cd12023-03-21 17:53:07 +0900568fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
569 let mut node = fdt
570 .root_mut()?
571 .next_compatible(cstr!("pci-host-cam-generic"))?
572 .ok_or(FdtError::NotFound)?;
573
574 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
575 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
576
577 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
578 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
579
580 node.setprop_inplace(
581 cstr!("ranges"),
582 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
583 )
584}
585
Jiyong Park00ceff32023-03-13 05:43:23 +0000586#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900587struct SerialInfo {
588 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000589}
590
591impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900592 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000593}
594
Jiyong Park6a8789a2023-03-21 14:50:59 +0900595fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000596 let mut addrs = ArrayVec::new();
597
598 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
599 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000600 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900601 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000602 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000603 if serial_nodes.next().is_some() {
604 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
605 }
606
Jiyong Park6a8789a2023-03-21 14:50:59 +0900607 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000608}
609
Jiyong Park9c63cd12023-03-21 17:53:07 +0900610/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
611fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
612 let name = cstr!("ns16550a");
613 let mut next = fdt.root_mut()?.next_compatible(name);
614 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000615 let reg =
616 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900617 next = if !serial_info.addrs.contains(&reg.addr) {
618 current.delete_and_next_compatible(name)
619 } else {
620 current.next_compatible(name)
621 }
622 }
623 Ok(())
624}
625
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700626fn validate_swiotlb_info(
627 swiotlb_info: &SwiotlbInfo,
628 memory: &Range<usize>,
629) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900630 let size = swiotlb_info.size;
631 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000632
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700633 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000634 error!("Invalid swiotlb size {:#x}", size);
635 return Err(RebootReason::InvalidFdt);
636 }
637
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000638 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000639 error!("Invalid swiotlb alignment {:#x}", align);
640 return Err(RebootReason::InvalidFdt);
641 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700642
Alice Wang9cfbfd62023-06-14 11:19:03 +0000643 if let Some(addr) = swiotlb_info.addr {
644 if addr.checked_add(size).is_none() {
645 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
646 return Err(RebootReason::InvalidFdt);
647 }
648 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700649 if let Some(range) = swiotlb_info.fixed_range() {
650 if !range.is_within(memory) {
651 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
652 return Err(RebootReason::InvalidFdt);
653 }
654 }
655
Jiyong Park6a8789a2023-03-21 14:50:59 +0900656 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000657}
658
Jiyong Park9c63cd12023-03-21 17:53:07 +0900659fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
660 let mut node =
661 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700662
663 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000664 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700665 cstr!("reg"),
666 range.start.try_into().unwrap(),
667 range.len().try_into().unwrap(),
668 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000669 node.nop_property(cstr!("size"))?;
670 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700671 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000672 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700673 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000674 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700675 }
676
Jiyong Park9c63cd12023-03-21 17:53:07 +0900677 Ok(())
678}
679
680fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
681 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
682 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
683 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
684 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
685
686 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000687 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
688 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000689 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900690
691 // range1 is just below range0
692 range1.addr = addr - size;
693 range1.size = Some(size);
694
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000695 let (addr0, size0) = range0.to_cells();
696 let (addr1, size1) = range1.to_cells();
697 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900698
699 let mut node =
700 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
701 node.setprop_inplace(cstr!("reg"), flatten(&value))
702}
703
704fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
705 const NUM_INTERRUPTS: usize = 4;
706 const CELLS_PER_INTERRUPT: usize = 3;
707 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
708 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
709 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
710 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
711
712 let num_cpus: u32 = num_cpus.try_into().unwrap();
713 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
714 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
715 *v |= cpu_mask;
716 }
717 for v in value.iter_mut() {
718 *v = v.to_be();
719 }
720
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000721 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900722
723 let mut node =
724 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000725 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900726}
727
Jiyong Park00ceff32023-03-13 05:43:23 +0000728#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800729struct VcpufreqInfo {
730 addr: u64,
731 size: u64,
732}
733
734fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
735 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
736 if let Some(info) = vcpufreq_info {
737 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
738 } else {
739 node.nop()
740 }
741}
742
743#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900744pub struct DeviceTreeInfo {
745 pub kernel_range: Option<Range<usize>>,
746 pub initrd_range: Option<Range<usize>>,
747 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900748 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000749 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000750 pci_info: PciInfo,
751 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700752 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900753 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900754 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800755 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000756}
757
758impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000759 const MAX_CPUS: usize = 16;
760
761 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000762 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
763
764 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
765 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000766}
767
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900768pub fn sanitize_device_tree(
769 fdt: &mut [u8],
770 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900771 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900772) -> Result<DeviceTreeInfo, RebootReason> {
773 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
774 error!("Failed to load FDT: {e}");
775 RebootReason::InvalidFdt
776 })?;
777
778 let vm_dtbo = match vm_dtbo {
779 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
780 error!("Failed to load VM DTBO: {e}");
781 RebootReason::InvalidFdt
782 })?),
783 None => None,
784 };
785
786 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900787
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000788 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
789 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
790 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900791 error!("Failed to instantiate FDT from the template DT: {e}");
792 RebootReason::InvalidFdt
793 })?;
794
Jaewan Kim9220e852023-12-01 10:58:40 +0900795 fdt.unpack().map_err(|e| {
796 error!("Failed to unpack DT for patching: {e}");
797 RebootReason::InvalidFdt
798 })?;
799
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900800 if let Some(device_assignment_info) = &info.device_assignment {
801 let vm_dtbo = vm_dtbo.unwrap();
802 device_assignment_info.filter(vm_dtbo).map_err(|e| {
803 error!("Failed to filter VM DTBO: {e}");
804 RebootReason::InvalidFdt
805 })?;
806 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
807 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
808 // it can only be instantiated after validation.
809 unsafe {
810 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
811 error!("Failed to apply filtered VM DTBO: {e}");
812 RebootReason::InvalidFdt
813 })?;
814 }
815 }
816
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900817 if let Some(vm_ref_dt) = vm_ref_dt {
818 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
819 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900820 RebootReason::InvalidFdt
821 })?;
822
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900823 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
824 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900825 RebootReason::InvalidFdt
826 })?;
827 }
828
Jiyong Park9c63cd12023-03-21 17:53:07 +0900829 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900830
Jaewan Kim19b984f2023-12-04 15:16:50 +0900831 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
832
Jaewan Kim9220e852023-12-01 10:58:40 +0900833 fdt.pack().map_err(|e| {
834 error!("Failed to unpack DT after patching: {e}");
835 RebootReason::InvalidFdt
836 })?;
837
Jiyong Park6a8789a2023-03-21 14:50:59 +0900838 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900839}
840
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900841fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900842 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
843 error!("Failed to read kernel range from DT: {e}");
844 RebootReason::InvalidFdt
845 })?;
846
847 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
848 error!("Failed to read initrd range from DT: {e}");
849 RebootReason::InvalidFdt
850 })?;
851
Alice Wang0d527472023-06-13 14:55:38 +0000852 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900853
Jiyong Parke9d87e82023-03-21 19:28:40 +0900854 let bootargs = read_bootargs_from(fdt).map_err(|e| {
855 error!("Failed to read bootargs from DT: {e}");
856 RebootReason::InvalidFdt
857 })?;
858
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000859 let cpus = read_cpu_info_from(fdt).map_err(|e| {
860 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900861 RebootReason::InvalidFdt
862 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000863 validate_cpu_info(&cpus).map_err(|e| {
864 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +0000865 RebootReason::InvalidFdt
866 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900867
David Dai9bdb10c2024-02-01 22:42:54 -0800868 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
869 error!("Failed to read vcpufreq info from DT: {e}");
870 RebootReason::InvalidFdt
871 })?;
872 if let Some(ref info) = vcpufreq_info {
873 validate_vcpufreq_info(info, &cpus).map_err(|e| {
874 error!("Failed to validate vcpufreq info from DT: {e}");
875 RebootReason::InvalidFdt
876 })?;
877 }
878
Jiyong Park6a8789a2023-03-21 14:50:59 +0900879 let pci_info = read_pci_info_from(fdt).map_err(|e| {
880 error!("Failed to read pci info from DT: {e}");
881 RebootReason::InvalidFdt
882 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900883 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900884
885 let serial_info = read_serial_info_from(fdt).map_err(|e| {
886 error!("Failed to read serial info from DT: {e}");
887 RebootReason::InvalidFdt
888 })?;
889
Alice Wang9cfbfd62023-06-14 11:19:03 +0000890 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900891 error!("Failed to read swiotlb info from DT: {e}");
892 RebootReason::InvalidFdt
893 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700894 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900895
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900896 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900897 Some(vm_dtbo) => {
898 if let Some(hypervisor) = hyp::get_device_assigner() {
899 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
900 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
901 RebootReason::InvalidFdt
902 })?
903 } else {
904 warn!(
905 "Device assignment is ignored because device assigning hypervisor is missing"
906 );
907 None
908 }
909 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900910 None => None,
911 };
912
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900913 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900914 error!("Failed to read names of properties under /avf from DT: {e}");
915 RebootReason::InvalidFdt
916 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900917
Jiyong Park00ceff32023-03-13 05:43:23 +0000918 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900919 kernel_range,
920 initrd_range,
921 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900922 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000923 cpus,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900924 pci_info,
925 serial_info,
926 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900927 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900928 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -0800929 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000930 })
931}
932
Jiyong Park9c63cd12023-03-21 17:53:07 +0900933fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
934 if let Some(initrd_range) = &info.initrd_range {
935 patch_initrd_range(fdt, initrd_range).map_err(|e| {
936 error!("Failed to patch initrd range to DT: {e}");
937 RebootReason::InvalidFdt
938 })?;
939 }
940 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
941 error!("Failed to patch memory range to DT: {e}");
942 RebootReason::InvalidFdt
943 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900944 if let Some(bootargs) = &info.bootargs {
945 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
946 error!("Failed to patch bootargs to DT: {e}");
947 RebootReason::InvalidFdt
948 })?;
949 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000950 patch_cpus(fdt, &info.cpus).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900951 error!("Failed to patch cpus to DT: {e}");
952 RebootReason::InvalidFdt
953 })?;
David Dai9bdb10c2024-02-01 22:42:54 -0800954 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
955 error!("Failed to patch vcpufreq info to DT: {e}");
956 RebootReason::InvalidFdt
957 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900958 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
959 error!("Failed to patch pci info to DT: {e}");
960 RebootReason::InvalidFdt
961 })?;
962 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
963 error!("Failed to patch serial info to DT: {e}");
964 RebootReason::InvalidFdt
965 })?;
966 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
967 error!("Failed to patch swiotlb info to DT: {e}");
968 RebootReason::InvalidFdt
969 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000970 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900971 error!("Failed to patch gic info to DT: {e}");
972 RebootReason::InvalidFdt
973 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000974 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900975 error!("Failed to patch timer info to DT: {e}");
976 RebootReason::InvalidFdt
977 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900978 if let Some(device_assignment) = &info.device_assignment {
979 // Note: We patch values after VM DTBO is overlaid because patch may require more space
980 // then VM DTBO's underlying slice is allocated.
981 device_assignment.patch(fdt).map_err(|e| {
982 error!("Failed to patch device assignment info to DT: {e}");
983 RebootReason::InvalidFdt
984 })?;
985 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900986
Jiyong Park9c63cd12023-03-21 17:53:07 +0900987 Ok(())
988}
989
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000990/// Modifies the input DT according to the fields of the configuration.
991pub fn modify_for_next_stage(
992 fdt: &mut Fdt,
993 bcc: &[u8],
994 new_instance: bool,
995 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000996 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900997 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000998 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000999) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001000 if let Some(debug_policy) = debug_policy {
1001 let backup = Vec::from(fdt.as_slice());
1002 fdt.unpack()?;
1003 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1004 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1005 info!("Debug policy applied.");
1006 } else {
1007 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1008 fdt.unpack()?;
1009 }
1010 } else {
1011 info!("No debug policy found.");
1012 fdt.unpack()?;
1013 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001014
Jiyong Parke9d87e82023-03-21 19:28:40 +09001015 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001016
Alice Wang56ec45b2023-06-15 08:30:32 +00001017 if let Some(mut chosen) = fdt.chosen_mut()? {
1018 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1019 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001020 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001021 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001022 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001023 if let Some(bootargs) = read_bootargs_from(fdt)? {
1024 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1025 }
1026 }
1027
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001028 fdt.pack()?;
1029
1030 Ok(())
1031}
1032
Jiyong Parke9d87e82023-03-21 19:28:40 +09001033/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1034fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001035 // We reject DTs with missing reserved-memory node as validation should have checked that the
1036 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001037 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001038
Jiyong Parke9d87e82023-03-21 19:28:40 +09001039 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001040
Jiyong Parke9d87e82023-03-21 19:28:40 +09001041 let addr: u64 = addr.try_into().unwrap();
1042 let size: u64 = size.try_into().unwrap();
1043 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001044}
1045
Alice Wang56ec45b2023-06-15 08:30:32 +00001046fn empty_or_delete_prop(
1047 fdt_node: &mut FdtNodeMut,
1048 prop_name: &CStr,
1049 keep_prop: bool,
1050) -> libfdt::Result<()> {
1051 if keep_prop {
1052 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001053 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001054 fdt_node
1055 .delprop(prop_name)
1056 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001057 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001058}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001059
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001060/// Apply the debug policy overlay to the guest DT.
1061///
1062/// Returns Ok(true) on success, Ok(false) on recovered failure and Err(_) on corruption of the DT.
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001063fn apply_debug_policy(
1064 fdt: &mut Fdt,
1065 backup_fdt: &Fdt,
1066 debug_policy: &[u8],
1067) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001068 let mut debug_policy = Vec::from(debug_policy);
1069 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001070 Ok(overlay) => overlay,
1071 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001072 warn!("Corrupted debug policy found: {e}. Not applying.");
1073 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001074 }
1075 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001076
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001077 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001078 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001079 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001080 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001081 // A successful restoration is considered success because an invalid debug policy
1082 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001083 Ok(false)
1084 } else {
1085 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001086 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001087}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001088
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001089fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001090 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1091 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1092 return Ok(value == 1);
1093 }
1094 }
1095 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1096}
1097
1098fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001099 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1100 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001101
1102 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1103 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1104 ("crashkernel", Box::new(|_| has_crashkernel)),
1105 ("console", Box::new(|_| has_console)),
1106 ];
1107
1108 // parse and filter out unwanted
1109 let mut filtered = Vec::new();
1110 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1111 info!("Invalid bootarg: {e}");
1112 FdtError::BadValue
1113 })? {
1114 match accepted.iter().find(|&t| t.0 == arg.name()) {
1115 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1116 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1117 }
1118 }
1119
1120 // flatten into a new C-string
1121 let mut new_bootargs = Vec::new();
1122 for (i, arg) in filtered.iter().enumerate() {
1123 if i != 0 {
1124 new_bootargs.push(b' '); // separator
1125 }
1126 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1127 }
1128 new_bootargs.push(b'\0');
1129
1130 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1131 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1132}