blob: d8053eb268f8533936e9991fe70b8c6b13ee87f7 [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 libfdt::AddressRange;
34use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000035use libfdt::Fdt;
36use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080037use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000039use libfdt::Phandle;
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;
Pierre-Clément Tosif2c19d42024-10-01 17:42:04 +010046use vmbase::fdt::pci::PciMemoryFlags;
47use vmbase::fdt::pci::PciRangeType;
Alice Wanga3971062023-06-13 11:48:53 +000048use vmbase::fdt::SwiotlbInfo;
Pierre-Clément Tosia9b345f2024-04-27 01:01:42 +010049use vmbase::hyp;
Alice Wang63f4c9e2023-06-12 09:36:43 +000050use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000051use vmbase::memory::SIZE_4KB;
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 {
David Daib19fd082024-04-19 16:33:26 -0700222 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000223}
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 Tosi6ae8fe22024-04-17 20:02:23 +0100270 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,armv8"))?;
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 Tosi6ae8fe22024-04-17 20:02:23 +0100388 const COMPAT: &CStr = cstr!("arm,armv8");
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 Ioffe2d0969c2024-06-06 12:59:12 +0000517 const MAX_IRQS: usize = 16;
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();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900595 let bus_addr = range.addr.1;
596 let cpu_addr = range.parent_addr;
597 let size = range.size;
598
599 if range_type != PciRangeType::Memory64 {
600 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
601 return Err(RebootReason::InvalidFdt);
602 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900603 // Enforce ID bus-to-cpu mappings, as used by crosvm.
604 if bus_addr != cpu_addr {
605 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
606 return Err(RebootReason::InvalidFdt);
607 }
608
Jiyong Park0ee65392023-03-27 20:52:45 +0900609 let Some(bus_end) = bus_addr.checked_add(size) else {
610 error!("PCI address range size {:#x} overflows", size);
611 return Err(RebootReason::InvalidFdt);
612 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000613 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900614 error!("PCI address end {:#x} is outside of translatable range", bus_end);
615 return Err(RebootReason::InvalidFdt);
616 }
617
618 let memory_start = memory_range.start.try_into().unwrap();
619 let memory_end = memory_range.end.try_into().unwrap();
620
621 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
622 error!(
623 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
624 bus_addr, bus_end, memory_start, memory_end
625 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900626 return Err(RebootReason::InvalidFdt);
627 }
628
629 Ok(())
630}
631
632fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000633 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
634 const IRQ_MASK_ADDR_ME: u32 = 0x0;
635 const IRQ_MASK_ADDR_LO: u32 = 0x0;
636 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900637 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000638 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639 if *irq_mask != EXPECTED {
640 error!("Invalid PCI irq mask {:#?}", irq_mask);
641 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000642 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900643 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000644}
645
Jiyong Park6a8789a2023-03-21 14:50:59 +0900646fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000647 const PCI_DEVICE_IDX: usize = 11;
648 const PCI_IRQ_ADDR_ME: u32 = 0;
649 const PCI_IRQ_ADDR_LO: u32 = 0;
650 const PCI_IRQ_INTC: u32 = 1;
651 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
652 const GIC_SPI: u32 = 0;
653 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
654
Jiyong Park6a8789a2023-03-21 14:50:59 +0900655 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
656 let pci_irq_number = irq_map[3];
657 let _controller_phandle = irq_map[4]; // skipped.
658 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
659 // interrupt-cells is <3> for GIC
660 let gic_peripheral_interrupt_type = irq_map[7];
661 let gic_irq_number = irq_map[8];
662 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000663
Jiyong Park6a8789a2023-03-21 14:50:59 +0900664 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
665 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000666
Jiyong Park6a8789a2023-03-21 14:50:59 +0900667 if pci_addr != expected_pci_addr {
668 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
669 {:#x} {:#x} {:#x}",
670 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
671 return Err(RebootReason::InvalidFdt);
672 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000673
Jiyong Park6a8789a2023-03-21 14:50:59 +0900674 if pci_irq_number != PCI_IRQ_INTC {
675 error!(
676 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
677 pci_irq_number, PCI_IRQ_INTC
678 );
679 return Err(RebootReason::InvalidFdt);
680 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000681
Jiyong Park6a8789a2023-03-21 14:50:59 +0900682 if gic_addr != (0, 0) {
683 error!(
684 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
685 {:#x} {:#x}",
686 gic_addr.0, gic_addr.1, 0, 0
687 );
688 return Err(RebootReason::InvalidFdt);
689 }
690
691 if gic_peripheral_interrupt_type != GIC_SPI {
692 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
693 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
694 return Err(RebootReason::InvalidFdt);
695 }
696
697 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
698 if gic_irq_number != irq_nr {
699 error!(
700 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
701 gic_irq_number, irq_nr
702 );
703 return Err(RebootReason::InvalidFdt);
704 }
705
706 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
707 error!(
708 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
709 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
710 );
711 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000712 }
713 Ok(())
714}
715
Jiyong Park9c63cd12023-03-21 17:53:07 +0900716fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000717 let mut node =
718 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900719
720 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
721 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
722
723 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
724 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
725
726 node.setprop_inplace(
727 cstr!("ranges"),
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000728 [pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()].as_flattened(),
Jiyong Park9c63cd12023-03-21 17:53:07 +0900729 )
730}
731
Jiyong Park00ceff32023-03-13 05:43:23 +0000732#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900733struct SerialInfo {
734 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000735}
736
737impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900738 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000739}
740
Jiyong Park6a8789a2023-03-21 14:50:59 +0900741fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000742 let mut addrs = ArrayVec::new();
743
744 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
745 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000746 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900747 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000748 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000749 if serial_nodes.next().is_some() {
750 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
751 }
752
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000754}
755
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000756#[derive(Default, Debug, PartialEq)]
757struct WdtInfo {
758 addr: u64,
759 size: u64,
760 irq: [u32; WdtInfo::IRQ_CELLS],
761}
762
763impl WdtInfo {
764 const IRQ_CELLS: usize = 3;
765 const IRQ_NR: u32 = 0xf;
766 const ADDR: u64 = 0x3000;
767 const SIZE: u64 = 0x1000;
768 const GIC_PPI: u32 = 1;
769 const IRQ_TYPE_EDGE_RISING: u32 = 1;
770 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100771 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000772 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
773
774 const fn get_expected(num_cpus: usize) -> Self {
775 Self {
776 addr: Self::ADDR,
777 size: Self::SIZE,
778 irq: [
779 Self::GIC_PPI,
780 Self::IRQ_NR,
781 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
782 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
783 | Self::IRQ_TYPE_EDGE_RISING,
784 ],
785 }
786 }
787}
788
789fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
790 let mut node_iter = fdt.compatible_nodes(cstr!("qemu,vcpu-stall-detector"))?;
791 let node = node_iter.next().ok_or(FdtError::NotFound)?;
792 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
793
794 let reg = ranges.next().ok_or(FdtError::NotFound)?;
795 let size = reg.size.ok_or(FdtError::NotFound)?;
796 if ranges.next().is_some() {
797 warn!("Discarding extra vmwdt <reg> entries.");
798 }
799
800 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
801 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
802 let irq = chunks.next().ok_or(FdtError::NotFound)?;
803
804 if chunks.next().is_some() {
805 warn!("Discarding extra vmwdt <interrupts> entries.");
806 }
807
808 Ok(WdtInfo { addr: reg.addr, size, irq })
809}
810
811fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
812 if *wdt != WdtInfo::get_expected(num_cpus) {
813 error!("Invalid watchdog timer: {wdt:?}");
814 return Err(RebootReason::InvalidFdt);
815 }
816
817 Ok(())
818}
819
820fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
821 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
822 for v in interrupts.iter_mut() {
823 *v = v.to_be();
824 }
825
826 let mut node = fdt
827 .root_mut()
828 .next_compatible(cstr!("qemu,vcpu-stall-detector"))?
829 .ok_or(libfdt::FdtError::NotFound)?;
830 node.setprop_inplace(cstr!("interrupts"), interrupts.as_bytes())?;
831 Ok(())
832}
833
Jiyong Park9c63cd12023-03-21 17:53:07 +0900834/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
835fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
836 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000837 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900838 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000839 let reg =
840 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900841 next = if !serial_info.addrs.contains(&reg.addr) {
842 current.delete_and_next_compatible(name)
843 } else {
844 current.next_compatible(name)
845 }
846 }
847 Ok(())
848}
849
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700850fn validate_swiotlb_info(
851 swiotlb_info: &SwiotlbInfo,
852 memory: &Range<usize>,
853) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900854 let size = swiotlb_info.size;
855 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000856
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700857 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000858 error!("Invalid swiotlb size {:#x}", size);
859 return Err(RebootReason::InvalidFdt);
860 }
861
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000862 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000863 error!("Invalid swiotlb alignment {:#x}", align);
864 return Err(RebootReason::InvalidFdt);
865 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700866
Alice Wang9cfbfd62023-06-14 11:19:03 +0000867 if let Some(addr) = swiotlb_info.addr {
868 if addr.checked_add(size).is_none() {
869 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
870 return Err(RebootReason::InvalidFdt);
871 }
872 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700873 if let Some(range) = swiotlb_info.fixed_range() {
874 if !range.is_within(memory) {
875 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
876 return Err(RebootReason::InvalidFdt);
877 }
878 }
879
Jiyong Park6a8789a2023-03-21 14:50:59 +0900880 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000881}
882
Jiyong Park9c63cd12023-03-21 17:53:07 +0900883fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
884 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000885 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700886
887 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000888 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700889 cstr!("reg"),
890 range.start.try_into().unwrap(),
891 range.len().try_into().unwrap(),
892 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000893 node.nop_property(cstr!("size"))?;
894 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700895 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000896 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700897 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000898 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700899 }
900
Jiyong Park9c63cd12023-03-21 17:53:07 +0900901 Ok(())
902}
903
904fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
905 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
906 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
907 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
908 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
909
910 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000911 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
912 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000913 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900914
915 // range1 is just below range0
916 range1.addr = addr - size;
917 range1.size = Some(size);
918
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000919 let (addr0, size0) = range0.to_cells();
920 let (addr1, size1) = range1.to_cells();
921 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900922
923 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000924 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000925 node.setprop_inplace(cstr!("reg"), value.as_flattened())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900926}
927
928fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
929 const NUM_INTERRUPTS: usize = 4;
930 const CELLS_PER_INTERRUPT: usize = 3;
931 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
932 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
933 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
934 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
935
936 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100937 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900938 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000939
Jiyong Park9c63cd12023-03-21 17:53:07 +0900940 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
941 *v |= cpu_mask;
942 }
943 for v in value.iter_mut() {
944 *v = v.to_be();
945 }
946
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000947 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900948
949 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000950 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000951 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900952}
953
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000954fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
955 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
956 node
957 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000958 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000959 };
960
961 // The node shouldn't already be present; if it is, return the error.
962 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
963
964 for (name, value) in props {
965 node.setprop(name, value)?;
966 }
967
968 Ok(())
969}
970
Jiyong Park00ceff32023-03-13 05:43:23 +0000971#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800972struct VcpufreqInfo {
973 addr: u64,
974 size: u64,
975}
976
977fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
978 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
979 if let Some(info) = vcpufreq_info {
980 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
981 } else {
982 node.nop()
983 }
984}
985
986#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900987pub struct DeviceTreeInfo {
988 pub kernel_range: Option<Range<usize>>,
989 pub initrd_range: Option<Range<usize>>,
990 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900991 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000992 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000993 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000994 pci_info: PciInfo,
995 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700996 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900997 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000998 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900999 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001000 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001001}
1002
1003impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001004 const MAX_CPUS: usize = 16;
1005
1006 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001007 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1008
1009 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1010 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001011}
1012
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001013pub fn sanitize_device_tree(
1014 fdt: &mut [u8],
1015 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001016 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001017) -> Result<DeviceTreeInfo, RebootReason> {
1018 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
1019 error!("Failed to load FDT: {e}");
1020 RebootReason::InvalidFdt
1021 })?;
1022
1023 let vm_dtbo = match vm_dtbo {
1024 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1025 error!("Failed to load VM DTBO: {e}");
1026 RebootReason::InvalidFdt
1027 })?),
1028 None => None,
1029 };
1030
1031 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +09001032
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001033 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
1034 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
1035 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001036 error!("Failed to instantiate FDT from the template DT: {e}");
1037 RebootReason::InvalidFdt
1038 })?;
1039
Jaewan Kim9220e852023-12-01 10:58:40 +09001040 fdt.unpack().map_err(|e| {
1041 error!("Failed to unpack DT for patching: {e}");
1042 RebootReason::InvalidFdt
1043 })?;
1044
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001045 if let Some(device_assignment_info) = &info.device_assignment {
1046 let vm_dtbo = vm_dtbo.unwrap();
1047 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1048 error!("Failed to filter VM DTBO: {e}");
1049 RebootReason::InvalidFdt
1050 })?;
1051 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1052 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1053 // it can only be instantiated after validation.
1054 unsafe {
1055 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1056 error!("Failed to apply filtered VM DTBO: {e}");
1057 RebootReason::InvalidFdt
1058 })?;
1059 }
1060 }
1061
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001062 if let Some(vm_ref_dt) = vm_ref_dt {
1063 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1064 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001065 RebootReason::InvalidFdt
1066 })?;
1067
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001068 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1069 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001070 RebootReason::InvalidFdt
1071 })?;
1072 }
1073
Jiyong Park9c63cd12023-03-21 17:53:07 +09001074 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001075
Jaewan Kim19b984f2023-12-04 15:16:50 +09001076 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1077
Jaewan Kim9220e852023-12-01 10:58:40 +09001078 fdt.pack().map_err(|e| {
1079 error!("Failed to unpack DT after patching: {e}");
1080 RebootReason::InvalidFdt
1081 })?;
1082
Jiyong Park6a8789a2023-03-21 14:50:59 +09001083 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001084}
1085
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001086fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001087 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1088 error!("Failed to read kernel range from DT: {e}");
1089 RebootReason::InvalidFdt
1090 })?;
1091
1092 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1093 error!("Failed to read initrd range from DT: {e}");
1094 RebootReason::InvalidFdt
1095 })?;
1096
Alice Wang0d527472023-06-13 14:55:38 +00001097 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001098
Jiyong Parke9d87e82023-03-21 19:28:40 +09001099 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1100 error!("Failed to read bootargs from DT: {e}");
1101 RebootReason::InvalidFdt
1102 })?;
1103
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001104 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001105 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001106 RebootReason::InvalidFdt
1107 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001108 validate_cpu_info(&cpus).map_err(|e| {
1109 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001110 RebootReason::InvalidFdt
1111 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001112
David Dai9bdb10c2024-02-01 22:42:54 -08001113 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1114 error!("Failed to read vcpufreq info from DT: {e}");
1115 RebootReason::InvalidFdt
1116 })?;
1117 if let Some(ref info) = vcpufreq_info {
1118 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1119 error!("Failed to validate vcpufreq info from DT: {e}");
1120 RebootReason::InvalidFdt
1121 })?;
1122 }
1123
Jiyong Park6a8789a2023-03-21 14:50:59 +09001124 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1125 error!("Failed to read pci info from DT: {e}");
1126 RebootReason::InvalidFdt
1127 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001128 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001129
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001130 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1131 error!("Failed to read vCPU stall detector info from DT: {e}");
1132 RebootReason::InvalidFdt
1133 })?;
1134 validate_wdt_info(&wdt_info, cpus.len())?;
1135
Jiyong Park6a8789a2023-03-21 14:50:59 +09001136 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1137 error!("Failed to read serial info from DT: {e}");
1138 RebootReason::InvalidFdt
1139 })?;
1140
Alice Wang9cfbfd62023-06-14 11:19:03 +00001141 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001142 error!("Failed to read swiotlb info from DT: {e}");
1143 RebootReason::InvalidFdt
1144 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001145 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001146
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001147 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001148 Some(vm_dtbo) => {
1149 if let Some(hypervisor) = hyp::get_device_assigner() {
1150 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1151 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1152 RebootReason::InvalidFdt
1153 })?
1154 } else {
1155 warn!(
1156 "Device assignment is ignored because device assigning hypervisor is missing"
1157 );
1158 None
1159 }
1160 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001161 None => None,
1162 };
1163
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001164 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1165 error!("Failed to read untrusted properties: {e}");
1166 RebootReason::InvalidFdt
1167 })?;
1168 validate_untrusted_props(&untrusted_props).map_err(|e| {
1169 error!("Failed to validate untrusted properties: {e}");
1170 RebootReason::InvalidFdt
1171 })?;
1172
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001173 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001174 error!("Failed to read names of properties under /avf from DT: {e}");
1175 RebootReason::InvalidFdt
1176 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001177
Jiyong Park00ceff32023-03-13 05:43:23 +00001178 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001179 kernel_range,
1180 initrd_range,
1181 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001182 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001183 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001184 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001185 pci_info,
1186 serial_info,
1187 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001188 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001189 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001190 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001191 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001192 })
1193}
1194
Jiyong Park9c63cd12023-03-21 17:53:07 +09001195fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1196 if let Some(initrd_range) = &info.initrd_range {
1197 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1198 error!("Failed to patch initrd range to DT: {e}");
1199 RebootReason::InvalidFdt
1200 })?;
1201 }
1202 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1203 error!("Failed to patch memory range to DT: {e}");
1204 RebootReason::InvalidFdt
1205 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001206 if let Some(bootargs) = &info.bootargs {
1207 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1208 error!("Failed to patch bootargs to DT: {e}");
1209 RebootReason::InvalidFdt
1210 })?;
1211 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001212 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001213 error!("Failed to patch cpus to DT: {e}");
1214 RebootReason::InvalidFdt
1215 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001216 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1217 error!("Failed to patch vcpufreq info to DT: {e}");
1218 RebootReason::InvalidFdt
1219 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001220 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1221 error!("Failed to patch pci info to DT: {e}");
1222 RebootReason::InvalidFdt
1223 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001224 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1225 error!("Failed to patch wdt info to DT: {e}");
1226 RebootReason::InvalidFdt
1227 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001228 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1229 error!("Failed to patch serial info to DT: {e}");
1230 RebootReason::InvalidFdt
1231 })?;
1232 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1233 error!("Failed to patch swiotlb info to DT: {e}");
1234 RebootReason::InvalidFdt
1235 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001236 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001237 error!("Failed to patch gic info to DT: {e}");
1238 RebootReason::InvalidFdt
1239 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001240 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001241 error!("Failed to patch timer info to DT: {e}");
1242 RebootReason::InvalidFdt
1243 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001244 if let Some(device_assignment) = &info.device_assignment {
1245 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1246 // then VM DTBO's underlying slice is allocated.
1247 device_assignment.patch(fdt).map_err(|e| {
1248 error!("Failed to patch device assignment info to DT: {e}");
1249 RebootReason::InvalidFdt
1250 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001251 } else {
1252 device_assignment::clean(fdt).map_err(|e| {
1253 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1254 RebootReason::InvalidFdt
1255 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001256 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001257 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1258 error!("Failed to patch untrusted properties: {e}");
1259 RebootReason::InvalidFdt
1260 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001261
Jiyong Park9c63cd12023-03-21 17:53:07 +09001262 Ok(())
1263}
1264
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001265/// Modifies the input DT according to the fields of the configuration.
1266pub fn modify_for_next_stage(
1267 fdt: &mut Fdt,
1268 bcc: &[u8],
1269 new_instance: bool,
1270 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001271 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001272 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001273 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001274) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001275 if let Some(debug_policy) = debug_policy {
1276 let backup = Vec::from(fdt.as_slice());
1277 fdt.unpack()?;
1278 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1279 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1280 info!("Debug policy applied.");
1281 } else {
1282 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1283 fdt.unpack()?;
1284 }
1285 } else {
1286 info!("No debug policy found.");
1287 fdt.unpack()?;
1288 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001289
Jiyong Parke9d87e82023-03-21 19:28:40 +09001290 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001291
Alice Wang56ec45b2023-06-15 08:30:32 +00001292 if let Some(mut chosen) = fdt.chosen_mut()? {
1293 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1294 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001295 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001296 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001297 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001298 if let Some(bootargs) = read_bootargs_from(fdt)? {
1299 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1300 }
1301 }
1302
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001303 fdt.pack()?;
1304
1305 Ok(())
1306}
1307
Jiyong Parke9d87e82023-03-21 19:28:40 +09001308/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1309fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001310 // We reject DTs with missing reserved-memory node as validation should have checked that the
1311 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001312 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001313
Jiyong Parke9d87e82023-03-21 19:28:40 +09001314 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001315
Jiyong Parke9d87e82023-03-21 19:28:40 +09001316 let addr: u64 = addr.try_into().unwrap();
1317 let size: u64 = size.try_into().unwrap();
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +00001318 node.setprop_inplace(cstr!("reg"), [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001319}
1320
Alice Wang56ec45b2023-06-15 08:30:32 +00001321fn empty_or_delete_prop(
1322 fdt_node: &mut FdtNodeMut,
1323 prop_name: &CStr,
1324 keep_prop: bool,
1325) -> libfdt::Result<()> {
1326 if keep_prop {
1327 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001328 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001329 fdt_node
1330 .delprop(prop_name)
1331 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001332 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001333}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001334
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001335/// Apply the debug policy overlay to the guest DT.
1336///
1337/// 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 +00001338fn apply_debug_policy(
1339 fdt: &mut Fdt,
1340 backup_fdt: &Fdt,
1341 debug_policy: &[u8],
1342) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001343 let mut debug_policy = Vec::from(debug_policy);
1344 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001345 Ok(overlay) => overlay,
1346 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001347 warn!("Corrupted debug policy found: {e}. Not applying.");
1348 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001349 }
1350 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001351
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001352 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001353 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001354 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001355 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001356 // A successful restoration is considered success because an invalid debug policy
1357 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001358 Ok(false)
1359 } else {
1360 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001361 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001362}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001363
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001364fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001365 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1366 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1367 return Ok(value == 1);
1368 }
1369 }
1370 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1371}
1372
1373fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001374 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1375 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001376
1377 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1378 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1379 ("crashkernel", Box::new(|_| has_crashkernel)),
1380 ("console", Box::new(|_| has_console)),
1381 ];
1382
1383 // parse and filter out unwanted
1384 let mut filtered = Vec::new();
1385 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1386 info!("Invalid bootarg: {e}");
1387 FdtError::BadValue
1388 })? {
1389 match accepted.iter().find(|&t| t.0 == arg.name()) {
1390 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1391 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1392 }
1393 }
1394
1395 // flatten into a new C-string
1396 let mut new_bootargs = Vec::new();
1397 for (i, arg) in filtered.iter().enumerate() {
1398 if i != 0 {
1399 new_bootargs.push(b' '); // separator
1400 }
1401 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1402 }
1403 new_bootargs.push(b'\0');
1404
1405 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1406 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1407}