blob: ba0a99216dbf22df835ffce242c17f20232bdcaa [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
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000181#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800182struct CpuInfo {
183 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800184 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800185}
186
187impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800188 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800189}
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()) {
David Dai50168a32024-02-14 17:00:48 -0800207 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800208 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
209 let opptable_info = if let Some(phandle) = opp_phandle {
210 let phandle = phandle.try_into()?;
211 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
212 Some(read_opp_info_from(node)?)
213 } else {
214 None
215 };
David Dai50168a32024-02-14 17:00:48 -0800216 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000217 cpus.push(info);
Jiyong Park6a8789a2023-03-21 14:50:59 +0900218 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000219 if cpu_nodes.next().is_some() {
220 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
221 }
222
223 Ok(cpus)
Jiyong Park9c63cd12023-03-21 17:53:07 +0900224}
225
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000226fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
227 if cpus.is_empty() {
228 return Err(FdtValidationError::InvalidCpuCount(0));
229 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000230 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,
David Dai622c05d2024-02-14 14:03:26 -0800270 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
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() {
David Dai50168a32024-02-14 17:00:48 -0800310 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
311 if let Some(cpu_capacity) = cpu.cpu_capacity {
312 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
313 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000314 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900315 }
David Dai9bdb10c2024-02-01 22:42:54 -0800316 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900317 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000318 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900319 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900320 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000321}
322
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900323/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900324fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900325 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900326 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900327 for property in avf_node.properties()? {
328 let name = property.name()?;
329 let value = property.value()?;
330 property_map.insert(
331 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
332 value.to_vec(),
333 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900334 }
335 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900336 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900337}
338
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900339/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
340/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
341fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900342 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900343 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900344 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900345) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900346 let mut root_vm_dt = vm_dt.root_mut()?;
347 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900348 // TODO(b/318431677): Validate nodes beyond /avf.
349 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900350 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900351 if let Some(ref_value) = avf_node.getprop(name)? {
352 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900353 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900354 "Property mismatches while applying overlay VM reference DT. \
355 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
356 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900357 );
358 return Err(FdtError::BadValue);
359 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900360 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900361 }
362 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900363 Ok(())
364}
365
Jiyong Park00ceff32023-03-13 05:43:23 +0000366#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000367struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900368 ranges: [PciAddrRange; 2],
369 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
370 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000371}
372
Jiyong Park6a8789a2023-03-21 14:50:59 +0900373impl PciInfo {
374 const IRQ_MASK_CELLS: usize = 4;
375 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100376 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000377}
378
Jiyong Park6a8789a2023-03-21 14:50:59 +0900379type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
380type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
381type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000382
383/// Iterator that takes N cells as a chunk
384struct CellChunkIterator<'a, const N: usize> {
385 cells: CellIterator<'a>,
386}
387
388impl<'a, const N: usize> CellChunkIterator<'a, N> {
389 fn new(cells: CellIterator<'a>) -> Self {
390 Self { cells }
391 }
392}
393
394impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
395 type Item = [u32; N];
396 fn next(&mut self) -> Option<Self::Item> {
397 let mut ret: Self::Item = [0; N];
398 for i in ret.iter_mut() {
399 *i = self.cells.next()?;
400 }
401 Some(ret)
402 }
403}
404
Jiyong Park6a8789a2023-03-21 14:50:59 +0900405/// Read pci host controller ranges, irq maps, and irq map masks from DT
406fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
407 let node =
408 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
409
410 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
411 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
412 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
413
414 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000415 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
416 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
417
418 if chunks.next().is_some() {
419 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
420 return Err(FdtError::NoSpace);
421 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900422
423 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000424 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
425 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
426
427 if chunks.next().is_some() {
428 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
429 return Err(FdtError::NoSpace);
430 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900431
432 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
433}
434
Jiyong Park0ee65392023-03-27 20:52:45 +0900435fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900436 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900437 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900438 }
439 for irq_mask in pci_info.irq_masks.iter() {
440 validate_pci_irq_mask(irq_mask)?;
441 }
442 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
443 validate_pci_irq_map(irq_map, idx)?;
444 }
445 Ok(())
446}
447
Jiyong Park0ee65392023-03-27 20:52:45 +0900448fn validate_pci_addr_range(
449 range: &PciAddrRange,
450 memory_range: &Range<usize>,
451) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900452 let mem_flags = PciMemoryFlags(range.addr.0);
453 let range_type = mem_flags.range_type();
454 let prefetchable = mem_flags.prefetchable();
455 let bus_addr = range.addr.1;
456 let cpu_addr = range.parent_addr;
457 let size = range.size;
458
459 if range_type != PciRangeType::Memory64 {
460 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
461 return Err(RebootReason::InvalidFdt);
462 }
463 if prefetchable {
464 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
465 return Err(RebootReason::InvalidFdt);
466 }
467 // Enforce ID bus-to-cpu mappings, as used by crosvm.
468 if bus_addr != cpu_addr {
469 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
470 return Err(RebootReason::InvalidFdt);
471 }
472
Jiyong Park0ee65392023-03-27 20:52:45 +0900473 let Some(bus_end) = bus_addr.checked_add(size) else {
474 error!("PCI address range size {:#x} overflows", size);
475 return Err(RebootReason::InvalidFdt);
476 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000477 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900478 error!("PCI address end {:#x} is outside of translatable range", bus_end);
479 return Err(RebootReason::InvalidFdt);
480 }
481
482 let memory_start = memory_range.start.try_into().unwrap();
483 let memory_end = memory_range.end.try_into().unwrap();
484
485 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
486 error!(
487 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
488 bus_addr, bus_end, memory_start, memory_end
489 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900490 return Err(RebootReason::InvalidFdt);
491 }
492
493 Ok(())
494}
495
496fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000497 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
498 const IRQ_MASK_ADDR_ME: u32 = 0x0;
499 const IRQ_MASK_ADDR_LO: u32 = 0x0;
500 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900501 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000502 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900503 if *irq_mask != EXPECTED {
504 error!("Invalid PCI irq mask {:#?}", irq_mask);
505 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000506 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900507 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000508}
509
Jiyong Park6a8789a2023-03-21 14:50:59 +0900510fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000511 const PCI_DEVICE_IDX: usize = 11;
512 const PCI_IRQ_ADDR_ME: u32 = 0;
513 const PCI_IRQ_ADDR_LO: u32 = 0;
514 const PCI_IRQ_INTC: u32 = 1;
515 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
516 const GIC_SPI: u32 = 0;
517 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
518
Jiyong Park6a8789a2023-03-21 14:50:59 +0900519 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
520 let pci_irq_number = irq_map[3];
521 let _controller_phandle = irq_map[4]; // skipped.
522 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
523 // interrupt-cells is <3> for GIC
524 let gic_peripheral_interrupt_type = irq_map[7];
525 let gic_irq_number = irq_map[8];
526 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000527
Jiyong Park6a8789a2023-03-21 14:50:59 +0900528 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
529 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000530
Jiyong Park6a8789a2023-03-21 14:50:59 +0900531 if pci_addr != expected_pci_addr {
532 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
533 {:#x} {:#x} {:#x}",
534 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
535 return Err(RebootReason::InvalidFdt);
536 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000537
Jiyong Park6a8789a2023-03-21 14:50:59 +0900538 if pci_irq_number != PCI_IRQ_INTC {
539 error!(
540 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
541 pci_irq_number, PCI_IRQ_INTC
542 );
543 return Err(RebootReason::InvalidFdt);
544 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000545
Jiyong Park6a8789a2023-03-21 14:50:59 +0900546 if gic_addr != (0, 0) {
547 error!(
548 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
549 {:#x} {:#x}",
550 gic_addr.0, gic_addr.1, 0, 0
551 );
552 return Err(RebootReason::InvalidFdt);
553 }
554
555 if gic_peripheral_interrupt_type != GIC_SPI {
556 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
557 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
558 return Err(RebootReason::InvalidFdt);
559 }
560
561 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
562 if gic_irq_number != irq_nr {
563 error!(
564 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
565 gic_irq_number, irq_nr
566 );
567 return Err(RebootReason::InvalidFdt);
568 }
569
570 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
571 error!(
572 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
573 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
574 );
575 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000576 }
577 Ok(())
578}
579
Jiyong Park9c63cd12023-03-21 17:53:07 +0900580fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
581 let mut node = fdt
582 .root_mut()?
583 .next_compatible(cstr!("pci-host-cam-generic"))?
584 .ok_or(FdtError::NotFound)?;
585
586 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
587 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
588
589 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
590 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
591
592 node.setprop_inplace(
593 cstr!("ranges"),
594 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
595 )
596}
597
Jiyong Park00ceff32023-03-13 05:43:23 +0000598#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900599struct SerialInfo {
600 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000601}
602
603impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000605}
606
Jiyong Park6a8789a2023-03-21 14:50:59 +0900607fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000608 let mut addrs = ArrayVec::new();
609
610 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
611 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000612 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900613 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000614 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000615 if serial_nodes.next().is_some() {
616 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
617 }
618
Jiyong Park6a8789a2023-03-21 14:50:59 +0900619 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000620}
621
Jiyong Park9c63cd12023-03-21 17:53:07 +0900622/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
623fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
624 let name = cstr!("ns16550a");
625 let mut next = fdt.root_mut()?.next_compatible(name);
626 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000627 let reg =
628 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900629 next = if !serial_info.addrs.contains(&reg.addr) {
630 current.delete_and_next_compatible(name)
631 } else {
632 current.next_compatible(name)
633 }
634 }
635 Ok(())
636}
637
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700638fn validate_swiotlb_info(
639 swiotlb_info: &SwiotlbInfo,
640 memory: &Range<usize>,
641) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900642 let size = swiotlb_info.size;
643 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000644
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700645 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000646 error!("Invalid swiotlb size {:#x}", size);
647 return Err(RebootReason::InvalidFdt);
648 }
649
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000650 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000651 error!("Invalid swiotlb alignment {:#x}", align);
652 return Err(RebootReason::InvalidFdt);
653 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700654
Alice Wang9cfbfd62023-06-14 11:19:03 +0000655 if let Some(addr) = swiotlb_info.addr {
656 if addr.checked_add(size).is_none() {
657 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
658 return Err(RebootReason::InvalidFdt);
659 }
660 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700661 if let Some(range) = swiotlb_info.fixed_range() {
662 if !range.is_within(memory) {
663 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
664 return Err(RebootReason::InvalidFdt);
665 }
666 }
667
Jiyong Park6a8789a2023-03-21 14:50:59 +0900668 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000669}
670
Jiyong Park9c63cd12023-03-21 17:53:07 +0900671fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
672 let mut node =
673 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700674
675 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000676 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700677 cstr!("reg"),
678 range.start.try_into().unwrap(),
679 range.len().try_into().unwrap(),
680 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000681 node.nop_property(cstr!("size"))?;
682 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700683 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000684 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700685 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000686 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700687 }
688
Jiyong Park9c63cd12023-03-21 17:53:07 +0900689 Ok(())
690}
691
692fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
693 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
694 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
695 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
696 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
697
698 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000699 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
700 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000701 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900702
703 // range1 is just below range0
704 range1.addr = addr - size;
705 range1.size = Some(size);
706
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000707 let (addr0, size0) = range0.to_cells();
708 let (addr1, size1) = range1.to_cells();
709 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900710
711 let mut node =
712 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
713 node.setprop_inplace(cstr!("reg"), flatten(&value))
714}
715
716fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
717 const NUM_INTERRUPTS: usize = 4;
718 const CELLS_PER_INTERRUPT: usize = 3;
719 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
720 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
721 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
722 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
723
724 let num_cpus: u32 = num_cpus.try_into().unwrap();
725 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
726 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
727 *v |= cpu_mask;
728 }
729 for v in value.iter_mut() {
730 *v = v.to_be();
731 }
732
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000733 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900734
735 let mut node =
736 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000737 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900738}
739
Jiyong Park00ceff32023-03-13 05:43:23 +0000740#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800741struct VcpufreqInfo {
742 addr: u64,
743 size: u64,
744}
745
746fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
747 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
748 if let Some(info) = vcpufreq_info {
749 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
750 } else {
751 node.nop()
752 }
753}
754
755#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900756pub struct DeviceTreeInfo {
757 pub kernel_range: Option<Range<usize>>,
758 pub initrd_range: Option<Range<usize>>,
759 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900760 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000761 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000762 pci_info: PciInfo,
763 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700764 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900765 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900766 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800767 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000768}
769
770impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000771 const MAX_CPUS: usize = 16;
772
773 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000774 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
775
776 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
777 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000778}
779
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900780pub fn sanitize_device_tree(
781 fdt: &mut [u8],
782 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900783 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900784) -> Result<DeviceTreeInfo, RebootReason> {
785 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
786 error!("Failed to load FDT: {e}");
787 RebootReason::InvalidFdt
788 })?;
789
790 let vm_dtbo = match vm_dtbo {
791 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
792 error!("Failed to load VM DTBO: {e}");
793 RebootReason::InvalidFdt
794 })?),
795 None => None,
796 };
797
798 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900799
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000800 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
801 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
802 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900803 error!("Failed to instantiate FDT from the template DT: {e}");
804 RebootReason::InvalidFdt
805 })?;
806
Jaewan Kim9220e852023-12-01 10:58:40 +0900807 fdt.unpack().map_err(|e| {
808 error!("Failed to unpack DT for patching: {e}");
809 RebootReason::InvalidFdt
810 })?;
811
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900812 if let Some(device_assignment_info) = &info.device_assignment {
813 let vm_dtbo = vm_dtbo.unwrap();
814 device_assignment_info.filter(vm_dtbo).map_err(|e| {
815 error!("Failed to filter VM DTBO: {e}");
816 RebootReason::InvalidFdt
817 })?;
818 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
819 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
820 // it can only be instantiated after validation.
821 unsafe {
822 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
823 error!("Failed to apply filtered VM DTBO: {e}");
824 RebootReason::InvalidFdt
825 })?;
826 }
827 }
828
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900829 if let Some(vm_ref_dt) = vm_ref_dt {
830 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
831 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900832 RebootReason::InvalidFdt
833 })?;
834
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900835 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
836 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900837 RebootReason::InvalidFdt
838 })?;
839 }
840
Jiyong Park9c63cd12023-03-21 17:53:07 +0900841 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900842
Jaewan Kim19b984f2023-12-04 15:16:50 +0900843 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
844
Jaewan Kim9220e852023-12-01 10:58:40 +0900845 fdt.pack().map_err(|e| {
846 error!("Failed to unpack DT after patching: {e}");
847 RebootReason::InvalidFdt
848 })?;
849
Jiyong Park6a8789a2023-03-21 14:50:59 +0900850 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900851}
852
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900853fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900854 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
855 error!("Failed to read kernel range from DT: {e}");
856 RebootReason::InvalidFdt
857 })?;
858
859 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
860 error!("Failed to read initrd range from DT: {e}");
861 RebootReason::InvalidFdt
862 })?;
863
Alice Wang0d527472023-06-13 14:55:38 +0000864 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900865
Jiyong Parke9d87e82023-03-21 19:28:40 +0900866 let bootargs = read_bootargs_from(fdt).map_err(|e| {
867 error!("Failed to read bootargs from DT: {e}");
868 RebootReason::InvalidFdt
869 })?;
870
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000871 let cpus = read_cpu_info_from(fdt).map_err(|e| {
872 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900873 RebootReason::InvalidFdt
874 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000875 validate_cpu_info(&cpus).map_err(|e| {
876 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +0000877 RebootReason::InvalidFdt
878 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900879
David Dai9bdb10c2024-02-01 22:42:54 -0800880 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
881 error!("Failed to read vcpufreq info from DT: {e}");
882 RebootReason::InvalidFdt
883 })?;
884 if let Some(ref info) = vcpufreq_info {
885 validate_vcpufreq_info(info, &cpus).map_err(|e| {
886 error!("Failed to validate vcpufreq info from DT: {e}");
887 RebootReason::InvalidFdt
888 })?;
889 }
890
Jiyong Park6a8789a2023-03-21 14:50:59 +0900891 let pci_info = read_pci_info_from(fdt).map_err(|e| {
892 error!("Failed to read pci info from DT: {e}");
893 RebootReason::InvalidFdt
894 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900895 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900896
897 let serial_info = read_serial_info_from(fdt).map_err(|e| {
898 error!("Failed to read serial info from DT: {e}");
899 RebootReason::InvalidFdt
900 })?;
901
Alice Wang9cfbfd62023-06-14 11:19:03 +0000902 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900903 error!("Failed to read swiotlb info from DT: {e}");
904 RebootReason::InvalidFdt
905 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700906 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900907
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900908 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900909 Some(vm_dtbo) => {
910 if let Some(hypervisor) = hyp::get_device_assigner() {
911 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
912 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
913 RebootReason::InvalidFdt
914 })?
915 } else {
916 warn!(
917 "Device assignment is ignored because device assigning hypervisor is missing"
918 );
919 None
920 }
921 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900922 None => None,
923 };
924
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900925 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900926 error!("Failed to read names of properties under /avf from DT: {e}");
927 RebootReason::InvalidFdt
928 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900929
Jiyong Park00ceff32023-03-13 05:43:23 +0000930 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900931 kernel_range,
932 initrd_range,
933 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900934 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000935 cpus,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900936 pci_info,
937 serial_info,
938 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900939 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900940 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -0800941 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000942 })
943}
944
Jiyong Park9c63cd12023-03-21 17:53:07 +0900945fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
946 if let Some(initrd_range) = &info.initrd_range {
947 patch_initrd_range(fdt, initrd_range).map_err(|e| {
948 error!("Failed to patch initrd range to DT: {e}");
949 RebootReason::InvalidFdt
950 })?;
951 }
952 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
953 error!("Failed to patch memory range to DT: {e}");
954 RebootReason::InvalidFdt
955 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900956 if let Some(bootargs) = &info.bootargs {
957 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
958 error!("Failed to patch bootargs to DT: {e}");
959 RebootReason::InvalidFdt
960 })?;
961 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000962 patch_cpus(fdt, &info.cpus).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900963 error!("Failed to patch cpus to DT: {e}");
964 RebootReason::InvalidFdt
965 })?;
David Dai9bdb10c2024-02-01 22:42:54 -0800966 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
967 error!("Failed to patch vcpufreq info to DT: {e}");
968 RebootReason::InvalidFdt
969 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900970 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
971 error!("Failed to patch pci info to DT: {e}");
972 RebootReason::InvalidFdt
973 })?;
974 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
975 error!("Failed to patch serial info to DT: {e}");
976 RebootReason::InvalidFdt
977 })?;
978 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
979 error!("Failed to patch swiotlb info to DT: {e}");
980 RebootReason::InvalidFdt
981 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000982 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900983 error!("Failed to patch gic info to DT: {e}");
984 RebootReason::InvalidFdt
985 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000986 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900987 error!("Failed to patch timer info to DT: {e}");
988 RebootReason::InvalidFdt
989 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900990 if let Some(device_assignment) = &info.device_assignment {
991 // Note: We patch values after VM DTBO is overlaid because patch may require more space
992 // then VM DTBO's underlying slice is allocated.
993 device_assignment.patch(fdt).map_err(|e| {
994 error!("Failed to patch device assignment info to DT: {e}");
995 RebootReason::InvalidFdt
996 })?;
997 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900998
Jiyong Park9c63cd12023-03-21 17:53:07 +0900999 Ok(())
1000}
1001
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001002/// Modifies the input DT according to the fields of the configuration.
1003pub fn modify_for_next_stage(
1004 fdt: &mut Fdt,
1005 bcc: &[u8],
1006 new_instance: bool,
1007 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001008 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001009 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001010 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001011) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001012 if let Some(debug_policy) = debug_policy {
1013 let backup = Vec::from(fdt.as_slice());
1014 fdt.unpack()?;
1015 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1016 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1017 info!("Debug policy applied.");
1018 } else {
1019 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1020 fdt.unpack()?;
1021 }
1022 } else {
1023 info!("No debug policy found.");
1024 fdt.unpack()?;
1025 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001026
Jiyong Parke9d87e82023-03-21 19:28:40 +09001027 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001028
Alice Wang56ec45b2023-06-15 08:30:32 +00001029 if let Some(mut chosen) = fdt.chosen_mut()? {
1030 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1031 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001032 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001033 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001034 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001035 if let Some(bootargs) = read_bootargs_from(fdt)? {
1036 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1037 }
1038 }
1039
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001040 fdt.pack()?;
1041
1042 Ok(())
1043}
1044
Jiyong Parke9d87e82023-03-21 19:28:40 +09001045/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1046fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001047 // We reject DTs with missing reserved-memory node as validation should have checked that the
1048 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001049 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001050
Jiyong Parke9d87e82023-03-21 19:28:40 +09001051 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001052
Jiyong Parke9d87e82023-03-21 19:28:40 +09001053 let addr: u64 = addr.try_into().unwrap();
1054 let size: u64 = size.try_into().unwrap();
1055 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001056}
1057
Alice Wang56ec45b2023-06-15 08:30:32 +00001058fn empty_or_delete_prop(
1059 fdt_node: &mut FdtNodeMut,
1060 prop_name: &CStr,
1061 keep_prop: bool,
1062) -> libfdt::Result<()> {
1063 if keep_prop {
1064 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001065 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001066 fdt_node
1067 .delprop(prop_name)
1068 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001069 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001070}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001071
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001072/// Apply the debug policy overlay to the guest DT.
1073///
1074/// 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 +00001075fn apply_debug_policy(
1076 fdt: &mut Fdt,
1077 backup_fdt: &Fdt,
1078 debug_policy: &[u8],
1079) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001080 let mut debug_policy = Vec::from(debug_policy);
1081 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001082 Ok(overlay) => overlay,
1083 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001084 warn!("Corrupted debug policy found: {e}. Not applying.");
1085 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001086 }
1087 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001088
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001089 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001090 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001091 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001092 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001093 // A successful restoration is considered success because an invalid debug policy
1094 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001095 Ok(false)
1096 } else {
1097 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001098 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001099}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001100
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001101fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001102 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1103 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1104 return Ok(value == 1);
1105 }
1106 }
1107 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1108}
1109
1110fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001111 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1112 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001113
1114 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1115 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1116 ("crashkernel", Box::new(|_| has_crashkernel)),
1117 ("console", Box::new(|_| has_console)),
1118 ];
1119
1120 // parse and filter out unwanted
1121 let mut filtered = Vec::new();
1122 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1123 info!("Invalid bootarg: {e}");
1124 FdtError::BadValue
1125 })? {
1126 match accepted.iter().find(|&t| t.0 == arg.name()) {
1127 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1128 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1129 }
1130 }
1131
1132 // flatten into a new C-string
1133 let mut new_bootargs = Vec::new();
1134 for (i, arg) in filtered.iter().enumerate() {
1135 if i != 0 {
1136 new_bootargs.push(b' '); // separator
1137 }
1138 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1139 }
1140 new_bootargs.push(b'\0');
1141
1142 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1143 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1144}