blob: 6716130e48d027640643f1507b82335c0303af31 [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 Parkc5d2ef22023-04-11 01:23:46 +090019use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000020use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090021use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090022use alloc::ffi::CString;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000023use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090024use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090025use core::cmp::max;
26use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000027use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000028use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090029use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::ops::Range;
Per Larsen7ec45d32024-11-02 00:56:46 +000031use hypervisor_backends::get_device_assigner;
Jiyong Park00ceff32023-03-13 05:43:23 +000032use libfdt::AddressRange;
33use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000034use libfdt::Fdt;
35use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080036use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000037use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000038use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090039use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000040use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090041use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000042use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000043use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000044use tinyvec::ArrayVec;
Pierre-Clément Tosif2c19d42024-10-01 17:42:04 +010045use vmbase::fdt::pci::PciMemoryFlags;
46use vmbase::fdt::pci::PciRangeType;
Alice Wanga3971062023-06-13 11:48:53 +000047use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000048use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000049use vmbase::memory::SIZE_4KB;
Alice Wang4be4dd02023-06-07 07:50:40 +000050use vmbase::util::RangeExt as _;
Andrew Walbran47d316e2024-11-28 18:41:09 +000051use zerocopy::IntoBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000052
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +000053// SAFETY: The template DT is automatically generated through DTC, which should produce valid DTBs.
54const FDT_TEMPLATE: &Fdt = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
55
Alice Wangabc7d632023-06-14 09:10:14 +000056/// An enumeration of errors that can occur during the FDT validation.
57#[derive(Clone, Debug)]
58pub enum FdtValidationError {
59 /// Invalid CPU count.
60 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080061 /// Invalid VCpufreq Range.
62 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000063 /// Forbidden /avf/untrusted property.
64 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000065}
66
67impl fmt::Display for FdtValidationError {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 match self {
70 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000071 Self::InvalidVcpufreq(addr, size) => {
72 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
73 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000074 Self::ForbiddenUntrustedProp(name) => {
75 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
76 }
Alice Wangabc7d632023-06-14 09:10:14 +000077 }
78 }
79}
80
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +000081/// Extract from /config the address range containing the pre-loaded kernel.
82///
83/// Absence of /config is not an error. However, an error is returned if only one of the two
84/// properties is present.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +000085pub fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +000086 let addr = c"kernel-address";
87 let size = c"kernel-size";
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000088
Alan Stokesf46a17c2025-01-05 15:50:18 +000089 if let Some(config) = fdt.node(c"/config")? {
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +000090 match (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
91 (None, None) => {}
92 (Some(addr), Some(size)) => {
93 let addr = addr as usize;
94 let size = size as usize;
95 return Ok(Some(addr..(addr + size)));
96 }
97 _ => return Err(FdtError::NotFound),
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000098 }
99 }
100
101 Ok(None)
102}
103
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +0000104/// Extract from /chosen the address range containing the pre-loaded ramdisk.
105///
106/// Absence is not an error as there can be initrd-less VM. However, an error is returned if only
107/// one of the two properties is present.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +0000108pub fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000109 let start = c"linux,initrd-start";
110 let end = c"linux,initrd-end";
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000111
112 if let Some(chosen) = fdt.chosen()? {
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +0000113 match (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
114 (None, None) => {}
115 (Some(start), Some(end)) => {
116 return Ok(Some((start as usize)..(end as usize)));
117 }
118 _ => return Err(FdtError::NotFound),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000119 }
120 }
121
122 Ok(None)
123}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000124
Pierre-Clément Tosi3729f652024-11-19 15:25:37 +0000125/// Read /avf/untrusted/instance-id, if present.
126pub fn read_instance_id(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
127 read_avf_untrusted_prop(fdt, c"instance-id")
128}
129
130/// Read /avf/untrusted/defer-rollback-protection, if present.
131pub fn read_defer_rollback_protection(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
132 read_avf_untrusted_prop(fdt, c"defer-rollback-protection")
133}
134
135fn read_avf_untrusted_prop<'a>(fdt: &'a Fdt, prop: &CStr) -> libfdt::Result<Option<&'a [u8]>> {
136 if let Some(node) = fdt.node(c"/avf/untrusted")? {
137 node.getprop(prop)
138 } else {
139 Ok(None)
140 }
141}
142
Jiyong Park9c63cd12023-03-21 17:53:07 +0900143fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
144 let start = u32::try_from(initrd_range.start).unwrap();
145 let end = u32::try_from(initrd_range.end).unwrap();
146
147 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000148 node.setprop(c"linux,initrd-start", &start.to_be_bytes())?;
149 node.setprop(c"linux,initrd-end", &end.to_be_bytes())?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900150 Ok(())
151}
152
Jiyong Parke9d87e82023-03-21 19:28:40 +0900153fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
154 if let Some(chosen) = fdt.chosen()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000155 if let Some(bootargs) = chosen.getprop_str(c"bootargs")? {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900156 // We need to copy the string to heap because the original fdt will be invalidated
157 // by the templated DT
158 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
159 return Ok(Some(copy));
160 }
161 }
162 Ok(None)
163}
164
165fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
166 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900167 // This function is called before the verification is done. So, we just copy the bootargs to
168 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
169 // if the VM is not debuggable.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000170 node.setprop(c"bootargs", bootargs.to_bytes_with_nul())
Jiyong Parke9d87e82023-03-21 19:28:40 +0900171}
172
Alice Wang0d527472023-06-13 14:55:38 +0000173/// Reads and validates the memory range in the DT.
174///
175/// Only one memory range is expected with the crosvm setup for now.
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000176fn read_and_validate_memory_range(
177 fdt: &Fdt,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000178 alignment: usize,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000179) -> Result<Range<usize>, RebootReason> {
Alice Wang0d527472023-06-13 14:55:38 +0000180 let mut memory = fdt.memory().map_err(|e| {
181 error!("Failed to read memory range from DT: {e}");
182 RebootReason::InvalidFdt
183 })?;
184 let range = memory.next().ok_or_else(|| {
185 error!("The /memory node in the DT contains no range.");
186 RebootReason::InvalidFdt
187 })?;
188 if memory.next().is_some() {
189 warn!(
190 "The /memory node in the DT contains more than one memory range, \
191 while only one is expected."
192 );
193 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900194 let base = range.start;
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000195 if base % alignment != 0 {
196 error!("Memory base address {:#x} is not aligned to {:#x}", base, alignment);
197 return Err(RebootReason::InvalidFdt);
198 }
199 // For simplicity, force a hardcoded memory base, for now.
Alice Wange243d462023-06-06 15:18:12 +0000200 if base != MEM_START {
201 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000202 return Err(RebootReason::InvalidFdt);
203 }
204
Jiyong Park6a8789a2023-03-21 14:50:59 +0900205 let size = range.len();
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000206 if size % alignment != 0 {
207 error!("Memory size {:#x} is not aligned to {:#x}", size, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000208 return Err(RebootReason::InvalidFdt);
209 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000210
Jiyong Park6a8789a2023-03-21 14:50:59 +0900211 if size == 0 {
212 error!("Memory size is 0");
213 return Err(RebootReason::InvalidFdt);
214 }
Alice Wang0d527472023-06-13 14:55:38 +0000215 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000216}
217
Jiyong Park9c63cd12023-03-21 17:53:07 +0900218fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000219 let addr = u64::try_from(MEM_START).unwrap();
220 let size = u64::try_from(memory_range.len()).unwrap();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000221 fdt.node_mut(c"/memory")?
Jiyong Park0ee65392023-03-27 20:52:45 +0900222 .ok_or(FdtError::NotFound)?
Alan Stokesf46a17c2025-01-05 15:50:18 +0000223 .setprop_inplace(c"reg", [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900224}
225
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000226#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800227struct CpuInfo {
228 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800229 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800230}
231
232impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800233 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800234}
235
236fn read_opp_info_from(
237 opp_node: FdtNode,
238) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
239 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100240 let mut opp_nodes = opp_node.subnodes()?;
241 for subnode in opp_nodes.by_ref().take(table.capacity()) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000242 let prop = subnode.getprop_u64(c"opp-hz")?.ok_or(FdtError::NotFound)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800243 table.push(prop);
244 }
245
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100246 if opp_nodes.next().is_some() {
247 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
248 }
249
David Dai9bdb10c2024-02-01 22:42:54 -0800250 Ok(table)
251}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900252
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000253#[derive(Debug, Default)]
254struct ClusterTopology {
255 // TODO: Support multi-level clusters & threads.
256 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
257}
258
259impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700260 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000261}
262
263#[derive(Debug, Default)]
264struct CpuTopology {
265 // TODO: Support sockets.
266 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
267}
268
269impl CpuTopology {
270 const MAX_CLUSTERS: usize = 3;
271}
272
273fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000274 let Some(cpu_map) = fdt.node(c"/cpus/cpu-map")? else {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000275 return Ok(None);
276 };
277
278 let mut topology = BTreeMap::new();
279 for n in 0..CpuTopology::MAX_CLUSTERS {
280 let name = CString::new(format!("cluster{n}")).unwrap();
281 let Some(cluster) = cpu_map.subnode(&name)? else {
282 break;
283 };
284 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800285 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000286 let Some(core) = cluster.subnode(&name)? else {
287 break;
288 };
Alan Stokesf46a17c2025-01-05 15:50:18 +0000289 let cpu = core.getprop_u32(c"cpu")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000290 let prev = topology.insert(cpu.try_into()?, (n, m));
291 if prev.is_some() {
292 return Err(FdtError::BadValue);
293 }
294 }
295 }
296
297 Ok(Some(topology))
298}
299
300fn read_cpu_info_from(
301 fdt: &Fdt,
302) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000303 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000304
305 let cpu_map = read_cpu_map_from(fdt)?;
306 let mut topology: CpuTopology = Default::default();
307
Alan Stokesf46a17c2025-01-05 15:50:18 +0000308 let mut cpu_nodes = fdt.compatible_nodes(c"arm,armv8")?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000309 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000310 let cpu_capacity = cpu.getprop_u32(c"capacity-dmips-mhz")?;
311 let opp_phandle = cpu.getprop_u32(c"operating-points-v2")?;
David Dai9bdb10c2024-02-01 22:42:54 -0800312 let opptable_info = if let Some(phandle) = opp_phandle {
313 let phandle = phandle.try_into()?;
314 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
315 Some(read_opp_info_from(node)?)
316 } else {
317 None
318 };
David Dai50168a32024-02-14 17:00:48 -0800319 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000320 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000321
322 if let Some(ref cpu_map) = cpu_map {
323 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800324 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000325 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800326 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000327 return Err(FdtError::BadValue);
328 }
David Dai8f476cb2024-02-15 21:57:01 -0800329 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000330 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900331 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000332
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000333 if cpu_nodes.next().is_some() {
334 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
335 }
336
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000337 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900338}
339
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000340fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
341 if cpus.is_empty() {
342 return Err(FdtValidationError::InvalidCpuCount(0));
343 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000344 Ok(())
345}
346
David Dai9bdb10c2024-02-01 22:42:54 -0800347fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000348 let mut nodes = fdt.compatible_nodes(c"virtual,android-v-only-cpufreq")?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000349 let Some(node) = nodes.next() else {
350 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800351 };
352
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000353 if nodes.next().is_some() {
354 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
355 }
356
357 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
358 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000359 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000360
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000361 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800362}
363
364fn validate_vcpufreq_info(
365 vcpufreq_info: &VcpufreqInfo,
366 cpus: &[CpuInfo],
367) -> Result<(), FdtValidationError> {
368 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000369 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800370
371 let base = vcpufreq_info.addr;
372 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000373 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
374
375 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800376 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000377 }
David Dai9bdb10c2024-02-01 22:42:54 -0800378
379 Ok(())
380}
381
382fn patch_opptable(
383 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800384 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800385) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000386 let oppcompat = c"operating-points-v2";
David Dai9bdb10c2024-02-01 22:42:54 -0800387 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000388
389 let Some(opptable) = opptable else {
390 return next.nop();
391 };
392
David Dai9bdb10c2024-02-01 22:42:54 -0800393 let mut next_subnode = next.first_subnode()?;
394
395 for entry in opptable {
396 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000397 subnode.setprop_inplace(c"opp-hz", &entry.to_be_bytes())?;
David Dai9bdb10c2024-02-01 22:42:54 -0800398 next_subnode = subnode.next_subnode()?;
399 }
400
401 while let Some(current) = next_subnode {
402 next_subnode = current.delete_and_next_subnode()?;
403 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000404
David Dai9bdb10c2024-02-01 22:42:54 -0800405 Ok(())
406}
407
408// TODO(ptosi): Rework FdtNodeMut and replace this function.
409fn get_nth_compatible<'a>(
410 fdt: &'a mut Fdt,
411 n: usize,
412 compat: &CStr,
413) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000414 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800415 for _ in 0..n {
416 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
417 }
418 Ok(node)
419}
420
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000421fn patch_cpus(
422 fdt: &mut Fdt,
423 cpus: &[CpuInfo],
424 topology: &Option<CpuTopology>,
425) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000426 const COMPAT: &CStr = c"arm,armv8";
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000427 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800428 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800429 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000430 let phandle = cur.as_node().get_phandle()?.unwrap();
431 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800432 if let Some(cpu_capacity) = cpu.cpu_capacity {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000433 cur.setprop_inplace(c"capacity-dmips-mhz", &cpu_capacity.to_be_bytes())?;
David Dai50168a32024-02-14 17:00:48 -0800434 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000435 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900436 }
David Dai9bdb10c2024-02-01 22:42:54 -0800437 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900438 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000439 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900440 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000441
442 if let Some(topology) = topology {
443 for (n, cluster) in topology.clusters.iter().enumerate() {
444 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
445 let cluster_node = fdt.node_mut(&path)?.unwrap();
446 if let Some(cluster) = cluster {
447 let mut iter = cluster_node.first_subnode()?;
448 for core in cluster.cores {
449 let mut core_node = iter.unwrap();
450 iter = if let Some(core_idx) = core {
451 let phandle = *cpu_phandles.get(core_idx).unwrap();
452 let value = u32::from(phandle).to_be_bytes();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000453 core_node.setprop_inplace(c"cpu", &value)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000454 core_node.next_subnode()?
455 } else {
456 core_node.delete_and_next_subnode()?
457 };
458 }
459 assert!(iter.is_none());
460 } else {
461 cluster_node.nop()?;
462 }
463 }
464 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000465 fdt.node_mut(c"/cpus/cpu-map")?.unwrap().nop()?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000466 }
467
Jiyong Park6a8789a2023-03-21 14:50:59 +0900468 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000469}
470
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000471/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
472/// the guest that don't require being validated by pvmfw.
473fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
474 let mut props = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000475 if let Some(node) = fdt.node(c"/avf/untrusted")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000476 for property in node.properties()? {
477 let name = property.name()?;
478 let value = property.value()?;
479 props.insert(CString::from(name), value.to_vec());
480 }
481 if node.subnodes()?.next().is_some() {
482 warn!("Discarding unexpected /avf/untrusted subnodes.");
483 }
484 }
485
486 Ok(props)
487}
488
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900489/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900490fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900491 let mut property_map = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000492 if let Some(avf_node) = fdt.node(c"/avf")? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900493 for property in avf_node.properties()? {
494 let name = property.name()?;
495 let value = property.value()?;
496 property_map.insert(
497 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
498 value.to_vec(),
499 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900500 }
501 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900502 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900503}
504
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000505fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000506 const FORBIDDEN_PROPS: &[&CStr] = &[c"compatible", c"linux,phandle", c"phandle"];
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000507
508 for name in FORBIDDEN_PROPS {
509 if props.contains_key(*name) {
510 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
511 }
512 }
513
514 Ok(())
515}
516
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900517/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
518/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
519fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900520 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900521 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900522 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900523) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000524 let root_vm_dt = vm_dt.root_mut();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000525 let mut avf_vm_dt = root_vm_dt.add_subnode(c"avf")?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900526 // TODO(b/318431677): Validate nodes beyond /avf.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000527 let avf_node = vm_ref_dt.node(c"/avf")?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900528 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900529 if let Some(ref_value) = avf_node.getprop(name)? {
530 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900531 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900532 "Property mismatches while applying overlay VM reference DT. \
533 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
534 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900535 );
536 return Err(FdtError::BadValue);
537 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900538 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900539 }
540 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900541 Ok(())
542}
543
Jiyong Park00ceff32023-03-13 05:43:23 +0000544#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000545struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900546 ranges: [PciAddrRange; 2],
547 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
548 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000549}
550
Jiyong Park6a8789a2023-03-21 14:50:59 +0900551impl PciInfo {
552 const IRQ_MASK_CELLS: usize = 4;
553 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe2d0969c2024-06-06 12:59:12 +0000554 const MAX_IRQS: usize = 16;
Jiyong Park00ceff32023-03-13 05:43:23 +0000555}
556
Jiyong Park6a8789a2023-03-21 14:50:59 +0900557type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
558type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
559type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000560
561/// Iterator that takes N cells as a chunk
562struct CellChunkIterator<'a, const N: usize> {
563 cells: CellIterator<'a>,
564}
565
566impl<'a, const N: usize> CellChunkIterator<'a, N> {
567 fn new(cells: CellIterator<'a>) -> Self {
568 Self { cells }
569 }
570}
571
Chris Wailes52358e92025-01-27 17:04:40 -0800572impl<const N: usize> Iterator for CellChunkIterator<'_, N> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000573 type Item = [u32; N];
574 fn next(&mut self) -> Option<Self::Item> {
575 let mut ret: Self::Item = [0; N];
576 for i in ret.iter_mut() {
577 *i = self.cells.next()?;
578 }
579 Some(ret)
580 }
581}
582
Jiyong Park6a8789a2023-03-21 14:50:59 +0900583/// Read pci host controller ranges, irq maps, and irq map masks from DT
584fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000585 let node = fdt.compatible_nodes(c"pci-host-cam-generic")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900586
587 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
588 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
589 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
590
Alan Stokesf46a17c2025-01-05 15:50:18 +0000591 let irq_masks = node.getprop_cells(c"interrupt-map-mask")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000592 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
593 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
594
595 if chunks.next().is_some() {
596 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
597 return Err(FdtError::NoSpace);
598 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900599
Alan Stokesf46a17c2025-01-05 15:50:18 +0000600 let irq_maps = node.getprop_cells(c"interrupt-map")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000601 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
602 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
603
604 if chunks.next().is_some() {
605 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
606 return Err(FdtError::NoSpace);
607 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900608
609 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
610}
611
Jiyong Park0ee65392023-03-27 20:52:45 +0900612fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900613 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900614 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900615 }
616 for irq_mask in pci_info.irq_masks.iter() {
617 validate_pci_irq_mask(irq_mask)?;
618 }
619 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
620 validate_pci_irq_map(irq_map, idx)?;
621 }
622 Ok(())
623}
624
Jiyong Park0ee65392023-03-27 20:52:45 +0900625fn validate_pci_addr_range(
626 range: &PciAddrRange,
627 memory_range: &Range<usize>,
628) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900629 let mem_flags = PciMemoryFlags(range.addr.0);
630 let range_type = mem_flags.range_type();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900631 let bus_addr = range.addr.1;
632 let cpu_addr = range.parent_addr;
633 let size = range.size;
634
635 if range_type != PciRangeType::Memory64 {
636 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
637 return Err(RebootReason::InvalidFdt);
638 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639 // Enforce ID bus-to-cpu mappings, as used by crosvm.
640 if bus_addr != cpu_addr {
641 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
642 return Err(RebootReason::InvalidFdt);
643 }
644
Jiyong Park0ee65392023-03-27 20:52:45 +0900645 let Some(bus_end) = bus_addr.checked_add(size) else {
646 error!("PCI address range size {:#x} overflows", size);
647 return Err(RebootReason::InvalidFdt);
648 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000649 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900650 error!("PCI address end {:#x} is outside of translatable range", bus_end);
651 return Err(RebootReason::InvalidFdt);
652 }
653
654 let memory_start = memory_range.start.try_into().unwrap();
655 let memory_end = memory_range.end.try_into().unwrap();
656
657 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
658 error!(
659 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
660 bus_addr, bus_end, memory_start, memory_end
661 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900662 return Err(RebootReason::InvalidFdt);
663 }
664
665 Ok(())
666}
667
668fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000669 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
670 const IRQ_MASK_ADDR_ME: u32 = 0x0;
671 const IRQ_MASK_ADDR_LO: u32 = 0x0;
672 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900673 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000674 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900675 if *irq_mask != EXPECTED {
676 error!("Invalid PCI irq mask {:#?}", irq_mask);
677 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000678 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900679 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000680}
681
Jiyong Park6a8789a2023-03-21 14:50:59 +0900682fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000683 const PCI_DEVICE_IDX: usize = 11;
684 const PCI_IRQ_ADDR_ME: u32 = 0;
685 const PCI_IRQ_ADDR_LO: u32 = 0;
686 const PCI_IRQ_INTC: u32 = 1;
687 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
688 const GIC_SPI: u32 = 0;
689 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
690
Jiyong Park6a8789a2023-03-21 14:50:59 +0900691 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
692 let pci_irq_number = irq_map[3];
693 let _controller_phandle = irq_map[4]; // skipped.
694 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
695 // interrupt-cells is <3> for GIC
696 let gic_peripheral_interrupt_type = irq_map[7];
697 let gic_irq_number = irq_map[8];
698 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000699
Jiyong Park6a8789a2023-03-21 14:50:59 +0900700 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
701 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000702
Jiyong Park6a8789a2023-03-21 14:50:59 +0900703 if pci_addr != expected_pci_addr {
704 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
705 {:#x} {:#x} {:#x}",
706 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
707 return Err(RebootReason::InvalidFdt);
708 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000709
Jiyong Park6a8789a2023-03-21 14:50:59 +0900710 if pci_irq_number != PCI_IRQ_INTC {
711 error!(
712 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
713 pci_irq_number, PCI_IRQ_INTC
714 );
715 return Err(RebootReason::InvalidFdt);
716 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000717
Jiyong Park6a8789a2023-03-21 14:50:59 +0900718 if gic_addr != (0, 0) {
719 error!(
720 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
721 {:#x} {:#x}",
722 gic_addr.0, gic_addr.1, 0, 0
723 );
724 return Err(RebootReason::InvalidFdt);
725 }
726
727 if gic_peripheral_interrupt_type != GIC_SPI {
728 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
729 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
730 return Err(RebootReason::InvalidFdt);
731 }
732
733 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
734 if gic_irq_number != irq_nr {
735 error!(
736 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
737 gic_irq_number, irq_nr
738 );
739 return Err(RebootReason::InvalidFdt);
740 }
741
742 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
743 error!(
744 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
745 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
746 );
747 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000748 }
749 Ok(())
750}
751
Jiyong Park9c63cd12023-03-21 17:53:07 +0900752fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000753 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000754 fdt.root_mut().next_compatible(c"pci-host-cam-generic")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900755
756 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000757 node.trimprop(c"interrupt-map-mask", irq_masks_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900758
759 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000760 node.trimprop(c"interrupt-map", irq_maps_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900761
762 node.setprop_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000763 c"ranges",
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000764 [pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()].as_flattened(),
Jiyong Park9c63cd12023-03-21 17:53:07 +0900765 )
766}
767
Jiyong Park00ceff32023-03-13 05:43:23 +0000768#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900769struct SerialInfo {
770 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000771}
772
773impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900774 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000775}
776
Jiyong Park6a8789a2023-03-21 14:50:59 +0900777fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000778 let mut addrs = ArrayVec::new();
779
Alan Stokesf46a17c2025-01-05 15:50:18 +0000780 let mut serial_nodes = fdt.compatible_nodes(c"ns16550a")?;
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000781 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000782 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900783 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000784 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000785 if serial_nodes.next().is_some() {
786 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
787 }
788
Jiyong Park6a8789a2023-03-21 14:50:59 +0900789 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000790}
791
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000792#[derive(Default, Debug, PartialEq)]
793struct WdtInfo {
794 addr: u64,
795 size: u64,
796 irq: [u32; WdtInfo::IRQ_CELLS],
797}
798
799impl WdtInfo {
800 const IRQ_CELLS: usize = 3;
801 const IRQ_NR: u32 = 0xf;
802 const ADDR: u64 = 0x3000;
803 const SIZE: u64 = 0x1000;
804 const GIC_PPI: u32 = 1;
805 const IRQ_TYPE_EDGE_RISING: u32 = 1;
806 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100807 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000808 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
809
810 const fn get_expected(num_cpus: usize) -> Self {
811 Self {
812 addr: Self::ADDR,
813 size: Self::SIZE,
814 irq: [
815 Self::GIC_PPI,
816 Self::IRQ_NR,
817 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
818 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
819 | Self::IRQ_TYPE_EDGE_RISING,
820 ],
821 }
822 }
823}
824
825fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000826 let mut node_iter = fdt.compatible_nodes(c"qemu,vcpu-stall-detector")?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000827 let node = node_iter.next().ok_or(FdtError::NotFound)?;
828 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
829
830 let reg = ranges.next().ok_or(FdtError::NotFound)?;
831 let size = reg.size.ok_or(FdtError::NotFound)?;
832 if ranges.next().is_some() {
833 warn!("Discarding extra vmwdt <reg> entries.");
834 }
835
Alan Stokesf46a17c2025-01-05 15:50:18 +0000836 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000837 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
838 let irq = chunks.next().ok_or(FdtError::NotFound)?;
839
840 if chunks.next().is_some() {
841 warn!("Discarding extra vmwdt <interrupts> entries.");
842 }
843
844 Ok(WdtInfo { addr: reg.addr, size, irq })
845}
846
847fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
848 if *wdt != WdtInfo::get_expected(num_cpus) {
849 error!("Invalid watchdog timer: {wdt:?}");
850 return Err(RebootReason::InvalidFdt);
851 }
852
853 Ok(())
854}
855
856fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
857 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
858 for v in interrupts.iter_mut() {
859 *v = v.to_be();
860 }
861
862 let mut node = fdt
863 .root_mut()
Alan Stokesf46a17c2025-01-05 15:50:18 +0000864 .next_compatible(c"qemu,vcpu-stall-detector")?
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000865 .ok_or(libfdt::FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000866 node.setprop_inplace(c"interrupts", interrupts.as_bytes())?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000867 Ok(())
868}
869
Jiyong Park9c63cd12023-03-21 17:53:07 +0900870/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
871fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000872 let name = c"ns16550a";
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000873 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900874 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000875 let reg =
876 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900877 next = if !serial_info.addrs.contains(&reg.addr) {
878 current.delete_and_next_compatible(name)
879 } else {
880 current.next_compatible(name)
881 }
882 }
883 Ok(())
884}
885
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700886fn validate_swiotlb_info(
887 swiotlb_info: &SwiotlbInfo,
888 memory: &Range<usize>,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000889 alignment: usize,
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700890) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900891 let size = swiotlb_info.size;
892 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000893
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000894 if size == 0 || (size % alignment) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000895 error!("Invalid swiotlb size {:#x}", size);
896 return Err(RebootReason::InvalidFdt);
897 }
898
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000899 if let Some(align) = align.filter(|&a| a % alignment != 0) {
900 error!("Swiotlb alignment {:#x} not aligned to {:#x}", align, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000901 return Err(RebootReason::InvalidFdt);
902 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700903
Alice Wang9cfbfd62023-06-14 11:19:03 +0000904 if let Some(addr) = swiotlb_info.addr {
905 if addr.checked_add(size).is_none() {
906 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
907 return Err(RebootReason::InvalidFdt);
908 }
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000909 if (addr % alignment) != 0 {
910 error!("Swiotlb address {:#x} not aligned to {:#x}", addr, alignment);
911 return Err(RebootReason::InvalidFdt);
912 }
Alice Wang9cfbfd62023-06-14 11:19:03 +0000913 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700914 if let Some(range) = swiotlb_info.fixed_range() {
915 if !range.is_within(memory) {
916 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
917 return Err(RebootReason::InvalidFdt);
918 }
919 }
920
Jiyong Park6a8789a2023-03-21 14:50:59 +0900921 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000922}
923
Jiyong Park9c63cd12023-03-21 17:53:07 +0900924fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
925 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000926 fdt.root_mut().next_compatible(c"restricted-dma-pool")?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700927
928 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000929 node.setprop_addrrange_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000930 c"reg",
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700931 range.start.try_into().unwrap(),
932 range.len().try_into().unwrap(),
933 )?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000934 node.nop_property(c"size")?;
935 node.nop_property(c"alignment")?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700936 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000937 node.nop_property(c"reg")?;
938 node.setprop_inplace(c"size", &swiotlb_info.size.to_be_bytes())?;
939 node.setprop_inplace(c"alignment", &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700940 }
941
Jiyong Park9c63cd12023-03-21 17:53:07 +0900942 Ok(())
943}
944
945fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000946 let node = fdt.compatible_nodes(c"arm,gic-v3")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900947 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
948 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
949 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
950
951 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000952 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
953 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000954 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900955
956 // range1 is just below range0
957 range1.addr = addr - size;
958 range1.size = Some(size);
959
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000960 let (addr0, size0) = range0.to_cells();
961 let (addr1, size1) = range1.to_cells();
962 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900963
Alan Stokesf46a17c2025-01-05 15:50:18 +0000964 let mut node = fdt.root_mut().next_compatible(c"arm,gic-v3")?.ok_or(FdtError::NotFound)?;
965 node.setprop_inplace(c"reg", value.as_flattened())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900966}
967
968fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
969 const NUM_INTERRUPTS: usize = 4;
970 const CELLS_PER_INTERRUPT: usize = 3;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000971 let node = fdt.compatible_nodes(c"arm,armv8-timer")?.next().ok_or(FdtError::NotFound)?;
972 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900973 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
974 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
975
976 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100977 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900978 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000979
Jiyong Park9c63cd12023-03-21 17:53:07 +0900980 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
981 *v |= cpu_mask;
982 }
983 for v in value.iter_mut() {
984 *v = v.to_be();
985 }
986
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000987 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900988
Alan Stokesf46a17c2025-01-05 15:50:18 +0000989 let mut node = fdt.root_mut().next_compatible(c"arm,armv8-timer")?.ok_or(FdtError::NotFound)?;
990 node.setprop_inplace(c"interrupts", value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900991}
992
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000993fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000994 let avf_node = if let Some(node) = fdt.node_mut(c"/avf")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000995 node
996 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000997 fdt.root_mut().add_subnode(c"avf")?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000998 };
999
1000 // The node shouldn't already be present; if it is, return the error.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001001 let mut node = avf_node.add_subnode(c"untrusted")?;
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001002
1003 for (name, value) in props {
1004 node.setprop(name, value)?;
1005 }
1006
1007 Ok(())
1008}
1009
Jiyong Park00ceff32023-03-13 05:43:23 +00001010#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -08001011struct VcpufreqInfo {
1012 addr: u64,
1013 size: u64,
1014}
1015
1016fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001017 let mut node = fdt.node_mut(c"/cpufreq")?.unwrap();
David Dai9bdb10c2024-02-01 22:42:54 -08001018 if let Some(info) = vcpufreq_info {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001019 node.setprop_addrrange_inplace(c"reg", info.addr, info.size)
David Dai9bdb10c2024-02-01 22:42:54 -08001020 } else {
1021 node.nop()
1022 }
1023}
1024
1025#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +09001026pub struct DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001027 pub initrd_range: Option<Range<usize>>,
1028 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001029 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001030 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001031 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001032 pci_info: PciInfo,
1033 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -07001034 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001035 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001036 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001037 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001038 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001039}
1040
1041impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001042 const MAX_CPUS: usize = 16;
1043
1044 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001045 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1046
1047 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1048 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001049}
1050
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001051pub fn sanitize_device_tree(
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +00001052 fdt: &mut Fdt,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001053 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001054 vm_ref_dt: Option<&[u8]>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001055 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001056 hyp_page_size: Option<usize>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001057) -> Result<DeviceTreeInfo, RebootReason> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001058 let vm_dtbo = match vm_dtbo {
1059 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1060 error!("Failed to load VM DTBO: {e}");
1061 RebootReason::InvalidFdt
1062 })?),
1063 None => None,
1064 };
1065
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001066 let info = parse_device_tree(fdt, vm_dtbo.as_deref(), guest_page_size, hyp_page_size)?;
Jiyong Park83316122023-03-21 09:39:39 +09001067
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +00001068 fdt.clone_from(FDT_TEMPLATE).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001069 error!("Failed to instantiate FDT from the template DT: {e}");
1070 RebootReason::InvalidFdt
1071 })?;
1072
Jaewan Kim9220e852023-12-01 10:58:40 +09001073 fdt.unpack().map_err(|e| {
1074 error!("Failed to unpack DT for patching: {e}");
1075 RebootReason::InvalidFdt
1076 })?;
1077
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001078 if let Some(device_assignment_info) = &info.device_assignment {
1079 let vm_dtbo = vm_dtbo.unwrap();
1080 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1081 error!("Failed to filter VM DTBO: {e}");
1082 RebootReason::InvalidFdt
1083 })?;
1084 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1085 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1086 // it can only be instantiated after validation.
1087 unsafe {
1088 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1089 error!("Failed to apply filtered VM DTBO: {e}");
1090 RebootReason::InvalidFdt
1091 })?;
1092 }
1093 }
1094
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001095 if let Some(vm_ref_dt) = vm_ref_dt {
1096 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1097 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001098 RebootReason::InvalidFdt
1099 })?;
1100
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001101 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1102 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001103 RebootReason::InvalidFdt
1104 })?;
1105 }
1106
Jiyong Park9c63cd12023-03-21 17:53:07 +09001107 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001108
Jaewan Kim19b984f2023-12-04 15:16:50 +09001109 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1110
Jaewan Kim9220e852023-12-01 10:58:40 +09001111 fdt.pack().map_err(|e| {
1112 error!("Failed to unpack DT after patching: {e}");
1113 RebootReason::InvalidFdt
1114 })?;
1115
Jiyong Park6a8789a2023-03-21 14:50:59 +09001116 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001117}
1118
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001119fn parse_device_tree(
1120 fdt: &Fdt,
1121 vm_dtbo: Option<&VmDtbo>,
1122 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001123 hyp_page_size: Option<usize>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001124) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001125 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1126 error!("Failed to read initrd range from DT: {e}");
1127 RebootReason::InvalidFdt
1128 })?;
1129
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001130 // Ensure that MMIO_GUARD can't be used to inadvertently map some memory as MMIO.
1131 let memory_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001132 let memory_range = read_and_validate_memory_range(fdt, memory_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001133
Jiyong Parke9d87e82023-03-21 19:28:40 +09001134 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1135 error!("Failed to read bootargs from DT: {e}");
1136 RebootReason::InvalidFdt
1137 })?;
1138
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001139 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001140 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001141 RebootReason::InvalidFdt
1142 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001143 validate_cpu_info(&cpus).map_err(|e| {
1144 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001145 RebootReason::InvalidFdt
1146 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001147
David Dai9bdb10c2024-02-01 22:42:54 -08001148 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1149 error!("Failed to read vcpufreq info from DT: {e}");
1150 RebootReason::InvalidFdt
1151 })?;
1152 if let Some(ref info) = vcpufreq_info {
1153 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1154 error!("Failed to validate vcpufreq info from DT: {e}");
1155 RebootReason::InvalidFdt
1156 })?;
1157 }
1158
Jiyong Park6a8789a2023-03-21 14:50:59 +09001159 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1160 error!("Failed to read pci info from DT: {e}");
1161 RebootReason::InvalidFdt
1162 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001163 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001164
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001165 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1166 error!("Failed to read vCPU stall detector info from DT: {e}");
1167 RebootReason::InvalidFdt
1168 })?;
1169 validate_wdt_info(&wdt_info, cpus.len())?;
1170
Jiyong Park6a8789a2023-03-21 14:50:59 +09001171 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1172 error!("Failed to read serial info from DT: {e}");
1173 RebootReason::InvalidFdt
1174 })?;
1175
Pierre-Clément Tosi3c5e7a72024-11-27 20:12:37 +00001176 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt)
1177 .map_err(|e| {
1178 error!("Failed to read swiotlb info from DT: {e}");
1179 RebootReason::InvalidFdt
1180 })?
1181 .ok_or_else(|| {
1182 error!("Swiotlb info missing from DT");
1183 RebootReason::InvalidFdt
1184 })?;
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001185 // Ensure that MEM_SHARE won't inadvertently map beyond the shared region.
1186 let swiotlb_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001187 validate_swiotlb_info(&swiotlb_info, &memory_range, swiotlb_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001188
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001189 let device_assignment = if let Some(vm_dtbo) = vm_dtbo {
1190 if let Some(hypervisor) = get_device_assigner() {
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001191 let granule = hyp_page_size.ok_or_else(|| {
1192 error!("No granule found during device assignment validation");
1193 RebootReason::InternalError
1194 })?;
1195
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001196 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor, granule).map_err(|e| {
1197 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1198 RebootReason::InvalidFdt
1199 })?
1200 } else {
1201 warn!("Device assignment is ignored because device assigning hypervisor is missing");
1202 None
Jaewan Kim52477ae2023-11-21 21:20:52 +09001203 }
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001204 } else {
1205 None
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001206 };
1207
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001208 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1209 error!("Failed to read untrusted properties: {e}");
1210 RebootReason::InvalidFdt
1211 })?;
1212 validate_untrusted_props(&untrusted_props).map_err(|e| {
1213 error!("Failed to validate untrusted properties: {e}");
1214 RebootReason::InvalidFdt
1215 })?;
1216
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001217 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001218 error!("Failed to read names of properties under /avf from DT: {e}");
1219 RebootReason::InvalidFdt
1220 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001221
Jiyong Park00ceff32023-03-13 05:43:23 +00001222 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001223 initrd_range,
1224 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001225 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001226 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001227 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001228 pci_info,
1229 serial_info,
1230 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001231 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001232 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001233 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001234 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001235 })
1236}
1237
Jiyong Park9c63cd12023-03-21 17:53:07 +09001238fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1239 if let Some(initrd_range) = &info.initrd_range {
1240 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1241 error!("Failed to patch initrd range to DT: {e}");
1242 RebootReason::InvalidFdt
1243 })?;
1244 }
1245 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1246 error!("Failed to patch memory range to DT: {e}");
1247 RebootReason::InvalidFdt
1248 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001249 if let Some(bootargs) = &info.bootargs {
1250 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1251 error!("Failed to patch bootargs to DT: {e}");
1252 RebootReason::InvalidFdt
1253 })?;
1254 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001255 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001256 error!("Failed to patch cpus to DT: {e}");
1257 RebootReason::InvalidFdt
1258 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001259 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1260 error!("Failed to patch vcpufreq info to DT: {e}");
1261 RebootReason::InvalidFdt
1262 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001263 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1264 error!("Failed to patch pci info to DT: {e}");
1265 RebootReason::InvalidFdt
1266 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001267 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1268 error!("Failed to patch wdt info to DT: {e}");
1269 RebootReason::InvalidFdt
1270 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001271 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1272 error!("Failed to patch serial info to DT: {e}");
1273 RebootReason::InvalidFdt
1274 })?;
1275 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1276 error!("Failed to patch swiotlb info to DT: {e}");
1277 RebootReason::InvalidFdt
1278 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001279 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001280 error!("Failed to patch gic info to DT: {e}");
1281 RebootReason::InvalidFdt
1282 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001283 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001284 error!("Failed to patch timer info to DT: {e}");
1285 RebootReason::InvalidFdt
1286 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001287 if let Some(device_assignment) = &info.device_assignment {
1288 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1289 // then VM DTBO's underlying slice is allocated.
1290 device_assignment.patch(fdt).map_err(|e| {
1291 error!("Failed to patch device assignment info to DT: {e}");
1292 RebootReason::InvalidFdt
1293 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001294 } else {
1295 device_assignment::clean(fdt).map_err(|e| {
1296 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1297 RebootReason::InvalidFdt
1298 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001299 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001300 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1301 error!("Failed to patch untrusted properties: {e}");
1302 RebootReason::InvalidFdt
1303 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001304
Jiyong Park9c63cd12023-03-21 17:53:07 +09001305 Ok(())
1306}
1307
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001308/// Modifies the input DT according to the fields of the configuration.
1309pub fn modify_for_next_stage(
1310 fdt: &mut Fdt,
1311 bcc: &[u8],
1312 new_instance: bool,
1313 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001314 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001315 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001316 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001317) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001318 if let Some(debug_policy) = debug_policy {
1319 let backup = Vec::from(fdt.as_slice());
1320 fdt.unpack()?;
1321 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1322 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1323 info!("Debug policy applied.");
1324 } else {
1325 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1326 fdt.unpack()?;
1327 }
1328 } else {
1329 info!("No debug policy found.");
1330 fdt.unpack()?;
1331 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001332
Jiyong Parke9d87e82023-03-21 19:28:40 +09001333 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001334
Alice Wang56ec45b2023-06-15 08:30:32 +00001335 if let Some(mut chosen) = fdt.chosen_mut()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001336 empty_or_delete_prop(&mut chosen, c"avf,strict-boot", strict_boot)?;
1337 empty_or_delete_prop(&mut chosen, c"avf,new-instance", new_instance)?;
1338 chosen.setprop_inplace(c"kaslr-seed", &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001339 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001340 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001341 if let Some(bootargs) = read_bootargs_from(fdt)? {
1342 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1343 }
1344 }
1345
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001346 fdt.pack()?;
1347
1348 Ok(())
1349}
1350
Jiyong Parke9d87e82023-03-21 19:28:40 +09001351/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1352fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001353 // We reject DTs with missing reserved-memory node as validation should have checked that the
1354 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001355 let node = fdt.node_mut(c"/reserved-memory")?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001356
Alan Stokesf46a17c2025-01-05 15:50:18 +00001357 let mut node = node.next_compatible(c"google,open-dice")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001358
Jiyong Parke9d87e82023-03-21 19:28:40 +09001359 let addr: u64 = addr.try_into().unwrap();
1360 let size: u64 = size.try_into().unwrap();
Alan Stokesf46a17c2025-01-05 15:50:18 +00001361 node.setprop_inplace(c"reg", [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001362}
1363
Alice Wang56ec45b2023-06-15 08:30:32 +00001364fn empty_or_delete_prop(
1365 fdt_node: &mut FdtNodeMut,
1366 prop_name: &CStr,
1367 keep_prop: bool,
1368) -> libfdt::Result<()> {
1369 if keep_prop {
1370 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001371 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001372 fdt_node
1373 .delprop(prop_name)
1374 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001375 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001376}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001377
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001378/// Apply the debug policy overlay to the guest DT.
1379///
1380/// 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 +00001381fn apply_debug_policy(
1382 fdt: &mut Fdt,
1383 backup_fdt: &Fdt,
1384 debug_policy: &[u8],
1385) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001386 let mut debug_policy = Vec::from(debug_policy);
1387 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001388 Ok(overlay) => overlay,
1389 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001390 warn!("Corrupted debug policy found: {e}. Not applying.");
1391 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001392 }
1393 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001394
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001395 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001396 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001397 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001398 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001399 // A successful restoration is considered success because an invalid debug policy
1400 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001401 Ok(false)
1402 } else {
1403 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001404 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001405}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001406
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001407fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001408 if let Some(node) = fdt.node(c"/avf/guest/common")? {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001409 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1410 return Ok(value == 1);
1411 }
1412 }
1413 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1414}
1415
1416fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001417 let has_crashkernel = has_common_debug_policy(fdt, c"ramdump")?;
1418 let has_console = has_common_debug_policy(fdt, c"log")?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001419
1420 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1421 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1422 ("crashkernel", Box::new(|_| has_crashkernel)),
1423 ("console", Box::new(|_| has_console)),
1424 ];
1425
1426 // parse and filter out unwanted
1427 let mut filtered = Vec::new();
1428 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1429 info!("Invalid bootarg: {e}");
1430 FdtError::BadValue
1431 })? {
1432 match accepted.iter().find(|&t| t.0 == arg.name()) {
1433 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1434 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1435 }
1436 }
1437
1438 // flatten into a new C-string
1439 let mut new_bootargs = Vec::new();
1440 for (i, arg) in filtered.iter().enumerate() {
1441 if i != 0 {
1442 new_bootargs.push(b' '); // separator
1443 }
1444 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1445 }
1446 new_bootargs.push(b'\0');
1447
1448 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001449 node.setprop(c"bootargs", new_bootargs.as_slice())
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001450}