blob: 9dca8af887bf6cb7ef3a318b8c2a9071183608b3 [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 Kim50246682024-03-11 23:18:54 +090018use crate::device_assignment::{self, 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;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000024use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090025use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090026use core::cmp::max;
27use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000029use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090030use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use fdtpci::PciMemoryFlags;
34use fdtpci::PciRangeType;
35use libfdt::AddressRange;
36use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000037use libfdt::Fdt;
38use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080039use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000040use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000041use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090042use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090044use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000045use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000046use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000047use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000048use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000049use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000050use vmbase::memory::SIZE_4KB;
51use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000052use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000053use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054
Alice Wangabc7d632023-06-14 09:10:14 +000055/// An enumeration of errors that can occur during the FDT validation.
56#[derive(Clone, Debug)]
57pub enum FdtValidationError {
58 /// Invalid CPU count.
59 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080060 /// Invalid VCpufreq Range.
61 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000062 /// Forbidden /avf/untrusted property.
63 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000064}
65
66impl fmt::Display for FdtValidationError {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 match self {
69 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000070 Self::InvalidVcpufreq(addr, size) => {
71 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
72 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000073 Self::ForbiddenUntrustedProp(name) => {
74 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
75 }
Alice Wangabc7d632023-06-14 09:10:14 +000076 }
77 }
78}
79
Jiyong Park6a8789a2023-03-21 14:50:59 +090080/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
81/// not an error.
82fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090083 let addr = cstr!("kernel-address");
84 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000085
Jiyong Parkb87f3302023-03-21 10:03:11 +090086 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000087 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
88 let addr = addr as usize;
89 let size = size as usize;
90
91 return Ok(Some(addr..(addr + size)));
92 }
93 }
94
95 Ok(None)
96}
97
Jiyong Park6a8789a2023-03-21 14:50:59 +090098/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
99/// error as there can be initrd-less VM.
100fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +0900101 let start = cstr!("linux,initrd-start");
102 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000103
104 if let Some(chosen) = fdt.chosen()? {
105 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
106 return Ok(Some((start as usize)..(end as usize)));
107 }
108 }
109
110 Ok(None)
111}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000112
Jiyong Park9c63cd12023-03-21 17:53:07 +0900113fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
114 let start = u32::try_from(initrd_range.start).unwrap();
115 let end = u32::try_from(initrd_range.end).unwrap();
116
117 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
118 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
119 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
120 Ok(())
121}
122
Jiyong Parke9d87e82023-03-21 19:28:40 +0900123fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
124 if let Some(chosen) = fdt.chosen()? {
125 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
126 // We need to copy the string to heap because the original fdt will be invalidated
127 // by the templated DT
128 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
129 return Ok(Some(copy));
130 }
131 }
132 Ok(None)
133}
134
135fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
136 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900137 // This function is called before the verification is done. So, we just copy the bootargs to
138 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
139 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900140 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
141}
142
Alice Wang0d527472023-06-13 14:55:38 +0000143/// Reads and validates the memory range in the DT.
144///
145/// Only one memory range is expected with the crosvm setup for now.
146fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
147 let mut memory = fdt.memory().map_err(|e| {
148 error!("Failed to read memory range from DT: {e}");
149 RebootReason::InvalidFdt
150 })?;
151 let range = memory.next().ok_or_else(|| {
152 error!("The /memory node in the DT contains no range.");
153 RebootReason::InvalidFdt
154 })?;
155 if memory.next().is_some() {
156 warn!(
157 "The /memory node in the DT contains more than one memory range, \
158 while only one is expected."
159 );
160 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900161 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000162 if base != MEM_START {
163 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000164 return Err(RebootReason::InvalidFdt);
165 }
166
Jiyong Park6a8789a2023-03-21 14:50:59 +0900167 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000168 if size % GUEST_PAGE_SIZE != 0 {
169 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
170 return Err(RebootReason::InvalidFdt);
171 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000172
Jiyong Park6a8789a2023-03-21 14:50:59 +0900173 if size == 0 {
174 error!("Memory size is 0");
175 return Err(RebootReason::InvalidFdt);
176 }
Alice Wang0d527472023-06-13 14:55:38 +0000177 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000178}
179
Jiyong Park9c63cd12023-03-21 17:53:07 +0900180fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000181 let addr = u64::try_from(MEM_START).unwrap();
182 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900183 fdt.node_mut(cstr!("/memory"))?
184 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000185 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900186}
187
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000188#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800189struct CpuInfo {
190 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800191 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800192}
193
194impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800195 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800196}
197
198fn read_opp_info_from(
199 opp_node: FdtNode,
200) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
201 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100202 let mut opp_nodes = opp_node.subnodes()?;
203 for subnode in opp_nodes.by_ref().take(table.capacity()) {
David Dai9bdb10c2024-02-01 22:42:54 -0800204 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
205 table.push(prop);
206 }
207
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100208 if opp_nodes.next().is_some() {
209 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
210 }
211
David Dai9bdb10c2024-02-01 22:42:54 -0800212 Ok(table)
213}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900214
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000215#[derive(Debug, Default)]
216struct ClusterTopology {
217 // TODO: Support multi-level clusters & threads.
218 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
219}
220
221impl ClusterTopology {
222 const MAX_CORES_PER_CLUSTER: usize = 6;
223}
224
225#[derive(Debug, Default)]
226struct CpuTopology {
227 // TODO: Support sockets.
228 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
229}
230
231impl CpuTopology {
232 const MAX_CLUSTERS: usize = 3;
233}
234
235fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
236 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
237 return Ok(None);
238 };
239
240 let mut topology = BTreeMap::new();
241 for n in 0..CpuTopology::MAX_CLUSTERS {
242 let name = CString::new(format!("cluster{n}")).unwrap();
243 let Some(cluster) = cpu_map.subnode(&name)? else {
244 break;
245 };
246 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800247 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000248 let Some(core) = cluster.subnode(&name)? else {
249 break;
250 };
251 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
252 let prev = topology.insert(cpu.try_into()?, (n, m));
253 if prev.is_some() {
254 return Err(FdtError::BadValue);
255 }
256 }
257 }
258
259 Ok(Some(topology))
260}
261
262fn read_cpu_info_from(
263 fdt: &Fdt,
264) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000265 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000266
267 let cpu_map = read_cpu_map_from(fdt)?;
268 let mut topology: CpuTopology = Default::default();
269
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000270 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000271 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800272 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800273 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
274 let opptable_info = if let Some(phandle) = opp_phandle {
275 let phandle = phandle.try_into()?;
276 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
277 Some(read_opp_info_from(node)?)
278 } else {
279 None
280 };
David Dai50168a32024-02-14 17:00:48 -0800281 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000282 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000283
284 if let Some(ref cpu_map) = cpu_map {
285 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800286 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000287 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800288 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000289 return Err(FdtError::BadValue);
290 }
David Dai8f476cb2024-02-15 21:57:01 -0800291 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000292 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900293 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000294
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000295 if cpu_nodes.next().is_some() {
296 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
297 }
298
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000299 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900300}
301
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000302fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
303 if cpus.is_empty() {
304 return Err(FdtValidationError::InvalidCpuCount(0));
305 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000306 Ok(())
307}
308
David Dai9bdb10c2024-02-01 22:42:54 -0800309fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000310 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
311 let Some(node) = nodes.next() else {
312 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800313 };
314
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000315 if nodes.next().is_some() {
316 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
317 }
318
319 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
320 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000321 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000322
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000323 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800324}
325
326fn validate_vcpufreq_info(
327 vcpufreq_info: &VcpufreqInfo,
328 cpus: &[CpuInfo],
329) -> Result<(), FdtValidationError> {
330 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000331 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800332
333 let base = vcpufreq_info.addr;
334 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000335 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
336
337 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800338 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000339 }
David Dai9bdb10c2024-02-01 22:42:54 -0800340
341 Ok(())
342}
343
344fn patch_opptable(
345 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800346 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800347) -> libfdt::Result<()> {
348 let oppcompat = cstr!("operating-points-v2");
349 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000350
351 let Some(opptable) = opptable else {
352 return next.nop();
353 };
354
David Dai9bdb10c2024-02-01 22:42:54 -0800355 let mut next_subnode = next.first_subnode()?;
356
357 for entry in opptable {
358 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
359 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
360 next_subnode = subnode.next_subnode()?;
361 }
362
363 while let Some(current) = next_subnode {
364 next_subnode = current.delete_and_next_subnode()?;
365 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000366
David Dai9bdb10c2024-02-01 22:42:54 -0800367 Ok(())
368}
369
370// TODO(ptosi): Rework FdtNodeMut and replace this function.
371fn get_nth_compatible<'a>(
372 fdt: &'a mut Fdt,
373 n: usize,
374 compat: &CStr,
375) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000376 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800377 for _ in 0..n {
378 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
379 }
380 Ok(node)
381}
382
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000383fn patch_cpus(
384 fdt: &mut Fdt,
385 cpus: &[CpuInfo],
386 topology: &Option<CpuTopology>,
387) -> libfdt::Result<()> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000388 const COMPAT: &CStr = cstr!("arm,arm-v8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000389 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800390 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800391 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000392 let phandle = cur.as_node().get_phandle()?.unwrap();
393 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800394 if let Some(cpu_capacity) = cpu.cpu_capacity {
395 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
396 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000397 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900398 }
David Dai9bdb10c2024-02-01 22:42:54 -0800399 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900400 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000401 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900402 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000403
404 if let Some(topology) = topology {
405 for (n, cluster) in topology.clusters.iter().enumerate() {
406 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
407 let cluster_node = fdt.node_mut(&path)?.unwrap();
408 if let Some(cluster) = cluster {
409 let mut iter = cluster_node.first_subnode()?;
410 for core in cluster.cores {
411 let mut core_node = iter.unwrap();
412 iter = if let Some(core_idx) = core {
413 let phandle = *cpu_phandles.get(core_idx).unwrap();
414 let value = u32::from(phandle).to_be_bytes();
415 core_node.setprop_inplace(cstr!("cpu"), &value)?;
416 core_node.next_subnode()?
417 } else {
418 core_node.delete_and_next_subnode()?
419 };
420 }
421 assert!(iter.is_none());
422 } else {
423 cluster_node.nop()?;
424 }
425 }
426 } else {
427 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
428 }
429
Jiyong Park6a8789a2023-03-21 14:50:59 +0900430 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000431}
432
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000433/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
434/// the guest that don't require being validated by pvmfw.
435fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
436 let mut props = BTreeMap::new();
437 if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
438 for property in node.properties()? {
439 let name = property.name()?;
440 let value = property.value()?;
441 props.insert(CString::from(name), value.to_vec());
442 }
443 if node.subnodes()?.next().is_some() {
444 warn!("Discarding unexpected /avf/untrusted subnodes.");
445 }
446 }
447
448 Ok(props)
449}
450
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900451/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900452fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900453 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900454 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900455 for property in avf_node.properties()? {
456 let name = property.name()?;
457 let value = property.value()?;
458 property_map.insert(
459 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
460 value.to_vec(),
461 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900462 }
463 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900464 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900465}
466
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000467fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
468 const FORBIDDEN_PROPS: &[&CStr] =
469 &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
470
471 for name in FORBIDDEN_PROPS {
472 if props.contains_key(*name) {
473 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
474 }
475 }
476
477 Ok(())
478}
479
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900480/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
481/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
482fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900483 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900484 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900485 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900486) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000487 let root_vm_dt = vm_dt.root_mut();
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900488 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900489 // TODO(b/318431677): Validate nodes beyond /avf.
490 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900491 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900492 if let Some(ref_value) = avf_node.getprop(name)? {
493 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900494 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900495 "Property mismatches while applying overlay VM reference DT. \
496 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
497 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900498 );
499 return Err(FdtError::BadValue);
500 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900501 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900502 }
503 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900504 Ok(())
505}
506
Jiyong Park00ceff32023-03-13 05:43:23 +0000507#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000508struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900509 ranges: [PciAddrRange; 2],
510 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
511 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000512}
513
Jiyong Park6a8789a2023-03-21 14:50:59 +0900514impl PciInfo {
515 const IRQ_MASK_CELLS: usize = 4;
516 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100517 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000518}
519
Jiyong Park6a8789a2023-03-21 14:50:59 +0900520type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
521type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
522type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000523
524/// Iterator that takes N cells as a chunk
525struct CellChunkIterator<'a, const N: usize> {
526 cells: CellIterator<'a>,
527}
528
529impl<'a, const N: usize> CellChunkIterator<'a, N> {
530 fn new(cells: CellIterator<'a>) -> Self {
531 Self { cells }
532 }
533}
534
535impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
536 type Item = [u32; N];
537 fn next(&mut self) -> Option<Self::Item> {
538 let mut ret: Self::Item = [0; N];
539 for i in ret.iter_mut() {
540 *i = self.cells.next()?;
541 }
542 Some(ret)
543 }
544}
545
Jiyong Park6a8789a2023-03-21 14:50:59 +0900546/// Read pci host controller ranges, irq maps, and irq map masks from DT
547fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
548 let node =
549 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
550
551 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
552 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
553 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
554
555 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000556 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
557 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
558
559 if chunks.next().is_some() {
560 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
561 return Err(FdtError::NoSpace);
562 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900563
564 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000565 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
566 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
567
568 if chunks.next().is_some() {
569 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
570 return Err(FdtError::NoSpace);
571 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900572
573 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
574}
575
Jiyong Park0ee65392023-03-27 20:52:45 +0900576fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900577 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900578 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900579 }
580 for irq_mask in pci_info.irq_masks.iter() {
581 validate_pci_irq_mask(irq_mask)?;
582 }
583 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
584 validate_pci_irq_map(irq_map, idx)?;
585 }
586 Ok(())
587}
588
Jiyong Park0ee65392023-03-27 20:52:45 +0900589fn validate_pci_addr_range(
590 range: &PciAddrRange,
591 memory_range: &Range<usize>,
592) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900593 let mem_flags = PciMemoryFlags(range.addr.0);
594 let range_type = mem_flags.range_type();
595 let prefetchable = mem_flags.prefetchable();
596 let bus_addr = range.addr.1;
597 let cpu_addr = range.parent_addr;
598 let size = range.size;
599
600 if range_type != PciRangeType::Memory64 {
601 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
602 return Err(RebootReason::InvalidFdt);
603 }
604 if prefetchable {
605 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
606 return Err(RebootReason::InvalidFdt);
607 }
608 // Enforce ID bus-to-cpu mappings, as used by crosvm.
609 if bus_addr != cpu_addr {
610 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
611 return Err(RebootReason::InvalidFdt);
612 }
613
Jiyong Park0ee65392023-03-27 20:52:45 +0900614 let Some(bus_end) = bus_addr.checked_add(size) else {
615 error!("PCI address range size {:#x} overflows", size);
616 return Err(RebootReason::InvalidFdt);
617 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000618 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900619 error!("PCI address end {:#x} is outside of translatable range", bus_end);
620 return Err(RebootReason::InvalidFdt);
621 }
622
623 let memory_start = memory_range.start.try_into().unwrap();
624 let memory_end = memory_range.end.try_into().unwrap();
625
626 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
627 error!(
628 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
629 bus_addr, bus_end, memory_start, memory_end
630 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900631 return Err(RebootReason::InvalidFdt);
632 }
633
634 Ok(())
635}
636
637fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000638 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
639 const IRQ_MASK_ADDR_ME: u32 = 0x0;
640 const IRQ_MASK_ADDR_LO: u32 = 0x0;
641 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900642 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000643 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900644 if *irq_mask != EXPECTED {
645 error!("Invalid PCI irq mask {:#?}", irq_mask);
646 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000647 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900648 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000649}
650
Jiyong Park6a8789a2023-03-21 14:50:59 +0900651fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000652 const PCI_DEVICE_IDX: usize = 11;
653 const PCI_IRQ_ADDR_ME: u32 = 0;
654 const PCI_IRQ_ADDR_LO: u32 = 0;
655 const PCI_IRQ_INTC: u32 = 1;
656 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
657 const GIC_SPI: u32 = 0;
658 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
659
Jiyong Park6a8789a2023-03-21 14:50:59 +0900660 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
661 let pci_irq_number = irq_map[3];
662 let _controller_phandle = irq_map[4]; // skipped.
663 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
664 // interrupt-cells is <3> for GIC
665 let gic_peripheral_interrupt_type = irq_map[7];
666 let gic_irq_number = irq_map[8];
667 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000668
Jiyong Park6a8789a2023-03-21 14:50:59 +0900669 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
670 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000671
Jiyong Park6a8789a2023-03-21 14:50:59 +0900672 if pci_addr != expected_pci_addr {
673 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
674 {:#x} {:#x} {:#x}",
675 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
676 return Err(RebootReason::InvalidFdt);
677 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000678
Jiyong Park6a8789a2023-03-21 14:50:59 +0900679 if pci_irq_number != PCI_IRQ_INTC {
680 error!(
681 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
682 pci_irq_number, PCI_IRQ_INTC
683 );
684 return Err(RebootReason::InvalidFdt);
685 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000686
Jiyong Park6a8789a2023-03-21 14:50:59 +0900687 if gic_addr != (0, 0) {
688 error!(
689 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
690 {:#x} {:#x}",
691 gic_addr.0, gic_addr.1, 0, 0
692 );
693 return Err(RebootReason::InvalidFdt);
694 }
695
696 if gic_peripheral_interrupt_type != GIC_SPI {
697 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
698 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
699 return Err(RebootReason::InvalidFdt);
700 }
701
702 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
703 if gic_irq_number != irq_nr {
704 error!(
705 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
706 gic_irq_number, irq_nr
707 );
708 return Err(RebootReason::InvalidFdt);
709 }
710
711 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
712 error!(
713 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
714 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
715 );
716 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000717 }
718 Ok(())
719}
720
Jiyong Park9c63cd12023-03-21 17:53:07 +0900721fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000722 let mut node =
723 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900724
725 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
726 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
727
728 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
729 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
730
731 node.setprop_inplace(
732 cstr!("ranges"),
733 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
734 )
735}
736
Jiyong Park00ceff32023-03-13 05:43:23 +0000737#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900738struct SerialInfo {
739 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000740}
741
742impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900743 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000744}
745
Jiyong Park6a8789a2023-03-21 14:50:59 +0900746fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000747 let mut addrs = ArrayVec::new();
748
749 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
750 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000751 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900752 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000753 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000754 if serial_nodes.next().is_some() {
755 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
756 }
757
Jiyong Park6a8789a2023-03-21 14:50:59 +0900758 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000759}
760
Jiyong Park9c63cd12023-03-21 17:53:07 +0900761/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
762fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
763 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000764 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900765 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000766 let reg =
767 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900768 next = if !serial_info.addrs.contains(&reg.addr) {
769 current.delete_and_next_compatible(name)
770 } else {
771 current.next_compatible(name)
772 }
773 }
774 Ok(())
775}
776
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700777fn validate_swiotlb_info(
778 swiotlb_info: &SwiotlbInfo,
779 memory: &Range<usize>,
780) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900781 let size = swiotlb_info.size;
782 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000783
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700784 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000785 error!("Invalid swiotlb size {:#x}", size);
786 return Err(RebootReason::InvalidFdt);
787 }
788
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000789 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000790 error!("Invalid swiotlb alignment {:#x}", align);
791 return Err(RebootReason::InvalidFdt);
792 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700793
Alice Wang9cfbfd62023-06-14 11:19:03 +0000794 if let Some(addr) = swiotlb_info.addr {
795 if addr.checked_add(size).is_none() {
796 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
797 return Err(RebootReason::InvalidFdt);
798 }
799 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700800 if let Some(range) = swiotlb_info.fixed_range() {
801 if !range.is_within(memory) {
802 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
803 return Err(RebootReason::InvalidFdt);
804 }
805 }
806
Jiyong Park6a8789a2023-03-21 14:50:59 +0900807 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000808}
809
Jiyong Park9c63cd12023-03-21 17:53:07 +0900810fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
811 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000812 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700813
814 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000815 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700816 cstr!("reg"),
817 range.start.try_into().unwrap(),
818 range.len().try_into().unwrap(),
819 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000820 node.nop_property(cstr!("size"))?;
821 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700822 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000823 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700824 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000825 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700826 }
827
Jiyong Park9c63cd12023-03-21 17:53:07 +0900828 Ok(())
829}
830
831fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
832 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
833 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
834 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
835 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
836
837 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000838 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
839 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000840 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900841
842 // range1 is just below range0
843 range1.addr = addr - size;
844 range1.size = Some(size);
845
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000846 let (addr0, size0) = range0.to_cells();
847 let (addr1, size1) = range1.to_cells();
848 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900849
850 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000851 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900852 node.setprop_inplace(cstr!("reg"), flatten(&value))
853}
854
855fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
856 const NUM_INTERRUPTS: usize = 4;
857 const CELLS_PER_INTERRUPT: usize = 3;
858 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
859 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
860 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
861 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
862
863 let num_cpus: u32 = num_cpus.try_into().unwrap();
864 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
865 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
866 *v |= cpu_mask;
867 }
868 for v in value.iter_mut() {
869 *v = v.to_be();
870 }
871
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000872 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900873
874 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000875 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000876 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900877}
878
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000879fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
880 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
881 node
882 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000883 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000884 };
885
886 // The node shouldn't already be present; if it is, return the error.
887 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
888
889 for (name, value) in props {
890 node.setprop(name, value)?;
891 }
892
893 Ok(())
894}
895
Jiyong Park00ceff32023-03-13 05:43:23 +0000896#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800897struct VcpufreqInfo {
898 addr: u64,
899 size: u64,
900}
901
902fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
903 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
904 if let Some(info) = vcpufreq_info {
905 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
906 } else {
907 node.nop()
908 }
909}
910
911#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900912pub struct DeviceTreeInfo {
913 pub kernel_range: Option<Range<usize>>,
914 pub initrd_range: Option<Range<usize>>,
915 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900916 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000917 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000918 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000919 pci_info: PciInfo,
920 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700921 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900922 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000923 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900924 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800925 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000926}
927
928impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000929 const MAX_CPUS: usize = 16;
930
931 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000932 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
933
934 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
935 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000936}
937
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900938pub fn sanitize_device_tree(
939 fdt: &mut [u8],
940 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900941 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900942) -> Result<DeviceTreeInfo, RebootReason> {
943 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
944 error!("Failed to load FDT: {e}");
945 RebootReason::InvalidFdt
946 })?;
947
948 let vm_dtbo = match vm_dtbo {
949 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
950 error!("Failed to load VM DTBO: {e}");
951 RebootReason::InvalidFdt
952 })?),
953 None => None,
954 };
955
956 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900957
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000958 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
959 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
960 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900961 error!("Failed to instantiate FDT from the template DT: {e}");
962 RebootReason::InvalidFdt
963 })?;
964
Jaewan Kim9220e852023-12-01 10:58:40 +0900965 fdt.unpack().map_err(|e| {
966 error!("Failed to unpack DT for patching: {e}");
967 RebootReason::InvalidFdt
968 })?;
969
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900970 if let Some(device_assignment_info) = &info.device_assignment {
971 let vm_dtbo = vm_dtbo.unwrap();
972 device_assignment_info.filter(vm_dtbo).map_err(|e| {
973 error!("Failed to filter VM DTBO: {e}");
974 RebootReason::InvalidFdt
975 })?;
976 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
977 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
978 // it can only be instantiated after validation.
979 unsafe {
980 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
981 error!("Failed to apply filtered VM DTBO: {e}");
982 RebootReason::InvalidFdt
983 })?;
984 }
985 }
986
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900987 if let Some(vm_ref_dt) = vm_ref_dt {
988 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
989 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900990 RebootReason::InvalidFdt
991 })?;
992
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900993 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
994 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900995 RebootReason::InvalidFdt
996 })?;
997 }
998
Jiyong Park9c63cd12023-03-21 17:53:07 +0900999 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001000
Jaewan Kim19b984f2023-12-04 15:16:50 +09001001 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1002
Jaewan Kim9220e852023-12-01 10:58:40 +09001003 fdt.pack().map_err(|e| {
1004 error!("Failed to unpack DT after patching: {e}");
1005 RebootReason::InvalidFdt
1006 })?;
1007
Jiyong Park6a8789a2023-03-21 14:50:59 +09001008 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001009}
1010
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001011fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001012 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1013 error!("Failed to read kernel range from DT: {e}");
1014 RebootReason::InvalidFdt
1015 })?;
1016
1017 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1018 error!("Failed to read initrd range from DT: {e}");
1019 RebootReason::InvalidFdt
1020 })?;
1021
Alice Wang0d527472023-06-13 14:55:38 +00001022 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001023
Jiyong Parke9d87e82023-03-21 19:28:40 +09001024 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1025 error!("Failed to read bootargs from DT: {e}");
1026 RebootReason::InvalidFdt
1027 })?;
1028
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001029 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001030 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001031 RebootReason::InvalidFdt
1032 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001033 validate_cpu_info(&cpus).map_err(|e| {
1034 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001035 RebootReason::InvalidFdt
1036 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001037
David Dai9bdb10c2024-02-01 22:42:54 -08001038 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1039 error!("Failed to read vcpufreq info from DT: {e}");
1040 RebootReason::InvalidFdt
1041 })?;
1042 if let Some(ref info) = vcpufreq_info {
1043 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1044 error!("Failed to validate vcpufreq info from DT: {e}");
1045 RebootReason::InvalidFdt
1046 })?;
1047 }
1048
Jiyong Park6a8789a2023-03-21 14:50:59 +09001049 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1050 error!("Failed to read pci info from DT: {e}");
1051 RebootReason::InvalidFdt
1052 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001053 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001054
1055 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1056 error!("Failed to read serial info from DT: {e}");
1057 RebootReason::InvalidFdt
1058 })?;
1059
Alice Wang9cfbfd62023-06-14 11:19:03 +00001060 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001061 error!("Failed to read swiotlb info from DT: {e}");
1062 RebootReason::InvalidFdt
1063 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001064 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001065
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001066 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001067 Some(vm_dtbo) => {
1068 if let Some(hypervisor) = hyp::get_device_assigner() {
1069 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1070 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1071 RebootReason::InvalidFdt
1072 })?
1073 } else {
1074 warn!(
1075 "Device assignment is ignored because device assigning hypervisor is missing"
1076 );
1077 None
1078 }
1079 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001080 None => None,
1081 };
1082
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001083 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1084 error!("Failed to read untrusted properties: {e}");
1085 RebootReason::InvalidFdt
1086 })?;
1087 validate_untrusted_props(&untrusted_props).map_err(|e| {
1088 error!("Failed to validate untrusted properties: {e}");
1089 RebootReason::InvalidFdt
1090 })?;
1091
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001092 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001093 error!("Failed to read names of properties under /avf from DT: {e}");
1094 RebootReason::InvalidFdt
1095 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001096
Jiyong Park00ceff32023-03-13 05:43:23 +00001097 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001098 kernel_range,
1099 initrd_range,
1100 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001101 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001102 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001103 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001104 pci_info,
1105 serial_info,
1106 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001107 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001108 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001109 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001110 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001111 })
1112}
1113
Jiyong Park9c63cd12023-03-21 17:53:07 +09001114fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1115 if let Some(initrd_range) = &info.initrd_range {
1116 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1117 error!("Failed to patch initrd range to DT: {e}");
1118 RebootReason::InvalidFdt
1119 })?;
1120 }
1121 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1122 error!("Failed to patch memory range to DT: {e}");
1123 RebootReason::InvalidFdt
1124 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001125 if let Some(bootargs) = &info.bootargs {
1126 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1127 error!("Failed to patch bootargs to DT: {e}");
1128 RebootReason::InvalidFdt
1129 })?;
1130 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001131 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001132 error!("Failed to patch cpus to DT: {e}");
1133 RebootReason::InvalidFdt
1134 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001135 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1136 error!("Failed to patch vcpufreq info to DT: {e}");
1137 RebootReason::InvalidFdt
1138 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001139 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1140 error!("Failed to patch pci info to DT: {e}");
1141 RebootReason::InvalidFdt
1142 })?;
1143 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1144 error!("Failed to patch serial info to DT: {e}");
1145 RebootReason::InvalidFdt
1146 })?;
1147 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1148 error!("Failed to patch swiotlb info to DT: {e}");
1149 RebootReason::InvalidFdt
1150 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001151 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001152 error!("Failed to patch gic info to DT: {e}");
1153 RebootReason::InvalidFdt
1154 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001155 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001156 error!("Failed to patch timer info to DT: {e}");
1157 RebootReason::InvalidFdt
1158 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001159 if let Some(device_assignment) = &info.device_assignment {
1160 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1161 // then VM DTBO's underlying slice is allocated.
1162 device_assignment.patch(fdt).map_err(|e| {
1163 error!("Failed to patch device assignment info to DT: {e}");
1164 RebootReason::InvalidFdt
1165 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001166 } else {
1167 device_assignment::clean(fdt).map_err(|e| {
1168 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1169 RebootReason::InvalidFdt
1170 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001171 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001172 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1173 error!("Failed to patch untrusted properties: {e}");
1174 RebootReason::InvalidFdt
1175 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001176
Jiyong Park9c63cd12023-03-21 17:53:07 +09001177 Ok(())
1178}
1179
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001180/// Modifies the input DT according to the fields of the configuration.
1181pub fn modify_for_next_stage(
1182 fdt: &mut Fdt,
1183 bcc: &[u8],
1184 new_instance: bool,
1185 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001186 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001187 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001188 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001189) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001190 if let Some(debug_policy) = debug_policy {
1191 let backup = Vec::from(fdt.as_slice());
1192 fdt.unpack()?;
1193 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1194 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1195 info!("Debug policy applied.");
1196 } else {
1197 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1198 fdt.unpack()?;
1199 }
1200 } else {
1201 info!("No debug policy found.");
1202 fdt.unpack()?;
1203 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001204
Jiyong Parke9d87e82023-03-21 19:28:40 +09001205 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001206
Alice Wang56ec45b2023-06-15 08:30:32 +00001207 if let Some(mut chosen) = fdt.chosen_mut()? {
1208 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1209 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001210 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001211 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001212 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001213 if let Some(bootargs) = read_bootargs_from(fdt)? {
1214 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1215 }
1216 }
1217
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001218 fdt.pack()?;
1219
1220 Ok(())
1221}
1222
Jiyong Parke9d87e82023-03-21 19:28:40 +09001223/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1224fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001225 // We reject DTs with missing reserved-memory node as validation should have checked that the
1226 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001227 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001228
Jiyong Parke9d87e82023-03-21 19:28:40 +09001229 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001230
Jiyong Parke9d87e82023-03-21 19:28:40 +09001231 let addr: u64 = addr.try_into().unwrap();
1232 let size: u64 = size.try_into().unwrap();
1233 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001234}
1235
Alice Wang56ec45b2023-06-15 08:30:32 +00001236fn empty_or_delete_prop(
1237 fdt_node: &mut FdtNodeMut,
1238 prop_name: &CStr,
1239 keep_prop: bool,
1240) -> libfdt::Result<()> {
1241 if keep_prop {
1242 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001243 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001244 fdt_node
1245 .delprop(prop_name)
1246 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001247 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001248}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001249
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001250/// Apply the debug policy overlay to the guest DT.
1251///
1252/// 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 +00001253fn apply_debug_policy(
1254 fdt: &mut Fdt,
1255 backup_fdt: &Fdt,
1256 debug_policy: &[u8],
1257) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001258 let mut debug_policy = Vec::from(debug_policy);
1259 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001260 Ok(overlay) => overlay,
1261 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001262 warn!("Corrupted debug policy found: {e}. Not applying.");
1263 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001264 }
1265 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001266
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001267 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001268 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001269 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001270 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001271 // A successful restoration is considered success because an invalid debug policy
1272 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001273 Ok(false)
1274 } else {
1275 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001276 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001277}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001278
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001279fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001280 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1281 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1282 return Ok(value == 1);
1283 }
1284 }
1285 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1286}
1287
1288fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001289 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1290 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001291
1292 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1293 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1294 ("crashkernel", Box::new(|_| has_crashkernel)),
1295 ("console", Box::new(|_| has_console)),
1296 ];
1297
1298 // parse and filter out unwanted
1299 let mut filtered = Vec::new();
1300 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1301 info!("Invalid bootarg: {e}");
1302 FdtError::BadValue
1303 })? {
1304 match accepted.iter().find(|&t| t.0 == arg.name()) {
1305 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1306 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1307 }
1308 }
1309
1310 // flatten into a new C-string
1311 let mut new_bootargs = Vec::new();
1312 for (i, arg) in filtered.iter().enumerate() {
1313 if i != 0 {
1314 new_bootargs.push(b' '); // separator
1315 }
1316 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1317 }
1318 new_bootargs.push(b'\0');
1319
1320 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1321 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1322}