blob: 6f55c21185e551fc7f78b7f725cefe14f84f854e [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 Tosie6e46db2025-02-07 11:39:41 +000081/// For non-standardly sized integer properties, not following <#size-cells> or <#address-cells>.
82#[derive(Copy, Clone, Debug, Eq, PartialEq)]
83enum DeviceTreeInteger {
84 SingleCell(u32),
85 DoubleCell(u64),
86}
87
88impl DeviceTreeInteger {
89 fn read_from(node: &FdtNode, name: &CStr) -> libfdt::Result<Option<Self>> {
90 if let Some(bytes) = node.getprop(name)? {
91 Ok(Some(Self::from_bytes(bytes).ok_or(FdtError::BadValue)?))
92 } else {
93 Ok(None)
94 }
95 }
96
97 fn from_bytes(bytes: &[u8]) -> Option<Self> {
98 if let Some(val) = bytes.try_into().ok().map(u32::from_be_bytes) {
99 return Some(Self::SingleCell(val));
100 } else if let Some(val) = bytes.try_into().ok().map(u64::from_be_bytes) {
101 return Some(Self::DoubleCell(val));
102 }
103 None
104 }
105
106 fn write_to(&self, node: &mut FdtNodeMut, name: &CStr) -> libfdt::Result<()> {
107 match self {
108 Self::SingleCell(value) => node.setprop(name, &value.to_be_bytes()),
109 Self::DoubleCell(value) => node.setprop(name, &value.to_be_bytes()),
110 }
111 }
112}
113
114impl From<DeviceTreeInteger> for usize {
115 fn from(i: DeviceTreeInteger) -> Self {
116 match i {
117 DeviceTreeInteger::SingleCell(v) => v.try_into().unwrap(),
118 DeviceTreeInteger::DoubleCell(v) => v.try_into().unwrap(),
119 }
120 }
121}
122
123/// Returns the pair or integers or an error if only one value is present.
124fn read_two_ints(
125 node: &FdtNode,
126 name_a: &CStr,
127 name_b: &CStr,
128) -> libfdt::Result<Option<(DeviceTreeInteger, DeviceTreeInteger)>> {
129 let a = DeviceTreeInteger::read_from(node, name_a)?;
130 let b = DeviceTreeInteger::read_from(node, name_b)?;
131
132 match (a, b) {
133 (Some(a), Some(b)) => Ok(Some((a, b))),
134 (None, None) => Ok(None),
135 _ => Err(FdtError::NotFound),
136 }
137}
138
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +0000139/// Extract from /config the address range containing the pre-loaded kernel.
140///
141/// Absence of /config is not an error. However, an error is returned if only one of the two
142/// properties is present.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +0000143pub fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +0000144 if let Some(ref config) = fdt.node(c"/config")? {
145 if let Some((addr, size)) = read_two_ints(config, c"kernel-address", c"kernel-size")? {
146 let addr = usize::from(addr);
147 let size = usize::from(size);
148 return Ok(Some(addr..(addr + size)));
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +0000149 }
150 }
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +0000151 Ok(None)
152}
153
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +0000154fn read_initrd_range_props(
155 fdt: &Fdt,
156) -> libfdt::Result<Option<(DeviceTreeInteger, DeviceTreeInteger)>> {
157 if let Some(ref chosen) = fdt.chosen()? {
158 read_two_ints(chosen, c"linux,initrd-start", c"linux,initrd-end")
159 } else {
160 Ok(None)
161 }
162}
163
Pierre-Clément Tosiec368b72025-02-07 11:51:44 +0000164/// Extract from /chosen the address range containing the pre-loaded ramdisk.
165///
166/// Absence is not an error as there can be initrd-less VM. However, an error is returned if only
167/// one of the two properties is present.
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +0000168pub fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +0000169 if let Some((start, end)) = read_initrd_range_props(fdt)? {
170 Ok(Some(usize::from(start)..usize::from(end)))
171 } else {
172 Ok(None)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000173 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000174}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000175
Pierre-Clément Tosi3729f652024-11-19 15:25:37 +0000176/// Read /avf/untrusted/instance-id, if present.
177pub fn read_instance_id(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
178 read_avf_untrusted_prop(fdt, c"instance-id")
179}
180
181/// Read /avf/untrusted/defer-rollback-protection, if present.
182pub fn read_defer_rollback_protection(fdt: &Fdt) -> libfdt::Result<Option<&[u8]>> {
183 read_avf_untrusted_prop(fdt, c"defer-rollback-protection")
184}
185
186fn read_avf_untrusted_prop<'a>(fdt: &'a Fdt, prop: &CStr) -> libfdt::Result<Option<&'a [u8]>> {
187 if let Some(node) = fdt.node(c"/avf/untrusted")? {
188 node.getprop(prop)
189 } else {
190 Ok(None)
191 }
192}
193
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +0000194fn patch_initrd_range(
195 fdt: &mut Fdt,
196 start: &DeviceTreeInteger,
197 end: &DeviceTreeInteger,
198) -> libfdt::Result<()> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900199 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +0000200 start.write_to(&mut node, c"linux,initrd-start")?;
201 end.write_to(&mut node, c"linux,initrd-end")?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900202 Ok(())
203}
204
Jiyong Parke9d87e82023-03-21 19:28:40 +0900205fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
206 if let Some(chosen) = fdt.chosen()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000207 if let Some(bootargs) = chosen.getprop_str(c"bootargs")? {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900208 // We need to copy the string to heap because the original fdt will be invalidated
209 // by the templated DT
210 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
211 return Ok(Some(copy));
212 }
213 }
214 Ok(None)
215}
216
217fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
218 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900219 // This function is called before the verification is done. So, we just copy the bootargs to
220 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
221 // if the VM is not debuggable.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000222 node.setprop(c"bootargs", bootargs.to_bytes_with_nul())
Jiyong Parke9d87e82023-03-21 19:28:40 +0900223}
224
Alice Wang0d527472023-06-13 14:55:38 +0000225/// Reads and validates the memory range in the DT.
226///
227/// Only one memory range is expected with the crosvm setup for now.
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000228fn read_and_validate_memory_range(
229 fdt: &Fdt,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000230 alignment: usize,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +0000231) -> Result<Range<usize>, RebootReason> {
Alice Wang0d527472023-06-13 14:55:38 +0000232 let mut memory = fdt.memory().map_err(|e| {
233 error!("Failed to read memory range from DT: {e}");
234 RebootReason::InvalidFdt
235 })?;
236 let range = memory.next().ok_or_else(|| {
237 error!("The /memory node in the DT contains no range.");
238 RebootReason::InvalidFdt
239 })?;
240 if memory.next().is_some() {
241 warn!(
242 "The /memory node in the DT contains more than one memory range, \
243 while only one is expected."
244 );
245 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900246 let base = range.start;
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000247 if base % alignment != 0 {
248 error!("Memory base address {:#x} is not aligned to {:#x}", base, alignment);
249 return Err(RebootReason::InvalidFdt);
250 }
251 // For simplicity, force a hardcoded memory base, for now.
Alice Wange243d462023-06-06 15:18:12 +0000252 if base != MEM_START {
253 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000254 return Err(RebootReason::InvalidFdt);
255 }
256
Jiyong Park6a8789a2023-03-21 14:50:59 +0900257 let size = range.len();
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000258 if size % alignment != 0 {
259 error!("Memory size {:#x} is not aligned to {:#x}", size, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000260 return Err(RebootReason::InvalidFdt);
261 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000262
Jiyong Park6a8789a2023-03-21 14:50:59 +0900263 if size == 0 {
264 error!("Memory size is 0");
265 return Err(RebootReason::InvalidFdt);
266 }
Alice Wang0d527472023-06-13 14:55:38 +0000267 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000268}
269
Jiyong Park9c63cd12023-03-21 17:53:07 +0900270fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000271 let addr = u64::try_from(MEM_START).unwrap();
272 let size = u64::try_from(memory_range.len()).unwrap();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000273 fdt.node_mut(c"/memory")?
Jiyong Park0ee65392023-03-27 20:52:45 +0900274 .ok_or(FdtError::NotFound)?
Alan Stokesf46a17c2025-01-05 15:50:18 +0000275 .setprop_inplace(c"reg", [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900276}
277
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000278#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800279struct CpuInfo {
280 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800281 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800282}
283
284impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800285 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800286}
287
288fn read_opp_info_from(
289 opp_node: FdtNode,
290) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
291 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100292 let mut opp_nodes = opp_node.subnodes()?;
293 for subnode in opp_nodes.by_ref().take(table.capacity()) {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000294 let prop = subnode.getprop_u64(c"opp-hz")?.ok_or(FdtError::NotFound)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800295 table.push(prop);
296 }
297
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100298 if opp_nodes.next().is_some() {
299 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
300 }
301
David Dai9bdb10c2024-02-01 22:42:54 -0800302 Ok(table)
303}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900304
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000305#[derive(Debug, Default)]
306struct ClusterTopology {
307 // TODO: Support multi-level clusters & threads.
308 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
309}
310
311impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700312 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000313}
314
315#[derive(Debug, Default)]
316struct CpuTopology {
317 // TODO: Support sockets.
318 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
319}
320
321impl CpuTopology {
322 const MAX_CLUSTERS: usize = 3;
323}
324
325fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000326 let Some(cpu_map) = fdt.node(c"/cpus/cpu-map")? else {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000327 return Ok(None);
328 };
329
330 let mut topology = BTreeMap::new();
331 for n in 0..CpuTopology::MAX_CLUSTERS {
332 let name = CString::new(format!("cluster{n}")).unwrap();
333 let Some(cluster) = cpu_map.subnode(&name)? else {
334 break;
335 };
336 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800337 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000338 let Some(core) = cluster.subnode(&name)? else {
339 break;
340 };
Alan Stokesf46a17c2025-01-05 15:50:18 +0000341 let cpu = core.getprop_u32(c"cpu")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000342 let prev = topology.insert(cpu.try_into()?, (n, m));
343 if prev.is_some() {
344 return Err(FdtError::BadValue);
345 }
346 }
347 }
348
349 Ok(Some(topology))
350}
351
352fn read_cpu_info_from(
353 fdt: &Fdt,
354) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000355 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000356
357 let cpu_map = read_cpu_map_from(fdt)?;
358 let mut topology: CpuTopology = Default::default();
359
Alan Stokesf46a17c2025-01-05 15:50:18 +0000360 let mut cpu_nodes = fdt.compatible_nodes(c"arm,armv8")?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000361 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000362 let cpu_capacity = cpu.getprop_u32(c"capacity-dmips-mhz")?;
363 let opp_phandle = cpu.getprop_u32(c"operating-points-v2")?;
David Dai9bdb10c2024-02-01 22:42:54 -0800364 let opptable_info = if let Some(phandle) = opp_phandle {
365 let phandle = phandle.try_into()?;
366 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
367 Some(read_opp_info_from(node)?)
368 } else {
369 None
370 };
David Dai50168a32024-02-14 17:00:48 -0800371 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000372 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000373
374 if let Some(ref cpu_map) = cpu_map {
375 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800376 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000377 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800378 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000379 return Err(FdtError::BadValue);
380 }
David Dai8f476cb2024-02-15 21:57:01 -0800381 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000382 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900383 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000384
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000385 if cpu_nodes.next().is_some() {
386 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
387 }
388
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000389 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900390}
391
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000392fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
393 if cpus.is_empty() {
394 return Err(FdtValidationError::InvalidCpuCount(0));
395 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000396 Ok(())
397}
398
David Dai9bdb10c2024-02-01 22:42:54 -0800399fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000400 let mut nodes = fdt.compatible_nodes(c"virtual,android-v-only-cpufreq")?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000401 let Some(node) = nodes.next() else {
402 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800403 };
404
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000405 if nodes.next().is_some() {
406 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
407 }
408
409 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
410 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000411 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000412
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000413 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800414}
415
416fn validate_vcpufreq_info(
417 vcpufreq_info: &VcpufreqInfo,
418 cpus: &[CpuInfo],
419) -> Result<(), FdtValidationError> {
420 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000421 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800422
423 let base = vcpufreq_info.addr;
424 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000425 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
426
427 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800428 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000429 }
David Dai9bdb10c2024-02-01 22:42:54 -0800430
431 Ok(())
432}
433
434fn patch_opptable(
435 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800436 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800437) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000438 let oppcompat = c"operating-points-v2";
David Dai9bdb10c2024-02-01 22:42:54 -0800439 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000440
441 let Some(opptable) = opptable else {
442 return next.nop();
443 };
444
David Dai9bdb10c2024-02-01 22:42:54 -0800445 let mut next_subnode = next.first_subnode()?;
446
447 for entry in opptable {
448 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000449 subnode.setprop_inplace(c"opp-hz", &entry.to_be_bytes())?;
David Dai9bdb10c2024-02-01 22:42:54 -0800450 next_subnode = subnode.next_subnode()?;
451 }
452
453 while let Some(current) = next_subnode {
454 next_subnode = current.delete_and_next_subnode()?;
455 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000456
David Dai9bdb10c2024-02-01 22:42:54 -0800457 Ok(())
458}
459
460// TODO(ptosi): Rework FdtNodeMut and replace this function.
461fn get_nth_compatible<'a>(
462 fdt: &'a mut Fdt,
463 n: usize,
464 compat: &CStr,
465) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000466 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800467 for _ in 0..n {
468 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
469 }
470 Ok(node)
471}
472
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000473fn patch_cpus(
474 fdt: &mut Fdt,
475 cpus: &[CpuInfo],
476 topology: &Option<CpuTopology>,
477) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000478 const COMPAT: &CStr = c"arm,armv8";
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000479 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800480 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800481 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000482 let phandle = cur.as_node().get_phandle()?.unwrap();
483 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800484 if let Some(cpu_capacity) = cpu.cpu_capacity {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000485 cur.setprop_inplace(c"capacity-dmips-mhz", &cpu_capacity.to_be_bytes())?;
David Dai50168a32024-02-14 17:00:48 -0800486 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000487 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900488 }
David Dai9bdb10c2024-02-01 22:42:54 -0800489 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900490 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000491 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900492 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000493
494 if let Some(topology) = topology {
495 for (n, cluster) in topology.clusters.iter().enumerate() {
496 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
497 let cluster_node = fdt.node_mut(&path)?.unwrap();
498 if let Some(cluster) = cluster {
499 let mut iter = cluster_node.first_subnode()?;
500 for core in cluster.cores {
501 let mut core_node = iter.unwrap();
502 iter = if let Some(core_idx) = core {
503 let phandle = *cpu_phandles.get(core_idx).unwrap();
504 let value = u32::from(phandle).to_be_bytes();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000505 core_node.setprop_inplace(c"cpu", &value)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000506 core_node.next_subnode()?
507 } else {
508 core_node.delete_and_next_subnode()?
509 };
510 }
511 assert!(iter.is_none());
512 } else {
513 cluster_node.nop()?;
514 }
515 }
516 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000517 fdt.node_mut(c"/cpus/cpu-map")?.unwrap().nop()?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000518 }
519
Jiyong Park6a8789a2023-03-21 14:50:59 +0900520 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000521}
522
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000523/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
524/// the guest that don't require being validated by pvmfw.
525fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
526 let mut props = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000527 if let Some(node) = fdt.node(c"/avf/untrusted")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000528 for property in node.properties()? {
529 let name = property.name()?;
530 let value = property.value()?;
531 props.insert(CString::from(name), value.to_vec());
532 }
533 if node.subnodes()?.next().is_some() {
534 warn!("Discarding unexpected /avf/untrusted subnodes.");
535 }
536 }
537
538 Ok(props)
539}
540
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900541/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900542fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900543 let mut property_map = BTreeMap::new();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000544 if let Some(avf_node) = fdt.node(c"/avf")? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900545 for property in avf_node.properties()? {
546 let name = property.name()?;
547 let value = property.value()?;
548 property_map.insert(
549 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
550 value.to_vec(),
551 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900552 }
553 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900554 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900555}
556
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000557fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000558 const FORBIDDEN_PROPS: &[&CStr] = &[c"compatible", c"linux,phandle", c"phandle"];
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000559
560 for name in FORBIDDEN_PROPS {
561 if props.contains_key(*name) {
562 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
563 }
564 }
565
566 Ok(())
567}
568
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900569/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
570/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
571fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900572 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900573 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900574 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900575) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000576 let root_vm_dt = vm_dt.root_mut();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000577 let mut avf_vm_dt = root_vm_dt.add_subnode(c"avf")?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900578 // TODO(b/318431677): Validate nodes beyond /avf.
Alan Stokesf46a17c2025-01-05 15:50:18 +0000579 let avf_node = vm_ref_dt.node(c"/avf")?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900580 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900581 if let Some(ref_value) = avf_node.getprop(name)? {
582 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900583 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900584 "Property mismatches while applying overlay VM reference DT. \
585 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
586 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900587 );
588 return Err(FdtError::BadValue);
589 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900590 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900591 }
592 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900593 Ok(())
594}
595
Jiyong Park00ceff32023-03-13 05:43:23 +0000596#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000597struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900598 ranges: [PciAddrRange; 2],
599 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
600 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000601}
602
Jiyong Park6a8789a2023-03-21 14:50:59 +0900603impl PciInfo {
604 const IRQ_MASK_CELLS: usize = 4;
605 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe2d0969c2024-06-06 12:59:12 +0000606 const MAX_IRQS: usize = 16;
Jiyong Park00ceff32023-03-13 05:43:23 +0000607}
608
Jiyong Park6a8789a2023-03-21 14:50:59 +0900609type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
610type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
611type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000612
613/// Iterator that takes N cells as a chunk
614struct CellChunkIterator<'a, const N: usize> {
615 cells: CellIterator<'a>,
616}
617
618impl<'a, const N: usize> CellChunkIterator<'a, N> {
619 fn new(cells: CellIterator<'a>) -> Self {
620 Self { cells }
621 }
622}
623
Chris Wailes52358e92025-01-27 17:04:40 -0800624impl<const N: usize> Iterator for CellChunkIterator<'_, N> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000625 type Item = [u32; N];
626 fn next(&mut self) -> Option<Self::Item> {
627 let mut ret: Self::Item = [0; N];
628 for i in ret.iter_mut() {
629 *i = self.cells.next()?;
630 }
631 Some(ret)
632 }
633}
634
Jiyong Park6a8789a2023-03-21 14:50:59 +0900635/// Read pci host controller ranges, irq maps, and irq map masks from DT
636fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000637 let node = fdt.compatible_nodes(c"pci-host-cam-generic")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900638
639 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
640 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
641 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
642
Alan Stokesf46a17c2025-01-05 15:50:18 +0000643 let irq_masks = node.getprop_cells(c"interrupt-map-mask")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000644 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
645 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
646
647 if chunks.next().is_some() {
648 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
649 return Err(FdtError::NoSpace);
650 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900651
Alan Stokesf46a17c2025-01-05 15:50:18 +0000652 let irq_maps = node.getprop_cells(c"interrupt-map")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000653 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
654 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
655
656 if chunks.next().is_some() {
657 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
658 return Err(FdtError::NoSpace);
659 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900660
661 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
662}
663
Jiyong Park0ee65392023-03-27 20:52:45 +0900664fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900665 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900666 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900667 }
668 for irq_mask in pci_info.irq_masks.iter() {
669 validate_pci_irq_mask(irq_mask)?;
670 }
671 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
672 validate_pci_irq_map(irq_map, idx)?;
673 }
674 Ok(())
675}
676
Jiyong Park0ee65392023-03-27 20:52:45 +0900677fn validate_pci_addr_range(
678 range: &PciAddrRange,
679 memory_range: &Range<usize>,
680) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900681 let mem_flags = PciMemoryFlags(range.addr.0);
682 let range_type = mem_flags.range_type();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900683 let bus_addr = range.addr.1;
684 let cpu_addr = range.parent_addr;
685 let size = range.size;
686
687 if range_type != PciRangeType::Memory64 {
688 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
689 return Err(RebootReason::InvalidFdt);
690 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900691 // Enforce ID bus-to-cpu mappings, as used by crosvm.
692 if bus_addr != cpu_addr {
693 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
694 return Err(RebootReason::InvalidFdt);
695 }
696
Jiyong Park0ee65392023-03-27 20:52:45 +0900697 let Some(bus_end) = bus_addr.checked_add(size) else {
698 error!("PCI address range size {:#x} overflows", size);
699 return Err(RebootReason::InvalidFdt);
700 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000701 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900702 error!("PCI address end {:#x} is outside of translatable range", bus_end);
703 return Err(RebootReason::InvalidFdt);
704 }
705
706 let memory_start = memory_range.start.try_into().unwrap();
707 let memory_end = memory_range.end.try_into().unwrap();
708
709 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
710 error!(
711 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
712 bus_addr, bus_end, memory_start, memory_end
713 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900714 return Err(RebootReason::InvalidFdt);
715 }
716
717 Ok(())
718}
719
720fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000721 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
722 const IRQ_MASK_ADDR_ME: u32 = 0x0;
723 const IRQ_MASK_ADDR_LO: u32 = 0x0;
724 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900725 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000726 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900727 if *irq_mask != EXPECTED {
728 error!("Invalid PCI irq mask {:#?}", irq_mask);
729 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000730 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900731 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000732}
733
Jiyong Park6a8789a2023-03-21 14:50:59 +0900734fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000735 const PCI_DEVICE_IDX: usize = 11;
736 const PCI_IRQ_ADDR_ME: u32 = 0;
737 const PCI_IRQ_ADDR_LO: u32 = 0;
738 const PCI_IRQ_INTC: u32 = 1;
739 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
740 const GIC_SPI: u32 = 0;
741 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
742
Jiyong Park6a8789a2023-03-21 14:50:59 +0900743 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
744 let pci_irq_number = irq_map[3];
745 let _controller_phandle = irq_map[4]; // skipped.
746 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
747 // interrupt-cells is <3> for GIC
748 let gic_peripheral_interrupt_type = irq_map[7];
749 let gic_irq_number = irq_map[8];
750 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000751
Jiyong Park6a8789a2023-03-21 14:50:59 +0900752 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
753 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000754
Jiyong Park6a8789a2023-03-21 14:50:59 +0900755 if pci_addr != expected_pci_addr {
756 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
757 {:#x} {:#x} {:#x}",
758 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
759 return Err(RebootReason::InvalidFdt);
760 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000761
Jiyong Park6a8789a2023-03-21 14:50:59 +0900762 if pci_irq_number != PCI_IRQ_INTC {
763 error!(
764 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
765 pci_irq_number, PCI_IRQ_INTC
766 );
767 return Err(RebootReason::InvalidFdt);
768 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000769
Jiyong Park6a8789a2023-03-21 14:50:59 +0900770 if gic_addr != (0, 0) {
771 error!(
772 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
773 {:#x} {:#x}",
774 gic_addr.0, gic_addr.1, 0, 0
775 );
776 return Err(RebootReason::InvalidFdt);
777 }
778
779 if gic_peripheral_interrupt_type != GIC_SPI {
780 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
781 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
782 return Err(RebootReason::InvalidFdt);
783 }
784
785 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
786 if gic_irq_number != irq_nr {
787 error!(
788 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
789 gic_irq_number, irq_nr
790 );
791 return Err(RebootReason::InvalidFdt);
792 }
793
794 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
795 error!(
796 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
797 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
798 );
799 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000800 }
801 Ok(())
802}
803
Jiyong Park9c63cd12023-03-21 17:53:07 +0900804fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000805 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000806 fdt.root_mut().next_compatible(c"pci-host-cam-generic")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900807
808 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000809 node.trimprop(c"interrupt-map-mask", irq_masks_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900810
811 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
Alan Stokesf46a17c2025-01-05 15:50:18 +0000812 node.trimprop(c"interrupt-map", irq_maps_size)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900813
814 node.setprop_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000815 c"ranges",
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000816 [pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()].as_flattened(),
Jiyong Park9c63cd12023-03-21 17:53:07 +0900817 )
818}
819
Jiyong Park00ceff32023-03-13 05:43:23 +0000820#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900821struct SerialInfo {
822 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000823}
824
825impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900826 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000827}
828
Jiyong Park6a8789a2023-03-21 14:50:59 +0900829fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000830 let mut addrs = ArrayVec::new();
831
Alan Stokesf46a17c2025-01-05 15:50:18 +0000832 let mut serial_nodes = fdt.compatible_nodes(c"ns16550a")?;
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000833 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000834 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900835 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000836 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000837 if serial_nodes.next().is_some() {
838 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
839 }
840
Jiyong Park6a8789a2023-03-21 14:50:59 +0900841 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000842}
843
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000844#[derive(Default, Debug, PartialEq)]
845struct WdtInfo {
846 addr: u64,
847 size: u64,
848 irq: [u32; WdtInfo::IRQ_CELLS],
849}
850
851impl WdtInfo {
852 const IRQ_CELLS: usize = 3;
853 const IRQ_NR: u32 = 0xf;
854 const ADDR: u64 = 0x3000;
855 const SIZE: u64 = 0x1000;
856 const GIC_PPI: u32 = 1;
857 const IRQ_TYPE_EDGE_RISING: u32 = 1;
858 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100859 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000860 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
861
862 const fn get_expected(num_cpus: usize) -> Self {
863 Self {
864 addr: Self::ADDR,
865 size: Self::SIZE,
866 irq: [
867 Self::GIC_PPI,
868 Self::IRQ_NR,
869 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
870 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
871 | Self::IRQ_TYPE_EDGE_RISING,
872 ],
873 }
874 }
875}
876
877fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000878 let mut node_iter = fdt.compatible_nodes(c"qemu,vcpu-stall-detector")?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000879 let node = node_iter.next().ok_or(FdtError::NotFound)?;
880 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
881
882 let reg = ranges.next().ok_or(FdtError::NotFound)?;
883 let size = reg.size.ok_or(FdtError::NotFound)?;
884 if ranges.next().is_some() {
885 warn!("Discarding extra vmwdt <reg> entries.");
886 }
887
Alan Stokesf46a17c2025-01-05 15:50:18 +0000888 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000889 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
890 let irq = chunks.next().ok_or(FdtError::NotFound)?;
891
892 if chunks.next().is_some() {
893 warn!("Discarding extra vmwdt <interrupts> entries.");
894 }
895
896 Ok(WdtInfo { addr: reg.addr, size, irq })
897}
898
899fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
900 if *wdt != WdtInfo::get_expected(num_cpus) {
901 error!("Invalid watchdog timer: {wdt:?}");
902 return Err(RebootReason::InvalidFdt);
903 }
904
905 Ok(())
906}
907
908fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
909 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
910 for v in interrupts.iter_mut() {
911 *v = v.to_be();
912 }
913
914 let mut node = fdt
915 .root_mut()
Alan Stokesf46a17c2025-01-05 15:50:18 +0000916 .next_compatible(c"qemu,vcpu-stall-detector")?
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000917 .ok_or(libfdt::FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000918 node.setprop_inplace(c"interrupts", interrupts.as_bytes())?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000919 Ok(())
920}
921
Jiyong Park9c63cd12023-03-21 17:53:07 +0900922/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
923fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000924 let name = c"ns16550a";
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000925 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900926 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000927 let reg =
928 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900929 next = if !serial_info.addrs.contains(&reg.addr) {
930 current.delete_and_next_compatible(name)
931 } else {
932 current.next_compatible(name)
933 }
934 }
935 Ok(())
936}
937
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700938fn validate_swiotlb_info(
939 swiotlb_info: &SwiotlbInfo,
940 memory: &Range<usize>,
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000941 alignment: usize,
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700942) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900943 let size = swiotlb_info.size;
944 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000945
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000946 if size == 0 || (size % alignment) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000947 error!("Invalid swiotlb size {:#x}", size);
948 return Err(RebootReason::InvalidFdt);
949 }
950
Pierre-Clément Tosica354342025-02-06 17:34:52 +0000951 if let Some(align) = align.filter(|&a| a % alignment != 0) {
952 error!("Swiotlb alignment {:#x} not aligned to {:#x}", align, alignment);
Jiyong Park00ceff32023-03-13 05:43:23 +0000953 return Err(RebootReason::InvalidFdt);
954 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700955
Alice Wang9cfbfd62023-06-14 11:19:03 +0000956 if let Some(addr) = swiotlb_info.addr {
957 if addr.checked_add(size).is_none() {
958 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
959 return Err(RebootReason::InvalidFdt);
960 }
Pierre-Clément Tosi4ae4da42025-02-06 17:36:47 +0000961 if (addr % alignment) != 0 {
962 error!("Swiotlb address {:#x} not aligned to {:#x}", addr, alignment);
963 return Err(RebootReason::InvalidFdt);
964 }
Alice Wang9cfbfd62023-06-14 11:19:03 +0000965 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700966 if let Some(range) = swiotlb_info.fixed_range() {
967 if !range.is_within(memory) {
968 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
969 return Err(RebootReason::InvalidFdt);
970 }
971 }
972
Jiyong Park6a8789a2023-03-21 14:50:59 +0900973 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000974}
975
Jiyong Park9c63cd12023-03-21 17:53:07 +0900976fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
977 let mut node =
Alan Stokesf46a17c2025-01-05 15:50:18 +0000978 fdt.root_mut().next_compatible(c"restricted-dma-pool")?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700979
980 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000981 node.setprop_addrrange_inplace(
Alan Stokesf46a17c2025-01-05 15:50:18 +0000982 c"reg",
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700983 range.start.try_into().unwrap(),
984 range.len().try_into().unwrap(),
985 )?;
Alan Stokesf46a17c2025-01-05 15:50:18 +0000986 node.nop_property(c"size")?;
987 node.nop_property(c"alignment")?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700988 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000989 node.nop_property(c"reg")?;
990 node.setprop_inplace(c"size", &swiotlb_info.size.to_be_bytes())?;
991 node.setprop_inplace(c"alignment", &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700992 }
993
Jiyong Park9c63cd12023-03-21 17:53:07 +0900994 Ok(())
995}
996
997fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +0000998 let node = fdt.compatible_nodes(c"arm,gic-v3")?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900999 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
1000 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
1001 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
1002
1003 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001004 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
1005 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +00001006 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +09001007
1008 // range1 is just below range0
1009 range1.addr = addr - size;
1010 range1.size = Some(size);
1011
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +00001012 let (addr0, size0) = range0.to_cells();
1013 let (addr1, size1) = range1.to_cells();
1014 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +09001015
Alan Stokesf46a17c2025-01-05 15:50:18 +00001016 let mut node = fdt.root_mut().next_compatible(c"arm,gic-v3")?.ok_or(FdtError::NotFound)?;
1017 node.setprop_inplace(c"reg", value.as_flattened())
Jiyong Park9c63cd12023-03-21 17:53:07 +09001018}
1019
1020fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
1021 const NUM_INTERRUPTS: usize = 4;
1022 const CELLS_PER_INTERRUPT: usize = 3;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001023 let node = fdt.compatible_nodes(c"arm,armv8-timer")?.next().ok_or(FdtError::NotFound)?;
1024 let interrupts = node.getprop_cells(c"interrupts")?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001025 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
1026 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
1027
1028 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +01001029 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +09001030 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001031
Jiyong Park9c63cd12023-03-21 17:53:07 +09001032 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
1033 *v |= cpu_mask;
1034 }
1035 for v in value.iter_mut() {
1036 *v = v.to_be();
1037 }
1038
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +00001039 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +09001040
Alan Stokesf46a17c2025-01-05 15:50:18 +00001041 let mut node = fdt.root_mut().next_compatible(c"arm,armv8-timer")?.ok_or(FdtError::NotFound)?;
1042 node.setprop_inplace(c"interrupts", value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +09001043}
1044
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001045fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001046 let avf_node = if let Some(node) = fdt.node_mut(c"/avf")? {
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001047 node
1048 } else {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001049 fdt.root_mut().add_subnode(c"avf")?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001050 };
1051
1052 // The node shouldn't already be present; if it is, return the error.
Alan Stokesf46a17c2025-01-05 15:50:18 +00001053 let mut node = avf_node.add_subnode(c"untrusted")?;
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001054
1055 for (name, value) in props {
1056 node.setprop(name, value)?;
1057 }
1058
1059 Ok(())
1060}
1061
Jiyong Park00ceff32023-03-13 05:43:23 +00001062#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -08001063struct VcpufreqInfo {
1064 addr: u64,
1065 size: u64,
1066}
1067
1068fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001069 let mut node = fdt.node_mut(c"/cpufreq")?.unwrap();
David Dai9bdb10c2024-02-01 22:42:54 -08001070 if let Some(info) = vcpufreq_info {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001071 node.setprop_addrrange_inplace(c"reg", info.addr, info.size)
David Dai9bdb10c2024-02-01 22:42:54 -08001072 } else {
1073 node.nop()
1074 }
1075}
1076
1077#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +09001078pub struct DeviceTreeInfo {
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +00001079 initrd_range: Option<(DeviceTreeInteger, DeviceTreeInteger)>,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001080 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001081 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001082 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001083 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001084 pci_info: PciInfo,
1085 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -07001086 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001087 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001088 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001089 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001090 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001091}
1092
1093impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001094 const MAX_CPUS: usize = 16;
1095
1096 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001097 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1098
1099 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1100 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001101}
1102
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001103pub fn sanitize_device_tree(
Pierre-Clément Tosi0d4c09b2024-11-19 17:32:15 +00001104 fdt: &mut Fdt,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001105 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001106 vm_ref_dt: Option<&[u8]>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001107 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001108 hyp_page_size: Option<usize>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001109) -> Result<DeviceTreeInfo, RebootReason> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001110 let vm_dtbo = match vm_dtbo {
1111 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1112 error!("Failed to load VM DTBO: {e}");
1113 RebootReason::InvalidFdt
1114 })?),
1115 None => None,
1116 };
1117
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001118 let info = parse_device_tree(fdt, vm_dtbo.as_deref(), guest_page_size, hyp_page_size)?;
Jiyong Park83316122023-03-21 09:39:39 +09001119
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +00001120 fdt.clone_from(FDT_TEMPLATE).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001121 error!("Failed to instantiate FDT from the template DT: {e}");
1122 RebootReason::InvalidFdt
1123 })?;
1124
Jaewan Kim9220e852023-12-01 10:58:40 +09001125 fdt.unpack().map_err(|e| {
1126 error!("Failed to unpack DT for patching: {e}");
1127 RebootReason::InvalidFdt
1128 })?;
1129
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001130 if let Some(device_assignment_info) = &info.device_assignment {
1131 let vm_dtbo = vm_dtbo.unwrap();
1132 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1133 error!("Failed to filter VM DTBO: {e}");
1134 RebootReason::InvalidFdt
1135 })?;
1136 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1137 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1138 // it can only be instantiated after validation.
1139 unsafe {
1140 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1141 error!("Failed to apply filtered VM DTBO: {e}");
1142 RebootReason::InvalidFdt
1143 })?;
1144 }
1145 }
1146
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001147 if let Some(vm_ref_dt) = vm_ref_dt {
1148 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1149 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001150 RebootReason::InvalidFdt
1151 })?;
1152
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001153 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1154 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001155 RebootReason::InvalidFdt
1156 })?;
1157 }
1158
Jiyong Park9c63cd12023-03-21 17:53:07 +09001159 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001160
Jaewan Kim19b984f2023-12-04 15:16:50 +09001161 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1162
Jaewan Kim9220e852023-12-01 10:58:40 +09001163 fdt.pack().map_err(|e| {
1164 error!("Failed to unpack DT after patching: {e}");
1165 RebootReason::InvalidFdt
1166 })?;
1167
Jiyong Park6a8789a2023-03-21 14:50:59 +09001168 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001169}
1170
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001171fn parse_device_tree(
1172 fdt: &Fdt,
1173 vm_dtbo: Option<&VmDtbo>,
1174 guest_page_size: usize,
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001175 hyp_page_size: Option<usize>,
Pierre-Clément Tosi938b4fb2024-11-26 12:59:47 +00001176) -> Result<DeviceTreeInfo, RebootReason> {
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +00001177 let initrd_range = read_initrd_range_props(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001178 error!("Failed to read initrd range from DT: {e}");
1179 RebootReason::InvalidFdt
1180 })?;
1181
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001182 // Ensure that MMIO_GUARD can't be used to inadvertently map some memory as MMIO.
1183 let memory_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001184 let memory_range = read_and_validate_memory_range(fdt, memory_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001185
Jiyong Parke9d87e82023-03-21 19:28:40 +09001186 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1187 error!("Failed to read bootargs from DT: {e}");
1188 RebootReason::InvalidFdt
1189 })?;
1190
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001191 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001192 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001193 RebootReason::InvalidFdt
1194 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001195 validate_cpu_info(&cpus).map_err(|e| {
1196 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001197 RebootReason::InvalidFdt
1198 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001199
David Dai9bdb10c2024-02-01 22:42:54 -08001200 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1201 error!("Failed to read vcpufreq info from DT: {e}");
1202 RebootReason::InvalidFdt
1203 })?;
1204 if let Some(ref info) = vcpufreq_info {
1205 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1206 error!("Failed to validate vcpufreq info from DT: {e}");
1207 RebootReason::InvalidFdt
1208 })?;
1209 }
1210
Jiyong Park6a8789a2023-03-21 14:50:59 +09001211 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1212 error!("Failed to read pci info from DT: {e}");
1213 RebootReason::InvalidFdt
1214 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001215 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001216
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001217 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1218 error!("Failed to read vCPU stall detector info from DT: {e}");
1219 RebootReason::InvalidFdt
1220 })?;
1221 validate_wdt_info(&wdt_info, cpus.len())?;
1222
Jiyong Park6a8789a2023-03-21 14:50:59 +09001223 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1224 error!("Failed to read serial info from DT: {e}");
1225 RebootReason::InvalidFdt
1226 })?;
1227
Pierre-Clément Tosi3c5e7a72024-11-27 20:12:37 +00001228 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt)
1229 .map_err(|e| {
1230 error!("Failed to read swiotlb info from DT: {e}");
1231 RebootReason::InvalidFdt
1232 })?
1233 .ok_or_else(|| {
1234 error!("Swiotlb info missing from DT");
1235 RebootReason::InvalidFdt
1236 })?;
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001237 // Ensure that MEM_SHARE won't inadvertently map beyond the shared region.
1238 let swiotlb_alignment = max(hyp_page_size, Some(guest_page_size)).unwrap();
Pierre-Clément Tosica354342025-02-06 17:34:52 +00001239 validate_swiotlb_info(&swiotlb_info, &memory_range, swiotlb_alignment)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001240
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001241 let device_assignment = if let Some(vm_dtbo) = vm_dtbo {
1242 if let Some(hypervisor) = get_device_assigner() {
Pierre-Clément Tosic9edf0f2025-02-06 17:47:25 +00001243 let granule = hyp_page_size.ok_or_else(|| {
1244 error!("No granule found during device assignment validation");
1245 RebootReason::InternalError
1246 })?;
1247
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001248 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor, granule).map_err(|e| {
1249 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1250 RebootReason::InvalidFdt
1251 })?
1252 } else {
1253 warn!("Device assignment is ignored because device assigning hypervisor is missing");
1254 None
Jaewan Kim52477ae2023-11-21 21:20:52 +09001255 }
Pierre-Clément Tosi3e674ed2025-02-06 17:48:44 +00001256 } else {
1257 None
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001258 };
1259
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001260 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1261 error!("Failed to read untrusted properties: {e}");
1262 RebootReason::InvalidFdt
1263 })?;
1264 validate_untrusted_props(&untrusted_props).map_err(|e| {
1265 error!("Failed to validate untrusted properties: {e}");
1266 RebootReason::InvalidFdt
1267 })?;
1268
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001269 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001270 error!("Failed to read names of properties under /avf from DT: {e}");
1271 RebootReason::InvalidFdt
1272 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001273
Jiyong Park00ceff32023-03-13 05:43:23 +00001274 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001275 initrd_range,
1276 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001277 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001278 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001279 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001280 pci_info,
1281 serial_info,
1282 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001283 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001284 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001285 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001286 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001287 })
1288}
1289
Jiyong Park9c63cd12023-03-21 17:53:07 +09001290fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Pierre-Clément Tosie6e46db2025-02-07 11:39:41 +00001291 if let Some((start, end)) = &info.initrd_range {
1292 patch_initrd_range(fdt, start, end).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001293 error!("Failed to patch initrd range to DT: {e}");
1294 RebootReason::InvalidFdt
1295 })?;
1296 }
1297 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1298 error!("Failed to patch memory range to DT: {e}");
1299 RebootReason::InvalidFdt
1300 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001301 if let Some(bootargs) = &info.bootargs {
1302 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1303 error!("Failed to patch bootargs to DT: {e}");
1304 RebootReason::InvalidFdt
1305 })?;
1306 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001307 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001308 error!("Failed to patch cpus to DT: {e}");
1309 RebootReason::InvalidFdt
1310 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001311 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1312 error!("Failed to patch vcpufreq info to DT: {e}");
1313 RebootReason::InvalidFdt
1314 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001315 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1316 error!("Failed to patch pci info to DT: {e}");
1317 RebootReason::InvalidFdt
1318 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001319 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1320 error!("Failed to patch wdt info to DT: {e}");
1321 RebootReason::InvalidFdt
1322 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001323 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1324 error!("Failed to patch serial info to DT: {e}");
1325 RebootReason::InvalidFdt
1326 })?;
1327 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1328 error!("Failed to patch swiotlb info to DT: {e}");
1329 RebootReason::InvalidFdt
1330 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001331 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001332 error!("Failed to patch gic info to DT: {e}");
1333 RebootReason::InvalidFdt
1334 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001335 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001336 error!("Failed to patch timer info to DT: {e}");
1337 RebootReason::InvalidFdt
1338 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001339 if let Some(device_assignment) = &info.device_assignment {
1340 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1341 // then VM DTBO's underlying slice is allocated.
1342 device_assignment.patch(fdt).map_err(|e| {
1343 error!("Failed to patch device assignment info to DT: {e}");
1344 RebootReason::InvalidFdt
1345 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001346 } else {
1347 device_assignment::clean(fdt).map_err(|e| {
1348 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1349 RebootReason::InvalidFdt
1350 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001351 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001352 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1353 error!("Failed to patch untrusted properties: {e}");
1354 RebootReason::InvalidFdt
1355 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001356
Jiyong Park9c63cd12023-03-21 17:53:07 +09001357 Ok(())
1358}
1359
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001360/// Modifies the input DT according to the fields of the configuration.
1361pub fn modify_for_next_stage(
1362 fdt: &mut Fdt,
1363 bcc: &[u8],
1364 new_instance: bool,
1365 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001366 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001367 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001368 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001369) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001370 if let Some(debug_policy) = debug_policy {
1371 let backup = Vec::from(fdt.as_slice());
1372 fdt.unpack()?;
1373 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1374 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1375 info!("Debug policy applied.");
1376 } else {
1377 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1378 fdt.unpack()?;
1379 }
1380 } else {
1381 info!("No debug policy found.");
1382 fdt.unpack()?;
1383 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001384
Pierre-Clément Tosie63cef92025-03-03 12:47:33 -08001385 patch_dice_node(fdt, bcc)?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001386
Alice Wang56ec45b2023-06-15 08:30:32 +00001387 if let Some(mut chosen) = fdt.chosen_mut()? {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001388 empty_or_delete_prop(&mut chosen, c"avf,strict-boot", strict_boot)?;
1389 empty_or_delete_prop(&mut chosen, c"avf,new-instance", new_instance)?;
1390 chosen.setprop_inplace(c"kaslr-seed", &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001391 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001392 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001393 if let Some(bootargs) = read_bootargs_from(fdt)? {
1394 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1395 }
1396 }
1397
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001398 fdt.pack()?;
1399
1400 Ok(())
1401}
1402
Jiyong Parke9d87e82023-03-21 19:28:40 +09001403/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
Pierre-Clément Tosie63cef92025-03-03 12:47:33 -08001404fn patch_dice_node(fdt: &mut Fdt, handover: &[u8]) -> libfdt::Result<()> {
1405 // The node is assumed to be present in the template DT.
1406 let node = fdt.node_mut(c"/reserved-memory")?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001407 let mut node = node.next_compatible(c"google,open-dice")?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001408
Pierre-Clément Tosie63cef92025-03-03 12:47:33 -08001409 let addr = (handover.as_ptr() as usize).try_into().unwrap();
1410 let size = handover.len().try_into().unwrap();
1411 node.setprop_addrrange_inplace(c"reg", addr, size)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001412}
1413
Alice Wang56ec45b2023-06-15 08:30:32 +00001414fn empty_or_delete_prop(
1415 fdt_node: &mut FdtNodeMut,
1416 prop_name: &CStr,
1417 keep_prop: bool,
1418) -> libfdt::Result<()> {
1419 if keep_prop {
1420 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001421 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001422 fdt_node
1423 .delprop(prop_name)
1424 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001425 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001426}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001427
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001428/// Apply the debug policy overlay to the guest DT.
1429///
1430/// 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 +00001431fn apply_debug_policy(
1432 fdt: &mut Fdt,
1433 backup_fdt: &Fdt,
1434 debug_policy: &[u8],
1435) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001436 let mut debug_policy = Vec::from(debug_policy);
1437 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001438 Ok(overlay) => overlay,
1439 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001440 warn!("Corrupted debug policy found: {e}. Not applying.");
1441 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001442 }
1443 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001444
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001445 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001446 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001447 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001448 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001449 // A successful restoration is considered success because an invalid debug policy
1450 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001451 Ok(false)
1452 } else {
1453 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001454 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001455}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001456
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001457fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001458 if let Some(node) = fdt.node(c"/avf/guest/common")? {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001459 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1460 return Ok(value == 1);
1461 }
1462 }
1463 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1464}
1465
1466fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Alan Stokesf46a17c2025-01-05 15:50:18 +00001467 let has_crashkernel = has_common_debug_policy(fdt, c"ramdump")?;
1468 let has_console = has_common_debug_policy(fdt, c"log")?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001469
1470 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1471 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1472 ("crashkernel", Box::new(|_| has_crashkernel)),
1473 ("console", Box::new(|_| has_console)),
1474 ];
1475
1476 // parse and filter out unwanted
1477 let mut filtered = Vec::new();
1478 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1479 info!("Invalid bootarg: {e}");
1480 FdtError::BadValue
1481 })? {
1482 match accepted.iter().find(|&t| t.0 == arg.name()) {
1483 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1484 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1485 }
1486 }
1487
1488 // flatten into a new C-string
1489 let mut new_bootargs = Vec::new();
1490 for (i, arg) in filtered.iter().enumerate() {
1491 if i != 0 {
1492 new_bootargs.push(b' '); // separator
1493 }
1494 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1495 }
1496 new_bootargs.push(b'\0');
1497
1498 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Alan Stokesf46a17c2025-01-05 15:50:18 +00001499 node.setprop(c"bootargs", new_bootargs.as_slice())
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001500}