blob: 7c888d57f3e0898af7b6560004d0ebd28f5a0b95 [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
Jiyong Park6a8789a2023-03-21 14:50:59 +090081/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
82/// not an error.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +000083pub fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +000084 let addr = c"kernel-address";
85 let size = c"kernel-size";
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000086
Alan Stokesf46a17c2025-01-05 15:50:18 +000087 if let Some(config) = fdt.node(c"/config")? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000088 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
89 let addr = addr as usize;
90 let size = size as usize;
91
92 return Ok(Some(addr..(addr + size)));
93 }
94 }
95
96 Ok(None)
97}
98
Jiyong Park6a8789a2023-03-21 14:50:59 +090099/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
100/// error as there can be initrd-less VM.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +0000101pub fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000102 let start = c"linux,initrd-start";
103 let end = c"linux,initrd-end";
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000104
105 if let Some(chosen) = fdt.chosen()? {
106 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
107 return Ok(Some((start as usize)..(end as usize)));
108 }
109 }
110
111 Ok(None)
112}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000113
Pierre-Clément Tosi3729f652024-11-19 15:25:37 +0000114/// Read /avf/untrusted/instance-id, if present.
115pub fn read_instance_id(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
116 read_avf_untrusted_prop(fdt, c"instance-id")
117}
118
119/// Read /avf/untrusted/defer-rollback-protection, if present.
120pub fn read_defer_rollback_protection(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
121 read_avf_untrusted_prop(fdt, c"defer-rollback-protection")
122}
123
124fn read_avf_untrusted_prop<'a>(fdt: &'a Fdt, prop: &CStr) -> libfdt::Result<Option<&'a [u8]>> {
125 if let Some(node) = fdt.node(c"/avf/untrusted")? {
126 node.getprop(prop)
127 } else {
128 Ok(None)
129 }
130}
131
Jiyong Park9c63cd12023-03-21 17:53:07 +0900132fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
133 let start = u32::try_from(initrd_range.start).unwrap();
134 let end = u32::try_from(initrd_range.end).unwrap();
135
136 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000137 node.setprop(c"linux,initrd-start", &start.to_be_bytes())?;
138 node.setprop(c"linux,initrd-end", &end.to_be_bytes())?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900139 Ok(())
140}
141
Jiyong Parke9d87e82023-03-21 19:28:40 +0900142fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
143 if let Some(chosen) = fdt.chosen()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000144 if let Some(bootargs) = chosen.getprop_str(c"bootargs")? {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900145 // We need to copy the string to heap because the original fdt will be invalidated
146 // by the templated DT
147 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
148 return Ok(Some(copy));
149 }
150 }
151 Ok(None)
152}
153
154fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
155 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900156 // This function is called before the verification is done. So, we just copy the bootargs to
157 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
158 // if the VM is not debuggable.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000159 node.setprop(c"bootargs", bootargs.to_bytes_with_nul())
Jiyong Parke9d87e82023-03-21 19:28:40 +0900160}
161
Alice Wang0d527472023-06-13 14:55:38 +0000162/// Reads and validates the memory range in the DT.
163///
164/// Only one memory range is expected with the crosvm setup for now.
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000165fn read_and_validate_memory_range(
166 fdt: &Fdt,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000167 alignment: usize,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000168) -> Result<Range<usize>, RebootReason> {
Alice Wang0d527472023-06-13 14:55:38 +0000169 let mut memory = fdt.memory().map_err(|e| {
170 error!("Failed to read memory range from DT: {e}");
171 RebootReason::InvalidFdt
172 })?;
173 let range = memory.next().ok_or_else(|| {
174 error!("The /memory node in the DT contains no range.");
175 RebootReason::InvalidFdt
176 })?;
177 if memory.next().is_some() {
178 warn!(
179 "The /memory node in the DT contains more than one memory range, \
180 while only one is expected."
181 );
182 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900183 let base = range.start;
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000184 if base % alignment != 0 {
185 error!("Memory base address {:#x} is not aligned to {:#x}", base, alignment);
186 return Err(RebootReason::InvalidFdt);
187 }
188 // For simplicity, force a hardcoded memory base, for now.
Alice Wange243d462023-06-06 15:18:12 +0000189 if base != MEM_START {
190 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000191 return Err(RebootReason::InvalidFdt);
192 }
193
Jiyong Park6a8789a2023-03-21 14:50:59 +0900194 let size = range.len();
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000195 if size % alignment != 0 {
196 error!("Memory size {:#x} is not aligned to {:#x}", size, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000197 return Err(RebootReason::InvalidFdt);
198 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000199
Jiyong Park6a8789a2023-03-21 14:50:59 +0900200 if size == 0 {
201 error!("Memory size is 0");
202 return Err(RebootReason::InvalidFdt);
203 }
Alice Wang0d527472023-06-13 14:55:38 +0000204 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000205}
206
Jiyong Park9c63cd12023-03-21 17:53:07 +0900207fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000208 let addr = u64::try_from(MEM_START).unwrap();
209 let size = u64::try_from(memory_range.len()).unwrap();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000210 fdt.node_mut(c"/memory")?
Jiyong Park0ee65392023-03-27 20:52:45 +0900211 .ok_or(FdtError::NotFound)?
Alan Stokesf46a17c2025-01-05 15:50:18 +0000212 .setprop_inplace(c"reg", [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900213}
214
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000215#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800216struct CpuInfo {
217 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800218 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800219}
220
221impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800222 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800223}
224
225fn read_opp_info_from(
226 opp_node: FdtNode,
227) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
228 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100229 let mut opp_nodes = opp_node.subnodes()?;
230 for subnode in opp_nodes.by_ref().take(table.capacity()) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000231 let prop = subnode.getprop_u64(c"opp-hz")?.ok_or(FdtError::NotFound)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800232 table.push(prop);
233 }
234
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100235 if opp_nodes.next().is_some() {
236 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
237 }
238
David Dai9bdb10c2024-02-01 22:42:54 -0800239 Ok(table)
240}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900241
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000242#[derive(Debug, Default)]
243struct ClusterTopology {
244 // TODO: Support multi-level clusters & threads.
245 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
246}
247
248impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700249 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000250}
251
252#[derive(Debug, Default)]
253struct CpuTopology {
254 // TODO: Support sockets.
255 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
256}
257
258impl CpuTopology {
259 const MAX_CLUSTERS: usize = 3;
260}
261
262fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000263 let Some(cpu_map) = fdt.node(c"/cpus/cpu-map")? else {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000264 return Ok(None);
265 };
266
267 let mut topology = BTreeMap::new();
268 for n in 0..CpuTopology::MAX_CLUSTERS {
269 let name = CString::new(format!("cluster{n}")).unwrap();
270 let Some(cluster) = cpu_map.subnode(&name)? else {
271 break;
272 };
273 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800274 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000275 let Some(core) = cluster.subnode(&name)? else {
276 break;
277 };
Alan Stokesf46a17c2025-01-05 15:50:18 +0000278 let cpu = core.getprop_u32(c"cpu")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000279 let prev = topology.insert(cpu.try_into()?, (n, m));
280 if prev.is_some() {
281 return Err(FdtError::BadValue);
282 }
283 }
284 }
285
286 Ok(Some(topology))
287}
288
289fn read_cpu_info_from(
290 fdt: &Fdt,
291) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000292 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000293
294 let cpu_map = read_cpu_map_from(fdt)?;
295 let mut topology: CpuTopology = Default::default();
296
Alan Stokesf46a17c2025-01-05 15:50:18 +0000297 let mut cpu_nodes = fdt.compatible_nodes(c"arm,armv8")?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000298 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000299 let cpu_capacity = cpu.getprop_u32(c"capacity-dmips-mhz")?;
300 let opp_phandle = cpu.getprop_u32(c"operating-points-v2")?;
David Dai9bdb10c2024-02-01 22:42:54 -0800301 let opptable_info = if let Some(phandle) = opp_phandle {
302 let phandle = phandle.try_into()?;
303 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
304 Some(read_opp_info_from(node)?)
305 } else {
306 None
307 };
David Dai50168a32024-02-14 17:00:48 -0800308 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000309 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000310
311 if let Some(ref cpu_map) = cpu_map {
312 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800313 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000314 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800315 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000316 return Err(FdtError::BadValue);
317 }
David Dai8f476cb2024-02-15 21:57:01 -0800318 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000319 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900320 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000321
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000322 if cpu_nodes.next().is_some() {
323 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
324 }
325
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000326 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900327}
328
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000329fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
330 if cpus.is_empty() {
331 return Err(FdtValidationError::InvalidCpuCount(0));
332 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000333 Ok(())
334}
335
David Dai9bdb10c2024-02-01 22:42:54 -0800336fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000337 let mut nodes = fdt.compatible_nodes(c"virtual,android-v-only-cpufreq")?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000338 let Some(node) = nodes.next() else {
339 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800340 };
341
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000342 if nodes.next().is_some() {
343 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
344 }
345
346 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
347 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000348 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000349
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000350 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800351}
352
353fn validate_vcpufreq_info(
354 vcpufreq_info: &VcpufreqInfo,
355 cpus: &[CpuInfo],
356) -> Result<(), FdtValidationError> {
357 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000358 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800359
360 let base = vcpufreq_info.addr;
361 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000362 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
363
364 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800365 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000366 }
David Dai9bdb10c2024-02-01 22:42:54 -0800367
368 Ok(())
369}
370
371fn patch_opptable(
372 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800373 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800374) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000375 let oppcompat = c"operating-points-v2";
David Dai9bdb10c2024-02-01 22:42:54 -0800376 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000377
378 let Some(opptable) = opptable else {
379 return next.nop();
380 };
381
David Dai9bdb10c2024-02-01 22:42:54 -0800382 let mut next_subnode = next.first_subnode()?;
383
384 for entry in opptable {
385 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000386 subnode.setprop_inplace(c"opp-hz", &entry.to_be_bytes())?;
David Dai9bdb10c2024-02-01 22:42:54 -0800387 next_subnode = subnode.next_subnode()?;
388 }
389
390 while let Some(current) = next_subnode {
391 next_subnode = current.delete_and_next_subnode()?;
392 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000393
David Dai9bdb10c2024-02-01 22:42:54 -0800394 Ok(())
395}
396
397// TODO(ptosi): Rework FdtNodeMut and replace this function.
398fn get_nth_compatible<'a>(
399 fdt: &'a mut Fdt,
400 n: usize,
401 compat: &CStr,
402) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000403 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800404 for _ in 0..n {
405 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
406 }
407 Ok(node)
408}
409
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000410fn patch_cpus(
411 fdt: &mut Fdt,
412 cpus: &[CpuInfo],
413 topology: &Option<CpuTopology>,
414) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000415 const COMPAT: &CStr = c"arm,armv8";
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000416 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800417 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800418 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000419 let phandle = cur.as_node().get_phandle()?.unwrap();
420 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800421 if let Some(cpu_capacity) = cpu.cpu_capacity {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000422 cur.setprop_inplace(c"capacity-dmips-mhz", &cpu_capacity.to_be_bytes())?;
David Dai50168a32024-02-14 17:00:48 -0800423 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000424 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900425 }
David Dai9bdb10c2024-02-01 22:42:54 -0800426 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900427 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000428 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900429 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000430
431 if let Some(topology) = topology {
432 for (n, cluster) in topology.clusters.iter().enumerate() {
433 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
434 let cluster_node = fdt.node_mut(&path)?.unwrap();
435 if let Some(cluster) = cluster {
436 let mut iter = cluster_node.first_subnode()?;
437 for core in cluster.cores {
438 let mut core_node = iter.unwrap();
439 iter = if let Some(core_idx) = core {
440 let phandle = *cpu_phandles.get(core_idx).unwrap();
441 let value = u32::from(phandle).to_be_bytes();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000442 core_node.setprop_inplace(c"cpu", &value)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000443 core_node.next_subnode()?
444 } else {
445 core_node.delete_and_next_subnode()?
446 };
447 }
448 assert!(iter.is_none());
449 } else {
450 cluster_node.nop()?;
451 }
452 }
453 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000454 fdt.node_mut(c"/cpus/cpu-map")?.unwrap().nop()?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000455 }
456
Jiyong Park6a8789a2023-03-21 14:50:59 +0900457 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000458}
459
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000460/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
461/// the guest that don't require being validated by pvmfw.
462fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
463 let mut props = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000464 if let Some(node) = fdt.node(c"/avf/untrusted")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000465 for property in node.properties()? {
466 let name = property.name()?;
467 let value = property.value()?;
468 props.insert(CString::from(name), value.to_vec());
469 }
470 if node.subnodes()?.next().is_some() {
471 warn!("Discarding unexpected /avf/untrusted subnodes.");
472 }
473 }
474
475 Ok(props)
476}
477
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900478/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900479fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900480 let mut property_map = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000481 if let Some(avf_node) = fdt.node(c"/avf")? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900482 for property in avf_node.properties()? {
483 let name = property.name()?;
484 let value = property.value()?;
485 property_map.insert(
486 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
487 value.to_vec(),
488 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900489 }
490 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900491 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900492}
493
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000494fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000495 const FORBIDDEN_PROPS: &[&CStr] = &[c"compatible", c"linux,phandle", c"phandle"];
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000496
497 for name in FORBIDDEN_PROPS {
498 if props.contains_key(*name) {
499 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
500 }
501 }
502
503 Ok(())
504}
505
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900506/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
507/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
508fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900509 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900510 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900511 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900512) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000513 let root_vm_dt = vm_dt.root_mut();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000514 let mut avf_vm_dt = root_vm_dt.add_subnode(c"avf")?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900515 // TODO(b/318431677): Validate nodes beyond /avf.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000516 let avf_node = vm_ref_dt.node(c"/avf")?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900517 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900518 if let Some(ref_value) = avf_node.getprop(name)? {
519 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900520 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900521 "Property mismatches while applying overlay VM reference DT. \
522 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
523 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900524 );
525 return Err(FdtError::BadValue);
526 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900527 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900528 }
529 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900530 Ok(())
531}
532
Jiyong Park00ceff32023-03-13 05:43:23 +0000533#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000534struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900535 ranges: [PciAddrRange; 2],
536 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
537 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000538}
539
Jiyong Park6a8789a2023-03-21 14:50:59 +0900540impl PciInfo {
541 const IRQ_MASK_CELLS: usize = 4;
542 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe2d0969c2024-06-06 12:59:12 +0000543 const MAX_IRQS: usize = 16;
Jiyong Park00ceff32023-03-13 05:43:23 +0000544}
545
Jiyong Park6a8789a2023-03-21 14:50:59 +0900546type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
547type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
548type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000549
550/// Iterator that takes N cells as a chunk
551struct CellChunkIterator<'a, const N: usize> {
552 cells: CellIterator<'a>,
553}
554
555impl<'a, const N: usize> CellChunkIterator<'a, N> {
556 fn new(cells: CellIterator<'a>) -> Self {
557 Self { cells }
558 }
559}
560
Chris Wailes52358e92025-01-27 17:04:40 -0800561impl<const N: usize> Iterator for CellChunkIterator<'_, N> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000562 type Item = [u32; N];
563 fn next(&mut self) -> Option<Self::Item> {
564 let mut ret: Self::Item = [0; N];
565 for i in ret.iter_mut() {
566 *i = self.cells.next()?;
567 }
568 Some(ret)
569 }
570}
571
Jiyong Park6a8789a2023-03-21 14:50:59 +0900572/// Read pci host controller ranges, irq maps, and irq map masks from DT
573fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000574 let node = fdt.compatible_nodes(c"pci-host-cam-generic")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900575
576 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
577 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
578 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
579
Alan Stokesf46a17c2025-01-05 15:50:18 +0000580 let irq_masks = node.getprop_cells(c"interrupt-map-mask")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000581 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
582 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
583
584 if chunks.next().is_some() {
585 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
586 return Err(FdtError::NoSpace);
587 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900588
Alan Stokesf46a17c2025-01-05 15:50:18 +0000589 let irq_maps = node.getprop_cells(c"interrupt-map")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000590 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
591 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
592
593 if chunks.next().is_some() {
594 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
595 return Err(FdtError::NoSpace);
596 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900597
598 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
599}
600
Jiyong Park0ee65392023-03-27 20:52:45 +0900601fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900602 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900603 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604 }
605 for irq_mask in pci_info.irq_masks.iter() {
606 validate_pci_irq_mask(irq_mask)?;
607 }
608 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
609 validate_pci_irq_map(irq_map, idx)?;
610 }
611 Ok(())
612}
613
Jiyong Park0ee65392023-03-27 20:52:45 +0900614fn validate_pci_addr_range(
615 range: &PciAddrRange,
616 memory_range: &Range<usize>,
617) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900618 let mem_flags = PciMemoryFlags(range.addr.0);
619 let range_type = mem_flags.range_type();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900620 let bus_addr = range.addr.1;
621 let cpu_addr = range.parent_addr;
622 let size = range.size;
623
624 if range_type != PciRangeType::Memory64 {
625 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
626 return Err(RebootReason::InvalidFdt);
627 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900628 // Enforce ID bus-to-cpu mappings, as used by crosvm.
629 if bus_addr != cpu_addr {
630 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
631 return Err(RebootReason::InvalidFdt);
632 }
633
Jiyong Park0ee65392023-03-27 20:52:45 +0900634 let Some(bus_end) = bus_addr.checked_add(size) else {
635 error!("PCI address range size {:#x} overflows", size);
636 return Err(RebootReason::InvalidFdt);
637 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000638 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900639 error!("PCI address end {:#x} is outside of translatable range", bus_end);
640 return Err(RebootReason::InvalidFdt);
641 }
642
643 let memory_start = memory_range.start.try_into().unwrap();
644 let memory_end = memory_range.end.try_into().unwrap();
645
646 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
647 error!(
648 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
649 bus_addr, bus_end, memory_start, memory_end
650 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900651 return Err(RebootReason::InvalidFdt);
652 }
653
654 Ok(())
655}
656
657fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000658 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
659 const IRQ_MASK_ADDR_ME: u32 = 0x0;
660 const IRQ_MASK_ADDR_LO: u32 = 0x0;
661 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900662 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000663 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900664 if *irq_mask != EXPECTED {
665 error!("Invalid PCI irq mask {:#?}", irq_mask);
666 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000667 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900668 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000669}
670
Jiyong Park6a8789a2023-03-21 14:50:59 +0900671fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000672 const PCI_DEVICE_IDX: usize = 11;
673 const PCI_IRQ_ADDR_ME: u32 = 0;
674 const PCI_IRQ_ADDR_LO: u32 = 0;
675 const PCI_IRQ_INTC: u32 = 1;
676 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
677 const GIC_SPI: u32 = 0;
678 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
679
Jiyong Park6a8789a2023-03-21 14:50:59 +0900680 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
681 let pci_irq_number = irq_map[3];
682 let _controller_phandle = irq_map[4]; // skipped.
683 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
684 // interrupt-cells is <3> for GIC
685 let gic_peripheral_interrupt_type = irq_map[7];
686 let gic_irq_number = irq_map[8];
687 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000688
Jiyong Park6a8789a2023-03-21 14:50:59 +0900689 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
690 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000691
Jiyong Park6a8789a2023-03-21 14:50:59 +0900692 if pci_addr != expected_pci_addr {
693 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
694 {:#x} {:#x} {:#x}",
695 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
696 return Err(RebootReason::InvalidFdt);
697 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000698
Jiyong Park6a8789a2023-03-21 14:50:59 +0900699 if pci_irq_number != PCI_IRQ_INTC {
700 error!(
701 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
702 pci_irq_number, PCI_IRQ_INTC
703 );
704 return Err(RebootReason::InvalidFdt);
705 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000706
Jiyong Park6a8789a2023-03-21 14:50:59 +0900707 if gic_addr != (0, 0) {
708 error!(
709 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
710 {:#x} {:#x}",
711 gic_addr.0, gic_addr.1, 0, 0
712 );
713 return Err(RebootReason::InvalidFdt);
714 }
715
716 if gic_peripheral_interrupt_type != GIC_SPI {
717 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
718 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
719 return Err(RebootReason::InvalidFdt);
720 }
721
722 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
723 if gic_irq_number != irq_nr {
724 error!(
725 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
726 gic_irq_number, irq_nr
727 );
728 return Err(RebootReason::InvalidFdt);
729 }
730
731 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
732 error!(
733 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
734 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
735 );
736 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000737 }
738 Ok(())
739}
740
Jiyong Park9c63cd12023-03-21 17:53:07 +0900741fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000742 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000743 fdt.root_mut().next_compatible(c"pci-host-cam-generic")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900744
745 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000746 node.trimprop(c"interrupt-map-mask", irq_masks_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900747
748 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000749 node.trimprop(c"interrupt-map", irq_maps_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900750
751 node.setprop_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000752 c"ranges",
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000753 [pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()].as_flattened(),
Jiyong Park9c63cd12023-03-21 17:53:07 +0900754 )
755}
756
Jiyong Park00ceff32023-03-13 05:43:23 +0000757#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900758struct SerialInfo {
759 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000760}
761
762impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900763 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000764}
765
Jiyong Park6a8789a2023-03-21 14:50:59 +0900766fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000767 let mut addrs = ArrayVec::new();
768
Alan Stokesf46a17c2025-01-05 15:50:18 +0000769 let mut serial_nodes = fdt.compatible_nodes(c"ns16550a")?;
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000770 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000771 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900772 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000773 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000774 if serial_nodes.next().is_some() {
775 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
776 }
777
Jiyong Park6a8789a2023-03-21 14:50:59 +0900778 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000779}
780
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000781#[derive(Default, Debug, PartialEq)]
782struct WdtInfo {
783 addr: u64,
784 size: u64,
785 irq: [u32; WdtInfo::IRQ_CELLS],
786}
787
788impl WdtInfo {
789 const IRQ_CELLS: usize = 3;
790 const IRQ_NR: u32 = 0xf;
791 const ADDR: u64 = 0x3000;
792 const SIZE: u64 = 0x1000;
793 const GIC_PPI: u32 = 1;
794 const IRQ_TYPE_EDGE_RISING: u32 = 1;
795 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100796 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000797 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
798
799 const fn get_expected(num_cpus: usize) -> Self {
800 Self {
801 addr: Self::ADDR,
802 size: Self::SIZE,
803 irq: [
804 Self::GIC_PPI,
805 Self::IRQ_NR,
806 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
807 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
808 | Self::IRQ_TYPE_EDGE_RISING,
809 ],
810 }
811 }
812}
813
814fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000815 let mut node_iter = fdt.compatible_nodes(c"qemu,vcpu-stall-detector")?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000816 let node = node_iter.next().ok_or(FdtError::NotFound)?;
817 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
818
819 let reg = ranges.next().ok_or(FdtError::NotFound)?;
820 let size = reg.size.ok_or(FdtError::NotFound)?;
821 if ranges.next().is_some() {
822 warn!("Discarding extra vmwdt <reg> entries.");
823 }
824
Alan Stokesf46a17c2025-01-05 15:50:18 +0000825 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000826 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
827 let irq = chunks.next().ok_or(FdtError::NotFound)?;
828
829 if chunks.next().is_some() {
830 warn!("Discarding extra vmwdt <interrupts> entries.");
831 }
832
833 Ok(WdtInfo { addr: reg.addr, size, irq })
834}
835
836fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
837 if *wdt != WdtInfo::get_expected(num_cpus) {
838 error!("Invalid watchdog timer: {wdt:?}");
839 return Err(RebootReason::InvalidFdt);
840 }
841
842 Ok(())
843}
844
845fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
846 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
847 for v in interrupts.iter_mut() {
848 *v = v.to_be();
849 }
850
851 let mut node = fdt
852 .root_mut()
Alan Stokesf46a17c2025-01-05 15:50:18 +0000853 .next_compatible(c"qemu,vcpu-stall-detector")?
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000854 .ok_or(libfdt::FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000855 node.setprop_inplace(c"interrupts", interrupts.as_bytes())?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000856 Ok(())
857}
858
Jiyong Park9c63cd12023-03-21 17:53:07 +0900859/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
860fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000861 let name = c"ns16550a";
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000862 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900863 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000864 let reg =
865 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900866 next = if !serial_info.addrs.contains(&reg.addr) {
867 current.delete_and_next_compatible(name)
868 } else {
869 current.next_compatible(name)
870 }
871 }
872 Ok(())
873}
874
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700875fn validate_swiotlb_info(
876 swiotlb_info: &SwiotlbInfo,
877 memory: &Range<usize>,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000878 alignment: usize,
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700879) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900880 let size = swiotlb_info.size;
881 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000882
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000883 if size == 0 || (size % alignment) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000884 error!("Invalid swiotlb size {:#x}", size);
885 return Err(RebootReason::InvalidFdt);
886 }
887
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000888 if let Some(align) = align.filter(|&a| a % alignment != 0) {
889 error!("Swiotlb alignment {:#x} not aligned to {:#x}", align, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000890 return Err(RebootReason::InvalidFdt);
891 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700892
Alice Wang9cfbfd62023-06-14 11:19:03 +0000893 if let Some(addr) = swiotlb_info.addr {
894 if addr.checked_add(size).is_none() {
895 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
896 return Err(RebootReason::InvalidFdt);
897 }
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000898 if (addr % alignment) != 0 {
899 error!("Swiotlb address {:#x} not aligned to {:#x}", addr, alignment);
900 return Err(RebootReason::InvalidFdt);
901 }
Alice Wang9cfbfd62023-06-14 11:19:03 +0000902 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700903 if let Some(range) = swiotlb_info.fixed_range() {
904 if !range.is_within(memory) {
905 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
906 return Err(RebootReason::InvalidFdt);
907 }
908 }
909
Jiyong Park6a8789a2023-03-21 14:50:59 +0900910 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000911}
912
Jiyong Park9c63cd12023-03-21 17:53:07 +0900913fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
914 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000915 fdt.root_mut().next_compatible(c"restricted-dma-pool")?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700916
917 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000918 node.setprop_addrrange_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000919 c"reg",
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700920 range.start.try_into().unwrap(),
921 range.len().try_into().unwrap(),
922 )?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000923 node.nop_property(c"size")?;
924 node.nop_property(c"alignment")?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700925 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000926 node.nop_property(c"reg")?;
927 node.setprop_inplace(c"size", &swiotlb_info.size.to_be_bytes())?;
928 node.setprop_inplace(c"alignment", &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700929 }
930
Jiyong Park9c63cd12023-03-21 17:53:07 +0900931 Ok(())
932}
933
934fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000935 let node = fdt.compatible_nodes(c"arm,gic-v3")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900936 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
937 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
938 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
939
940 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000941 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
942 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000943 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900944
945 // range1 is just below range0
946 range1.addr = addr - size;
947 range1.size = Some(size);
948
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000949 let (addr0, size0) = range0.to_cells();
950 let (addr1, size1) = range1.to_cells();
951 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900952
Alan Stokesf46a17c2025-01-05 15:50:18 +0000953 let mut node = fdt.root_mut().next_compatible(c"arm,gic-v3")?.ok_or(FdtError::NotFound)?;
954 node.setprop_inplace(c"reg", value.as_flattened())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900955}
956
957fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
958 const NUM_INTERRUPTS: usize = 4;
959 const CELLS_PER_INTERRUPT: usize = 3;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000960 let node = fdt.compatible_nodes(c"arm,armv8-timer")?.next().ok_or(FdtError::NotFound)?;
961 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900962 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
963 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
964
965 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100966 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900967 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000968
Jiyong Park9c63cd12023-03-21 17:53:07 +0900969 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
970 *v |= cpu_mask;
971 }
972 for v in value.iter_mut() {
973 *v = v.to_be();
974 }
975
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000976 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900977
Alan Stokesf46a17c2025-01-05 15:50:18 +0000978 let mut node = fdt.root_mut().next_compatible(c"arm,armv8-timer")?.ok_or(FdtError::NotFound)?;
979 node.setprop_inplace(c"interrupts", value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900980}
981
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000982fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000983 let avf_node = if let Some(node) = fdt.node_mut(c"/avf")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000984 node
985 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000986 fdt.root_mut().add_subnode(c"avf")?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000987 };
988
989 // The node shouldn't already be present; if it is, return the error.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000990 let mut node = avf_node.add_subnode(c"untrusted")?;
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000991
992 for (name, value) in props {
993 node.setprop(name, value)?;
994 }
995
996 Ok(())
997}
998
Jiyong Park00ceff32023-03-13 05:43:23 +0000999#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -08001000struct VcpufreqInfo {
1001 addr: u64,
1002 size: u64,
1003}
1004
1005fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001006 let mut node = fdt.node_mut(c"/cpufreq")?.unwrap();
David Dai9bdb10c2024-02-01 22:42:54 -08001007 if let Some(info) = vcpufreq_info {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001008 node.setprop_addrrange_inplace(c"reg", info.addr, info.size)
David Dai9bdb10c2024-02-01 22:42:54 -08001009 } else {
1010 node.nop()
1011 }
1012}
1013
1014#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +09001015pub struct DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001016 pub initrd_range: Option<Range<usize>>,
1017 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001018 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001019 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001020 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001021 pci_info: PciInfo,
1022 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -07001023 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001024 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001025 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001026 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001027 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001028}
1029
1030impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001031 const MAX_CPUS: usize = 16;
1032
1033 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001034 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1035
1036 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1037 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001038}
1039
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001040pub fn sanitize_device_tree(
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +00001041 fdt: &mut Fdt,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001042 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001043 vm_ref_dt: Option<&[u8]>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001044 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001045 hyp_page_size: Option<usize>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001046) -> Result<DeviceTreeInfo, RebootReason> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001047 let vm_dtbo = match vm_dtbo {
1048 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1049 error!("Failed to load VM DTBO: {e}");
1050 RebootReason::InvalidFdt
1051 })?),
1052 None => None,
1053 };
1054
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001055 let info = parse_device_tree(fdt, vm_dtbo.as_deref(), guest_page_size, hyp_page_size)?;
Jiyong Park83316122023-03-21 09:39:39 +09001056
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +00001057 fdt.clone_from(FDT_TEMPLATE).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001058 error!("Failed to instantiate FDT from the template DT: {e}");
1059 RebootReason::InvalidFdt
1060 })?;
1061
Jaewan Kim9220e852023-12-01 10:58:40 +09001062 fdt.unpack().map_err(|e| {
1063 error!("Failed to unpack DT for patching: {e}");
1064 RebootReason::InvalidFdt
1065 })?;
1066
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001067 if let Some(device_assignment_info) = &info.device_assignment {
1068 let vm_dtbo = vm_dtbo.unwrap();
1069 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1070 error!("Failed to filter VM DTBO: {e}");
1071 RebootReason::InvalidFdt
1072 })?;
1073 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1074 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1075 // it can only be instantiated after validation.
1076 unsafe {
1077 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1078 error!("Failed to apply filtered VM DTBO: {e}");
1079 RebootReason::InvalidFdt
1080 })?;
1081 }
1082 }
1083
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001084 if let Some(vm_ref_dt) = vm_ref_dt {
1085 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1086 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001087 RebootReason::InvalidFdt
1088 })?;
1089
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001090 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1091 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001092 RebootReason::InvalidFdt
1093 })?;
1094 }
1095
Jiyong Park9c63cd12023-03-21 17:53:07 +09001096 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001097
Jaewan Kim19b984f2023-12-04 15:16:50 +09001098 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1099
Jaewan Kim9220e852023-12-01 10:58:40 +09001100 fdt.pack().map_err(|e| {
1101 error!("Failed to unpack DT after patching: {e}");
1102 RebootReason::InvalidFdt
1103 })?;
1104
Jiyong Park6a8789a2023-03-21 14:50:59 +09001105 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001106}
1107
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001108fn parse_device_tree(
1109 fdt: &Fdt,
1110 vm_dtbo: Option<&VmDtbo>,
1111 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001112 hyp_page_size: Option<usize>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001113) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001114 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1115 error!("Failed to read initrd range from DT: {e}");
1116 RebootReason::InvalidFdt
1117 })?;
1118
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001119 // Ensure that MMIO_GUARD can't be used to inadvertently map some memory as MMIO.
1120 let memory_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001121 let memory_range = read_and_validate_memory_range(fdt, memory_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001122
Jiyong Parke9d87e82023-03-21 19:28:40 +09001123 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1124 error!("Failed to read bootargs from DT: {e}");
1125 RebootReason::InvalidFdt
1126 })?;
1127
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001128 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001129 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001130 RebootReason::InvalidFdt
1131 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001132 validate_cpu_info(&cpus).map_err(|e| {
1133 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001134 RebootReason::InvalidFdt
1135 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001136
David Dai9bdb10c2024-02-01 22:42:54 -08001137 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1138 error!("Failed to read vcpufreq info from DT: {e}");
1139 RebootReason::InvalidFdt
1140 })?;
1141 if let Some(ref info) = vcpufreq_info {
1142 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1143 error!("Failed to validate vcpufreq info from DT: {e}");
1144 RebootReason::InvalidFdt
1145 })?;
1146 }
1147
Jiyong Park6a8789a2023-03-21 14:50:59 +09001148 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1149 error!("Failed to read pci info from DT: {e}");
1150 RebootReason::InvalidFdt
1151 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001152 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001153
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001154 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1155 error!("Failed to read vCPU stall detector info from DT: {e}");
1156 RebootReason::InvalidFdt
1157 })?;
1158 validate_wdt_info(&wdt_info, cpus.len())?;
1159
Jiyong Park6a8789a2023-03-21 14:50:59 +09001160 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1161 error!("Failed to read serial info from DT: {e}");
1162 RebootReason::InvalidFdt
1163 })?;
1164
Pierre-Clément Tosi3c5e7a72024-11-27 20:12:37 +00001165 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt)
1166 .map_err(|e| {
1167 error!("Failed to read swiotlb info from DT: {e}");
1168 RebootReason::InvalidFdt
1169 })?
1170 .ok_or_else(|| {
1171 error!("Swiotlb info missing from DT");
1172 RebootReason::InvalidFdt
1173 })?;
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001174 // Ensure that MEM_SHARE won't inadvertently map beyond the shared region.
1175 let swiotlb_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001176 validate_swiotlb_info(&swiotlb_info, &memory_range, swiotlb_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001177
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001178 let device_assignment = if let Some(vm_dtbo) = vm_dtbo {
1179 if let Some(hypervisor) = get_device_assigner() {
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001180 let granule = hyp_page_size.ok_or_else(|| {
1181 error!("No granule found during device assignment validation");
1182 RebootReason::InternalError
1183 })?;
1184
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001185 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor, granule).map_err(|e| {
1186 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1187 RebootReason::InvalidFdt
1188 })?
1189 } else {
1190 warn!("Device assignment is ignored because device assigning hypervisor is missing");
1191 None
Jaewan Kim52477ae2023-11-21 21:20:52 +09001192 }
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001193 } else {
1194 None
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001195 };
1196
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001197 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1198 error!("Failed to read untrusted properties: {e}");
1199 RebootReason::InvalidFdt
1200 })?;
1201 validate_untrusted_props(&untrusted_props).map_err(|e| {
1202 error!("Failed to validate untrusted properties: {e}");
1203 RebootReason::InvalidFdt
1204 })?;
1205
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001206 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001207 error!("Failed to read names of properties under /avf from DT: {e}");
1208 RebootReason::InvalidFdt
1209 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001210
Jiyong Park00ceff32023-03-13 05:43:23 +00001211 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001212 initrd_range,
1213 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001214 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001215 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001216 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001217 pci_info,
1218 serial_info,
1219 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001220 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001221 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001222 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001223 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001224 })
1225}
1226
Jiyong Park9c63cd12023-03-21 17:53:07 +09001227fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1228 if let Some(initrd_range) = &info.initrd_range {
1229 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1230 error!("Failed to patch initrd range to DT: {e}");
1231 RebootReason::InvalidFdt
1232 })?;
1233 }
1234 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1235 error!("Failed to patch memory range to DT: {e}");
1236 RebootReason::InvalidFdt
1237 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001238 if let Some(bootargs) = &info.bootargs {
1239 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1240 error!("Failed to patch bootargs to DT: {e}");
1241 RebootReason::InvalidFdt
1242 })?;
1243 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001244 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001245 error!("Failed to patch cpus to DT: {e}");
1246 RebootReason::InvalidFdt
1247 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001248 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1249 error!("Failed to patch vcpufreq info to DT: {e}");
1250 RebootReason::InvalidFdt
1251 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001252 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1253 error!("Failed to patch pci info to DT: {e}");
1254 RebootReason::InvalidFdt
1255 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001256 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1257 error!("Failed to patch wdt info to DT: {e}");
1258 RebootReason::InvalidFdt
1259 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001260 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1261 error!("Failed to patch serial info to DT: {e}");
1262 RebootReason::InvalidFdt
1263 })?;
1264 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1265 error!("Failed to patch swiotlb info to DT: {e}");
1266 RebootReason::InvalidFdt
1267 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001268 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001269 error!("Failed to patch gic info to DT: {e}");
1270 RebootReason::InvalidFdt
1271 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001272 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001273 error!("Failed to patch timer info to DT: {e}");
1274 RebootReason::InvalidFdt
1275 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001276 if let Some(device_assignment) = &info.device_assignment {
1277 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1278 // then VM DTBO's underlying slice is allocated.
1279 device_assignment.patch(fdt).map_err(|e| {
1280 error!("Failed to patch device assignment info to DT: {e}");
1281 RebootReason::InvalidFdt
1282 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001283 } else {
1284 device_assignment::clean(fdt).map_err(|e| {
1285 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1286 RebootReason::InvalidFdt
1287 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001288 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001289 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1290 error!("Failed to patch untrusted properties: {e}");
1291 RebootReason::InvalidFdt
1292 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001293
Jiyong Park9c63cd12023-03-21 17:53:07 +09001294 Ok(())
1295}
1296
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001297/// Modifies the input DT according to the fields of the configuration.
1298pub fn modify_for_next_stage(
1299 fdt: &mut Fdt,
1300 bcc: &[u8],
1301 new_instance: bool,
1302 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001303 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001304 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001305 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001306) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001307 if let Some(debug_policy) = debug_policy {
1308 let backup = Vec::from(fdt.as_slice());
1309 fdt.unpack()?;
1310 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1311 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1312 info!("Debug policy applied.");
1313 } else {
1314 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1315 fdt.unpack()?;
1316 }
1317 } else {
1318 info!("No debug policy found.");
1319 fdt.unpack()?;
1320 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001321
Jiyong Parke9d87e82023-03-21 19:28:40 +09001322 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001323
Alice Wang56ec45b2023-06-15 08:30:32 +00001324 if let Some(mut chosen) = fdt.chosen_mut()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001325 empty_or_delete_prop(&mut chosen, c"avf,strict-boot", strict_boot)?;
1326 empty_or_delete_prop(&mut chosen, c"avf,new-instance", new_instance)?;
1327 chosen.setprop_inplace(c"kaslr-seed", &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001328 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001329 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001330 if let Some(bootargs) = read_bootargs_from(fdt)? {
1331 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1332 }
1333 }
1334
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001335 fdt.pack()?;
1336
1337 Ok(())
1338}
1339
Jiyong Parke9d87e82023-03-21 19:28:40 +09001340/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1341fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001342 // We reject DTs with missing reserved-memory node as validation should have checked that the
1343 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001344 let node = fdt.node_mut(c"/reserved-memory")?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001345
Alan Stokesf46a17c2025-01-05 15:50:18 +00001346 let mut node = node.next_compatible(c"google,open-dice")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001347
Jiyong Parke9d87e82023-03-21 19:28:40 +09001348 let addr: u64 = addr.try_into().unwrap();
1349 let size: u64 = size.try_into().unwrap();
Alan Stokesf46a17c2025-01-05 15:50:18 +00001350 node.setprop_inplace(c"reg", [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001351}
1352
Alice Wang56ec45b2023-06-15 08:30:32 +00001353fn empty_or_delete_prop(
1354 fdt_node: &mut FdtNodeMut,
1355 prop_name: &CStr,
1356 keep_prop: bool,
1357) -> libfdt::Result<()> {
1358 if keep_prop {
1359 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001360 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001361 fdt_node
1362 .delprop(prop_name)
1363 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001364 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001365}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001366
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001367/// Apply the debug policy overlay to the guest DT.
1368///
1369/// 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 +00001370fn apply_debug_policy(
1371 fdt: &mut Fdt,
1372 backup_fdt: &Fdt,
1373 debug_policy: &[u8],
1374) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001375 let mut debug_policy = Vec::from(debug_policy);
1376 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001377 Ok(overlay) => overlay,
1378 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001379 warn!("Corrupted debug policy found: {e}. Not applying.");
1380 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001381 }
1382 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001383
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001384 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001385 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001386 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001387 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001388 // A successful restoration is considered success because an invalid debug policy
1389 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001390 Ok(false)
1391 } else {
1392 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001393 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001394}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001395
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001396fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001397 if let Some(node) = fdt.node(c"/avf/guest/common")? {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001398 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1399 return Ok(value == 1);
1400 }
1401 }
1402 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1403}
1404
1405fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001406 let has_crashkernel = has_common_debug_policy(fdt, c"ramdump")?;
1407 let has_console = has_common_debug_policy(fdt, c"log")?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001408
1409 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1410 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1411 ("crashkernel", Box::new(|_| has_crashkernel)),
1412 ("console", Box::new(|_| has_console)),
1413 ];
1414
1415 // parse and filter out unwanted
1416 let mut filtered = Vec::new();
1417 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1418 info!("Invalid bootarg: {e}");
1419 FdtError::BadValue
1420 })? {
1421 match accepted.iter().find(|&t| t.0 == arg.name()) {
1422 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1423 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1424 }
1425 }
1426
1427 // flatten into a new C-string
1428 let mut new_bootargs = Vec::new();
1429 for (i, arg) in filtered.iter().enumerate() {
1430 if i != 0 {
1431 new_bootargs.push(b' '); // separator
1432 }
1433 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1434 }
1435 new_bootargs.push(b'\0');
1436
1437 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001438 node.setprop(c"bootargs", new_bootargs.as_slice())
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001439}