blob: 65b46c0cb368a82b30a7790a1ddc2ae378458c58 [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}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000066 Self::InvalidVcpufreq(addr, size) => {
67 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
68 }
Alice Wangabc7d632023-06-14 09:10:14 +000069 }
70 }
71}
72
Jiyong Park6a8789a2023-03-21 14:50:59 +090073/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
74/// not an error.
75fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090076 let addr = cstr!("kernel-address");
77 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000078
Jiyong Parkb87f3302023-03-21 10:03:11 +090079 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000080 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
81 let addr = addr as usize;
82 let size = size as usize;
83
84 return Ok(Some(addr..(addr + size)));
85 }
86 }
87
88 Ok(None)
89}
90
Jiyong Park6a8789a2023-03-21 14:50:59 +090091/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
92/// error as there can be initrd-less VM.
93fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090094 let start = cstr!("linux,initrd-start");
95 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000096
97 if let Some(chosen) = fdt.chosen()? {
98 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
99 return Ok(Some((start as usize)..(end as usize)));
100 }
101 }
102
103 Ok(None)
104}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000105
Jiyong Park9c63cd12023-03-21 17:53:07 +0900106fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
107 let start = u32::try_from(initrd_range.start).unwrap();
108 let end = u32::try_from(initrd_range.end).unwrap();
109
110 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
111 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
112 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
113 Ok(())
114}
115
Jiyong Parke9d87e82023-03-21 19:28:40 +0900116fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
117 if let Some(chosen) = fdt.chosen()? {
118 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
119 // We need to copy the string to heap because the original fdt will be invalidated
120 // by the templated DT
121 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
122 return Ok(Some(copy));
123 }
124 }
125 Ok(None)
126}
127
128fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
129 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900130 // This function is called before the verification is done. So, we just copy the bootargs to
131 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
132 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900133 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
134}
135
Alice Wang0d527472023-06-13 14:55:38 +0000136/// Reads and validates the memory range in the DT.
137///
138/// Only one memory range is expected with the crosvm setup for now.
139fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
140 let mut memory = fdt.memory().map_err(|e| {
141 error!("Failed to read memory range from DT: {e}");
142 RebootReason::InvalidFdt
143 })?;
144 let range = memory.next().ok_or_else(|| {
145 error!("The /memory node in the DT contains no range.");
146 RebootReason::InvalidFdt
147 })?;
148 if memory.next().is_some() {
149 warn!(
150 "The /memory node in the DT contains more than one memory range, \
151 while only one is expected."
152 );
153 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900154 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000155 if base != MEM_START {
156 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000157 return Err(RebootReason::InvalidFdt);
158 }
159
Jiyong Park6a8789a2023-03-21 14:50:59 +0900160 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000161 if size % GUEST_PAGE_SIZE != 0 {
162 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
163 return Err(RebootReason::InvalidFdt);
164 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000165
Jiyong Park6a8789a2023-03-21 14:50:59 +0900166 if size == 0 {
167 error!("Memory size is 0");
168 return Err(RebootReason::InvalidFdt);
169 }
Alice Wang0d527472023-06-13 14:55:38 +0000170 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000171}
172
Jiyong Park9c63cd12023-03-21 17:53:07 +0900173fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000174 let addr = u64::try_from(MEM_START).unwrap();
175 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900176 fdt.node_mut(cstr!("/memory"))?
177 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000178 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900179}
180
David Dai9bdb10c2024-02-01 22:42:54 -0800181//TODO: Need to add info for cpu capacity
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000182#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800183struct CpuInfo {
184 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
185}
186
187impl CpuInfo {
188 const MAX_OPPTABLES: usize = 16;
189}
190
191fn read_opp_info_from(
192 opp_node: FdtNode,
193) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
194 let mut table = ArrayVec::new();
195 for subnode in opp_node.subnodes()? {
196 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
197 table.push(prop);
198 }
199
200 Ok(table)
201}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900202
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000203fn read_cpu_info_from(fdt: &Fdt) -> libfdt::Result<ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>> {
204 let mut cpus = ArrayVec::new();
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000205 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800206 for cpu in cpu_nodes.by_ref().take(cpus.capacity()) {
207 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
208 let opptable_info = if let Some(phandle) = opp_phandle {
209 let phandle = phandle.try_into()?;
210 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
211 Some(read_opp_info_from(node)?)
212 } else {
213 None
214 };
215 let info = CpuInfo { opptable_info };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000216 cpus.push(info);
Jiyong Park6a8789a2023-03-21 14:50:59 +0900217 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000218 if cpu_nodes.next().is_some() {
219 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
220 }
221
222 Ok(cpus)
Jiyong Park9c63cd12023-03-21 17:53:07 +0900223}
224
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000225fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
226 if cpus.is_empty() {
227 return Err(FdtValidationError::InvalidCpuCount(0));
228 }
229
230 Ok(())
231}
232
David Dai9bdb10c2024-02-01 22:42:54 -0800233fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000234 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
235 let Some(node) = nodes.next() else {
236 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800237 };
238
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000239 if nodes.next().is_some() {
240 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
241 }
242
243 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
244 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000245 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000246
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000247 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800248}
249
250fn validate_vcpufreq_info(
251 vcpufreq_info: &VcpufreqInfo,
252 cpus: &[CpuInfo],
253) -> Result<(), FdtValidationError> {
254 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000255 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800256
257 let base = vcpufreq_info.addr;
258 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000259 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
260
261 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800262 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000263 }
David Dai9bdb10c2024-02-01 22:42:54 -0800264
265 Ok(())
266}
267
268fn patch_opptable(
269 node: FdtNodeMut,
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000270 opptable: Option<ArrayVec<[u64; DeviceTreeInfo::MAX_CPUS]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800271) -> libfdt::Result<()> {
272 let oppcompat = cstr!("operating-points-v2");
273 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000274
275 let Some(opptable) = opptable else {
276 return next.nop();
277 };
278
David Dai9bdb10c2024-02-01 22:42:54 -0800279 let mut next_subnode = next.first_subnode()?;
280
281 for entry in opptable {
282 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
283 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
284 next_subnode = subnode.next_subnode()?;
285 }
286
287 while let Some(current) = next_subnode {
288 next_subnode = current.delete_and_next_subnode()?;
289 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000290
David Dai9bdb10c2024-02-01 22:42:54 -0800291 Ok(())
292}
293
294// TODO(ptosi): Rework FdtNodeMut and replace this function.
295fn get_nth_compatible<'a>(
296 fdt: &'a mut Fdt,
297 n: usize,
298 compat: &CStr,
299) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
300 let mut node = fdt.root_mut()?.next_compatible(compat)?;
301 for _ in 0..n {
302 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
303 }
304 Ok(node)
305}
306
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000307fn patch_cpus(fdt: &mut Fdt, cpus: &[CpuInfo]) -> libfdt::Result<()> {
308 const COMPAT: &CStr = cstr!("arm,arm-v8");
David Dai9bdb10c2024-02-01 22:42:54 -0800309 for (idx, cpu) in cpus.iter().enumerate() {
310 let cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000311 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900312 }
David Dai9bdb10c2024-02-01 22:42:54 -0800313 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900314 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000315 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900316 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900317 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000318}
319
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900320/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900321fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900322 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900323 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900324 for property in avf_node.properties()? {
325 let name = property.name()?;
326 let value = property.value()?;
327 property_map.insert(
328 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
329 value.to_vec(),
330 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900331 }
332 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900333 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900334}
335
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900336/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
337/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
338fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900339 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900340 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900341 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900342) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900343 let mut root_vm_dt = vm_dt.root_mut()?;
344 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900345 // TODO(b/318431677): Validate nodes beyond /avf.
346 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900347 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900348 if let Some(ref_value) = avf_node.getprop(name)? {
349 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900350 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900351 "Property mismatches while applying overlay VM reference DT. \
352 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
353 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900354 );
355 return Err(FdtError::BadValue);
356 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900357 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900358 }
359 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900360 Ok(())
361}
362
Jiyong Park00ceff32023-03-13 05:43:23 +0000363#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000364struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900365 ranges: [PciAddrRange; 2],
366 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
367 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000368}
369
Jiyong Park6a8789a2023-03-21 14:50:59 +0900370impl PciInfo {
371 const IRQ_MASK_CELLS: usize = 4;
372 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100373 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000374}
375
Jiyong Park6a8789a2023-03-21 14:50:59 +0900376type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
377type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
378type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000379
380/// Iterator that takes N cells as a chunk
381struct CellChunkIterator<'a, const N: usize> {
382 cells: CellIterator<'a>,
383}
384
385impl<'a, const N: usize> CellChunkIterator<'a, N> {
386 fn new(cells: CellIterator<'a>) -> Self {
387 Self { cells }
388 }
389}
390
391impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
392 type Item = [u32; N];
393 fn next(&mut self) -> Option<Self::Item> {
394 let mut ret: Self::Item = [0; N];
395 for i in ret.iter_mut() {
396 *i = self.cells.next()?;
397 }
398 Some(ret)
399 }
400}
401
Jiyong Park6a8789a2023-03-21 14:50:59 +0900402/// Read pci host controller ranges, irq maps, and irq map masks from DT
403fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
404 let node =
405 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
406
407 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
408 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
409 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
410
411 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000412 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
413 let irq_masks = (&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 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000421 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
422 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
423
424 if chunks.next().is_some() {
425 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
426 return Err(FdtError::NoSpace);
427 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900428
429 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
430}
431
Jiyong Park0ee65392023-03-27 20:52:45 +0900432fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900433 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900434 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900435 }
436 for irq_mask in pci_info.irq_masks.iter() {
437 validate_pci_irq_mask(irq_mask)?;
438 }
439 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
440 validate_pci_irq_map(irq_map, idx)?;
441 }
442 Ok(())
443}
444
Jiyong Park0ee65392023-03-27 20:52:45 +0900445fn validate_pci_addr_range(
446 range: &PciAddrRange,
447 memory_range: &Range<usize>,
448) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900449 let mem_flags = PciMemoryFlags(range.addr.0);
450 let range_type = mem_flags.range_type();
451 let prefetchable = mem_flags.prefetchable();
452 let bus_addr = range.addr.1;
453 let cpu_addr = range.parent_addr;
454 let size = range.size;
455
456 if range_type != PciRangeType::Memory64 {
457 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
458 return Err(RebootReason::InvalidFdt);
459 }
460 if prefetchable {
461 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
462 return Err(RebootReason::InvalidFdt);
463 }
464 // Enforce ID bus-to-cpu mappings, as used by crosvm.
465 if bus_addr != cpu_addr {
466 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
467 return Err(RebootReason::InvalidFdt);
468 }
469
Jiyong Park0ee65392023-03-27 20:52:45 +0900470 let Some(bus_end) = bus_addr.checked_add(size) else {
471 error!("PCI address range size {:#x} overflows", size);
472 return Err(RebootReason::InvalidFdt);
473 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000474 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900475 error!("PCI address end {:#x} is outside of translatable range", bus_end);
476 return Err(RebootReason::InvalidFdt);
477 }
478
479 let memory_start = memory_range.start.try_into().unwrap();
480 let memory_end = memory_range.end.try_into().unwrap();
481
482 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
483 error!(
484 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
485 bus_addr, bus_end, memory_start, memory_end
486 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900487 return Err(RebootReason::InvalidFdt);
488 }
489
490 Ok(())
491}
492
493fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000494 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
495 const IRQ_MASK_ADDR_ME: u32 = 0x0;
496 const IRQ_MASK_ADDR_LO: u32 = 0x0;
497 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900498 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000499 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900500 if *irq_mask != EXPECTED {
501 error!("Invalid PCI irq mask {:#?}", irq_mask);
502 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000503 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900504 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000505}
506
Jiyong Park6a8789a2023-03-21 14:50:59 +0900507fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000508 const PCI_DEVICE_IDX: usize = 11;
509 const PCI_IRQ_ADDR_ME: u32 = 0;
510 const PCI_IRQ_ADDR_LO: u32 = 0;
511 const PCI_IRQ_INTC: u32 = 1;
512 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
513 const GIC_SPI: u32 = 0;
514 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
515
Jiyong Park6a8789a2023-03-21 14:50:59 +0900516 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
517 let pci_irq_number = irq_map[3];
518 let _controller_phandle = irq_map[4]; // skipped.
519 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
520 // interrupt-cells is <3> for GIC
521 let gic_peripheral_interrupt_type = irq_map[7];
522 let gic_irq_number = irq_map[8];
523 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000524
Jiyong Park6a8789a2023-03-21 14:50:59 +0900525 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
526 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000527
Jiyong Park6a8789a2023-03-21 14:50:59 +0900528 if pci_addr != expected_pci_addr {
529 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
530 {:#x} {:#x} {:#x}",
531 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
532 return Err(RebootReason::InvalidFdt);
533 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000534
Jiyong Park6a8789a2023-03-21 14:50:59 +0900535 if pci_irq_number != PCI_IRQ_INTC {
536 error!(
537 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
538 pci_irq_number, PCI_IRQ_INTC
539 );
540 return Err(RebootReason::InvalidFdt);
541 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000542
Jiyong Park6a8789a2023-03-21 14:50:59 +0900543 if gic_addr != (0, 0) {
544 error!(
545 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
546 {:#x} {:#x}",
547 gic_addr.0, gic_addr.1, 0, 0
548 );
549 return Err(RebootReason::InvalidFdt);
550 }
551
552 if gic_peripheral_interrupt_type != GIC_SPI {
553 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
554 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
555 return Err(RebootReason::InvalidFdt);
556 }
557
558 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
559 if gic_irq_number != irq_nr {
560 error!(
561 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
562 gic_irq_number, irq_nr
563 );
564 return Err(RebootReason::InvalidFdt);
565 }
566
567 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
568 error!(
569 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
570 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
571 );
572 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000573 }
574 Ok(())
575}
576
Jiyong Park9c63cd12023-03-21 17:53:07 +0900577fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
578 let mut node = fdt
579 .root_mut()?
580 .next_compatible(cstr!("pci-host-cam-generic"))?
581 .ok_or(FdtError::NotFound)?;
582
583 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
584 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
585
586 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
587 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
588
589 node.setprop_inplace(
590 cstr!("ranges"),
591 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
592 )
593}
594
Jiyong Park00ceff32023-03-13 05:43:23 +0000595#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900596struct SerialInfo {
597 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000598}
599
600impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900601 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000602}
603
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000605 let mut addrs = ArrayVec::new();
606
607 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
608 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000609 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900610 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000611 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000612 if serial_nodes.next().is_some() {
613 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
614 }
615
Jiyong Park6a8789a2023-03-21 14:50:59 +0900616 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000617}
618
Jiyong Park9c63cd12023-03-21 17:53:07 +0900619/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
620fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
621 let name = cstr!("ns16550a");
622 let mut next = fdt.root_mut()?.next_compatible(name);
623 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000624 let reg =
625 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900626 next = if !serial_info.addrs.contains(&reg.addr) {
627 current.delete_and_next_compatible(name)
628 } else {
629 current.next_compatible(name)
630 }
631 }
632 Ok(())
633}
634
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700635fn validate_swiotlb_info(
636 swiotlb_info: &SwiotlbInfo,
637 memory: &Range<usize>,
638) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639 let size = swiotlb_info.size;
640 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000641
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700642 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000643 error!("Invalid swiotlb size {:#x}", size);
644 return Err(RebootReason::InvalidFdt);
645 }
646
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000647 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000648 error!("Invalid swiotlb alignment {:#x}", align);
649 return Err(RebootReason::InvalidFdt);
650 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700651
Alice Wang9cfbfd62023-06-14 11:19:03 +0000652 if let Some(addr) = swiotlb_info.addr {
653 if addr.checked_add(size).is_none() {
654 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
655 return Err(RebootReason::InvalidFdt);
656 }
657 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700658 if let Some(range) = swiotlb_info.fixed_range() {
659 if !range.is_within(memory) {
660 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
661 return Err(RebootReason::InvalidFdt);
662 }
663 }
664
Jiyong Park6a8789a2023-03-21 14:50:59 +0900665 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000666}
667
Jiyong Park9c63cd12023-03-21 17:53:07 +0900668fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
669 let mut node =
670 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700671
672 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000673 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700674 cstr!("reg"),
675 range.start.try_into().unwrap(),
676 range.len().try_into().unwrap(),
677 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000678 node.nop_property(cstr!("size"))?;
679 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700680 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000681 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700682 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000683 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700684 }
685
Jiyong Park9c63cd12023-03-21 17:53:07 +0900686 Ok(())
687}
688
689fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
690 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
691 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
692 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
693 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
694
695 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000696 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
697 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000698 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900699
700 // range1 is just below range0
701 range1.addr = addr - size;
702 range1.size = Some(size);
703
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000704 let (addr0, size0) = range0.to_cells();
705 let (addr1, size1) = range1.to_cells();
706 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900707
708 let mut node =
709 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
710 node.setprop_inplace(cstr!("reg"), flatten(&value))
711}
712
713fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
714 const NUM_INTERRUPTS: usize = 4;
715 const CELLS_PER_INTERRUPT: usize = 3;
716 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
717 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
718 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
719 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
720
721 let num_cpus: u32 = num_cpus.try_into().unwrap();
722 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
723 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
724 *v |= cpu_mask;
725 }
726 for v in value.iter_mut() {
727 *v = v.to_be();
728 }
729
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000730 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900731
732 let mut node =
733 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000734 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900735}
736
Jiyong Park00ceff32023-03-13 05:43:23 +0000737#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800738struct VcpufreqInfo {
739 addr: u64,
740 size: u64,
741}
742
743fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
744 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
745 if let Some(info) = vcpufreq_info {
746 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
747 } else {
748 node.nop()
749 }
750}
751
752#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753pub struct DeviceTreeInfo {
754 pub kernel_range: Option<Range<usize>>,
755 pub initrd_range: Option<Range<usize>>,
756 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900757 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000758 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000759 pci_info: PciInfo,
760 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700761 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900762 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900763 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800764 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000765}
766
767impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000768 const MAX_CPUS: usize = 16;
769
770 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000771 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
772
773 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
774 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000775}
776
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900777pub fn sanitize_device_tree(
778 fdt: &mut [u8],
779 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900780 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900781) -> Result<DeviceTreeInfo, RebootReason> {
782 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
783 error!("Failed to load FDT: {e}");
784 RebootReason::InvalidFdt
785 })?;
786
787 let vm_dtbo = match vm_dtbo {
788 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
789 error!("Failed to load VM DTBO: {e}");
790 RebootReason::InvalidFdt
791 })?),
792 None => None,
793 };
794
795 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900796
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000797 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
798 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
799 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900800 error!("Failed to instantiate FDT from the template DT: {e}");
801 RebootReason::InvalidFdt
802 })?;
803
Jaewan Kim9220e852023-12-01 10:58:40 +0900804 fdt.unpack().map_err(|e| {
805 error!("Failed to unpack DT for patching: {e}");
806 RebootReason::InvalidFdt
807 })?;
808
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900809 if let Some(device_assignment_info) = &info.device_assignment {
810 let vm_dtbo = vm_dtbo.unwrap();
811 device_assignment_info.filter(vm_dtbo).map_err(|e| {
812 error!("Failed to filter VM DTBO: {e}");
813 RebootReason::InvalidFdt
814 })?;
815 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
816 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
817 // it can only be instantiated after validation.
818 unsafe {
819 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
820 error!("Failed to apply filtered VM DTBO: {e}");
821 RebootReason::InvalidFdt
822 })?;
823 }
824 }
825
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900826 if let Some(vm_ref_dt) = vm_ref_dt {
827 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
828 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900829 RebootReason::InvalidFdt
830 })?;
831
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900832 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
833 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900834 RebootReason::InvalidFdt
835 })?;
836 }
837
Jiyong Park9c63cd12023-03-21 17:53:07 +0900838 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900839
Jaewan Kim19b984f2023-12-04 15:16:50 +0900840 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
841
Jaewan Kim9220e852023-12-01 10:58:40 +0900842 fdt.pack().map_err(|e| {
843 error!("Failed to unpack DT after patching: {e}");
844 RebootReason::InvalidFdt
845 })?;
846
Jiyong Park6a8789a2023-03-21 14:50:59 +0900847 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900848}
849
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900850fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900851 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
852 error!("Failed to read kernel range from DT: {e}");
853 RebootReason::InvalidFdt
854 })?;
855
856 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
857 error!("Failed to read initrd range from DT: {e}");
858 RebootReason::InvalidFdt
859 })?;
860
Alice Wang0d527472023-06-13 14:55:38 +0000861 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900862
Jiyong Parke9d87e82023-03-21 19:28:40 +0900863 let bootargs = read_bootargs_from(fdt).map_err(|e| {
864 error!("Failed to read bootargs from DT: {e}");
865 RebootReason::InvalidFdt
866 })?;
867
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000868 let cpus = read_cpu_info_from(fdt).map_err(|e| {
869 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900870 RebootReason::InvalidFdt
871 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000872 validate_cpu_info(&cpus).map_err(|e| {
873 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +0000874 RebootReason::InvalidFdt
875 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900876
David Dai9bdb10c2024-02-01 22:42:54 -0800877 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
878 error!("Failed to read vcpufreq info from DT: {e}");
879 RebootReason::InvalidFdt
880 })?;
881 if let Some(ref info) = vcpufreq_info {
882 validate_vcpufreq_info(info, &cpus).map_err(|e| {
883 error!("Failed to validate vcpufreq info from DT: {e}");
884 RebootReason::InvalidFdt
885 })?;
886 }
887
Jiyong Park6a8789a2023-03-21 14:50:59 +0900888 let pci_info = read_pci_info_from(fdt).map_err(|e| {
889 error!("Failed to read pci info from DT: {e}");
890 RebootReason::InvalidFdt
891 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900892 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900893
894 let serial_info = read_serial_info_from(fdt).map_err(|e| {
895 error!("Failed to read serial info from DT: {e}");
896 RebootReason::InvalidFdt
897 })?;
898
Alice Wang9cfbfd62023-06-14 11:19:03 +0000899 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900900 error!("Failed to read swiotlb info from DT: {e}");
901 RebootReason::InvalidFdt
902 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700903 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900904
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900905 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900906 Some(vm_dtbo) => {
907 if let Some(hypervisor) = hyp::get_device_assigner() {
908 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
909 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
910 RebootReason::InvalidFdt
911 })?
912 } else {
913 warn!(
914 "Device assignment is ignored because device assigning hypervisor is missing"
915 );
916 None
917 }
918 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900919 None => None,
920 };
921
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900922 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900923 error!("Failed to read names of properties under /avf from DT: {e}");
924 RebootReason::InvalidFdt
925 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900926
Jiyong Park00ceff32023-03-13 05:43:23 +0000927 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900928 kernel_range,
929 initrd_range,
930 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900931 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000932 cpus,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900933 pci_info,
934 serial_info,
935 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900936 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900937 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -0800938 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000939 })
940}
941
Jiyong Park9c63cd12023-03-21 17:53:07 +0900942fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
943 if let Some(initrd_range) = &info.initrd_range {
944 patch_initrd_range(fdt, initrd_range).map_err(|e| {
945 error!("Failed to patch initrd range to DT: {e}");
946 RebootReason::InvalidFdt
947 })?;
948 }
949 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
950 error!("Failed to patch memory range to DT: {e}");
951 RebootReason::InvalidFdt
952 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900953 if let Some(bootargs) = &info.bootargs {
954 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
955 error!("Failed to patch bootargs to DT: {e}");
956 RebootReason::InvalidFdt
957 })?;
958 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000959 patch_cpus(fdt, &info.cpus).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900960 error!("Failed to patch cpus to DT: {e}");
961 RebootReason::InvalidFdt
962 })?;
David Dai9bdb10c2024-02-01 22:42:54 -0800963 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
964 error!("Failed to patch vcpufreq info to DT: {e}");
965 RebootReason::InvalidFdt
966 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900967 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
968 error!("Failed to patch pci info to DT: {e}");
969 RebootReason::InvalidFdt
970 })?;
971 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
972 error!("Failed to patch serial info to DT: {e}");
973 RebootReason::InvalidFdt
974 })?;
975 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
976 error!("Failed to patch swiotlb info to DT: {e}");
977 RebootReason::InvalidFdt
978 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000979 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900980 error!("Failed to patch gic info to DT: {e}");
981 RebootReason::InvalidFdt
982 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000983 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900984 error!("Failed to patch timer info to DT: {e}");
985 RebootReason::InvalidFdt
986 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900987 if let Some(device_assignment) = &info.device_assignment {
988 // Note: We patch values after VM DTBO is overlaid because patch may require more space
989 // then VM DTBO's underlying slice is allocated.
990 device_assignment.patch(fdt).map_err(|e| {
991 error!("Failed to patch device assignment info to DT: {e}");
992 RebootReason::InvalidFdt
993 })?;
994 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900995
Jiyong Park9c63cd12023-03-21 17:53:07 +0900996 Ok(())
997}
998
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000999/// Modifies the input DT according to the fields of the configuration.
1000pub fn modify_for_next_stage(
1001 fdt: &mut Fdt,
1002 bcc: &[u8],
1003 new_instance: bool,
1004 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001005 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001006 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001007 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001008) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001009 if let Some(debug_policy) = debug_policy {
1010 let backup = Vec::from(fdt.as_slice());
1011 fdt.unpack()?;
1012 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1013 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1014 info!("Debug policy applied.");
1015 } else {
1016 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1017 fdt.unpack()?;
1018 }
1019 } else {
1020 info!("No debug policy found.");
1021 fdt.unpack()?;
1022 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001023
Jiyong Parke9d87e82023-03-21 19:28:40 +09001024 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001025
Alice Wang56ec45b2023-06-15 08:30:32 +00001026 if let Some(mut chosen) = fdt.chosen_mut()? {
1027 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1028 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001029 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001030 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001031 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001032 if let Some(bootargs) = read_bootargs_from(fdt)? {
1033 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1034 }
1035 }
1036
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001037 fdt.pack()?;
1038
1039 Ok(())
1040}
1041
Jiyong Parke9d87e82023-03-21 19:28:40 +09001042/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1043fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001044 // We reject DTs with missing reserved-memory node as validation should have checked that the
1045 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001046 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001047
Jiyong Parke9d87e82023-03-21 19:28:40 +09001048 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001049
Jiyong Parke9d87e82023-03-21 19:28:40 +09001050 let addr: u64 = addr.try_into().unwrap();
1051 let size: u64 = size.try_into().unwrap();
1052 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001053}
1054
Alice Wang56ec45b2023-06-15 08:30:32 +00001055fn empty_or_delete_prop(
1056 fdt_node: &mut FdtNodeMut,
1057 prop_name: &CStr,
1058 keep_prop: bool,
1059) -> libfdt::Result<()> {
1060 if keep_prop {
1061 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001062 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001063 fdt_node
1064 .delprop(prop_name)
1065 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001066 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001067}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001068
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001069/// Apply the debug policy overlay to the guest DT.
1070///
1071/// 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 +00001072fn apply_debug_policy(
1073 fdt: &mut Fdt,
1074 backup_fdt: &Fdt,
1075 debug_policy: &[u8],
1076) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001077 let mut debug_policy = Vec::from(debug_policy);
1078 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001079 Ok(overlay) => overlay,
1080 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001081 warn!("Corrupted debug policy found: {e}. Not applying.");
1082 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001083 }
1084 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001085
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001086 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001087 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001088 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001089 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001090 // A successful restoration is considered success because an invalid debug policy
1091 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001092 Ok(false)
1093 } else {
1094 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001095 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001096}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001097
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001098fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001099 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1100 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1101 return Ok(value == 1);
1102 }
1103 }
1104 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1105}
1106
1107fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001108 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1109 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001110
1111 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1112 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1113 ("crashkernel", Box::new(|_| has_crashkernel)),
1114 ("console", Box::new(|_| has_console)),
1115 ];
1116
1117 // parse and filter out unwanted
1118 let mut filtered = Vec::new();
1119 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1120 info!("Invalid bootarg: {e}");
1121 FdtError::BadValue
1122 })? {
1123 match accepted.iter().find(|&t| t.0 == arg.name()) {
1124 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1125 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1126 }
1127 }
1128
1129 // flatten into a new C-string
1130 let mut new_bootargs = Vec::new();
1131 for (i, arg) in filtered.iter().enumerate() {
1132 if i != 0 {
1133 new_bootargs.push(b' '); // separator
1134 }
1135 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1136 }
1137 new_bootargs.push(b'\0');
1138
1139 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1140 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1141}