blob: 47f4cdde82feb13b7c270fa1f93f2ce49ea43ca7 [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 Kim52477ae2023-11-21 21:20:52 +090018use crate::device_assignment::{DeviceAssignmentInfo, VmDtbo};
Jiyong Park00ceff32023-03-13 05:43:23 +000019use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090020use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000024use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090025use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090026use core::cmp::max;
27use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000029use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090030use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use fdtpci::PciMemoryFlags;
34use fdtpci::PciRangeType;
35use libfdt::AddressRange;
36use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000037use libfdt::Fdt;
38use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080039use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000040use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000041use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090042use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090044use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000045use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000046use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000047use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000048use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000049use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000050use vmbase::memory::SIZE_4KB;
51use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000052use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000053use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054
Alice Wangabc7d632023-06-14 09:10:14 +000055/// An enumeration of errors that can occur during the FDT validation.
56#[derive(Clone, Debug)]
57pub enum FdtValidationError {
58 /// Invalid CPU count.
59 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080060 /// Invalid VCpufreq Range.
61 InvalidVcpufreq(u64, u64),
Alice Wangabc7d632023-06-14 09:10:14 +000062}
63
64impl fmt::Display for FdtValidationError {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 match self {
67 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000068 Self::InvalidVcpufreq(addr, size) => {
69 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
70 }
Alice Wangabc7d632023-06-14 09:10:14 +000071 }
72 }
73}
74
Jiyong Park6a8789a2023-03-21 14:50:59 +090075/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
76/// not an error.
77fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090078 let addr = cstr!("kernel-address");
79 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000080
Jiyong Parkb87f3302023-03-21 10:03:11 +090081 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000082 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
83 let addr = addr as usize;
84 let size = size as usize;
85
86 return Ok(Some(addr..(addr + size)));
87 }
88 }
89
90 Ok(None)
91}
92
Jiyong Park6a8789a2023-03-21 14:50:59 +090093/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
94/// error as there can be initrd-less VM.
95fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090096 let start = cstr!("linux,initrd-start");
97 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000098
99 if let Some(chosen) = fdt.chosen()? {
100 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
101 return Ok(Some((start as usize)..(end as usize)));
102 }
103 }
104
105 Ok(None)
106}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000107
Jiyong Park9c63cd12023-03-21 17:53:07 +0900108fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
109 let start = u32::try_from(initrd_range.start).unwrap();
110 let end = u32::try_from(initrd_range.end).unwrap();
111
112 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
113 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
114 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
115 Ok(())
116}
117
Jiyong Parke9d87e82023-03-21 19:28:40 +0900118fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
119 if let Some(chosen) = fdt.chosen()? {
120 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
121 // We need to copy the string to heap because the original fdt will be invalidated
122 // by the templated DT
123 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
124 return Ok(Some(copy));
125 }
126 }
127 Ok(None)
128}
129
130fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
131 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900132 // This function is called before the verification is done. So, we just copy the bootargs to
133 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
134 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900135 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
136}
137
Alice Wang0d527472023-06-13 14:55:38 +0000138/// Reads and validates the memory range in the DT.
139///
140/// Only one memory range is expected with the crosvm setup for now.
141fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
142 let mut memory = fdt.memory().map_err(|e| {
143 error!("Failed to read memory range from DT: {e}");
144 RebootReason::InvalidFdt
145 })?;
146 let range = memory.next().ok_or_else(|| {
147 error!("The /memory node in the DT contains no range.");
148 RebootReason::InvalidFdt
149 })?;
150 if memory.next().is_some() {
151 warn!(
152 "The /memory node in the DT contains more than one memory range, \
153 while only one is expected."
154 );
155 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900156 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000157 if base != MEM_START {
158 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000159 return Err(RebootReason::InvalidFdt);
160 }
161
Jiyong Park6a8789a2023-03-21 14:50:59 +0900162 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000163 if size % GUEST_PAGE_SIZE != 0 {
164 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
165 return Err(RebootReason::InvalidFdt);
166 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000167
Jiyong Park6a8789a2023-03-21 14:50:59 +0900168 if size == 0 {
169 error!("Memory size is 0");
170 return Err(RebootReason::InvalidFdt);
171 }
Alice Wang0d527472023-06-13 14:55:38 +0000172 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000173}
174
Jiyong Park9c63cd12023-03-21 17:53:07 +0900175fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000176 let addr = u64::try_from(MEM_START).unwrap();
177 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900178 fdt.node_mut(cstr!("/memory"))?
179 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000180 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900181}
182
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000183#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800184struct CpuInfo {
185 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800186 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800187}
188
189impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800190 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800191}
192
193fn read_opp_info_from(
194 opp_node: FdtNode,
195) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
196 let mut table = ArrayVec::new();
197 for subnode in opp_node.subnodes()? {
198 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
199 table.push(prop);
200 }
201
202 Ok(table)
203}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900204
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000205#[derive(Debug, Default)]
206struct ClusterTopology {
207 // TODO: Support multi-level clusters & threads.
208 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
209}
210
211impl ClusterTopology {
212 const MAX_CORES_PER_CLUSTER: usize = 6;
213}
214
215#[derive(Debug, Default)]
216struct CpuTopology {
217 // TODO: Support sockets.
218 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
219}
220
221impl CpuTopology {
222 const MAX_CLUSTERS: usize = 3;
223}
224
225fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
226 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
227 return Ok(None);
228 };
229
230 let mut topology = BTreeMap::new();
231 for n in 0..CpuTopology::MAX_CLUSTERS {
232 let name = CString::new(format!("cluster{n}")).unwrap();
233 let Some(cluster) = cpu_map.subnode(&name)? else {
234 break;
235 };
236 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
237 let name = CString::new(format!("core{n}")).unwrap();
238 let Some(core) = cluster.subnode(&name)? else {
239 break;
240 };
241 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
242 let prev = topology.insert(cpu.try_into()?, (n, m));
243 if prev.is_some() {
244 return Err(FdtError::BadValue);
245 }
246 }
247 }
248
249 Ok(Some(topology))
250}
251
252fn read_cpu_info_from(
253 fdt: &Fdt,
254) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000255 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000256
257 let cpu_map = read_cpu_map_from(fdt)?;
258 let mut topology: CpuTopology = Default::default();
259
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000260 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000261 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800262 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800263 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
264 let opptable_info = if let Some(phandle) = opp_phandle {
265 let phandle = phandle.try_into()?;
266 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
267 Some(read_opp_info_from(node)?)
268 } else {
269 None
270 };
David Dai50168a32024-02-14 17:00:48 -0800271 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000272 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000273
274 if let Some(ref cpu_map) = cpu_map {
275 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
276 let (cluster, core) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
277 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
278 let mut core = cluster.cores[*core];
279 if core.is_some() {
280 return Err(FdtError::BadValue);
281 }
282 let _ = core.insert(idx);
283 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900284 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000285
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000286 if cpu_nodes.next().is_some() {
287 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
288 }
289
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000290 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900291}
292
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000293fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
294 if cpus.is_empty() {
295 return Err(FdtValidationError::InvalidCpuCount(0));
296 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000297 Ok(())
298}
299
David Dai9bdb10c2024-02-01 22:42:54 -0800300fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000301 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
302 let Some(node) = nodes.next() else {
303 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800304 };
305
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000306 if nodes.next().is_some() {
307 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
308 }
309
310 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
311 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000312 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000313
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000314 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800315}
316
317fn validate_vcpufreq_info(
318 vcpufreq_info: &VcpufreqInfo,
319 cpus: &[CpuInfo],
320) -> Result<(), FdtValidationError> {
321 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000322 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800323
324 let base = vcpufreq_info.addr;
325 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000326 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
327
328 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800329 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000330 }
David Dai9bdb10c2024-02-01 22:42:54 -0800331
332 Ok(())
333}
334
335fn patch_opptable(
336 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800337 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800338) -> libfdt::Result<()> {
339 let oppcompat = cstr!("operating-points-v2");
340 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000341
342 let Some(opptable) = opptable else {
343 return next.nop();
344 };
345
David Dai9bdb10c2024-02-01 22:42:54 -0800346 let mut next_subnode = next.first_subnode()?;
347
348 for entry in opptable {
349 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
350 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
351 next_subnode = subnode.next_subnode()?;
352 }
353
354 while let Some(current) = next_subnode {
355 next_subnode = current.delete_and_next_subnode()?;
356 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000357
David Dai9bdb10c2024-02-01 22:42:54 -0800358 Ok(())
359}
360
361// TODO(ptosi): Rework FdtNodeMut and replace this function.
362fn get_nth_compatible<'a>(
363 fdt: &'a mut Fdt,
364 n: usize,
365 compat: &CStr,
366) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
367 let mut node = fdt.root_mut()?.next_compatible(compat)?;
368 for _ in 0..n {
369 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
370 }
371 Ok(node)
372}
373
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000374fn patch_cpus(
375 fdt: &mut Fdt,
376 cpus: &[CpuInfo],
377 topology: &Option<CpuTopology>,
378) -> libfdt::Result<()> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000379 const COMPAT: &CStr = cstr!("arm,arm-v8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000380 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800381 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800382 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000383 let phandle = cur.as_node().get_phandle()?.unwrap();
384 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800385 if let Some(cpu_capacity) = cpu.cpu_capacity {
386 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
387 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000388 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900389 }
David Dai9bdb10c2024-02-01 22:42:54 -0800390 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900391 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000392 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900393 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000394
395 if let Some(topology) = topology {
396 for (n, cluster) in topology.clusters.iter().enumerate() {
397 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
398 let cluster_node = fdt.node_mut(&path)?.unwrap();
399 if let Some(cluster) = cluster {
400 let mut iter = cluster_node.first_subnode()?;
401 for core in cluster.cores {
402 let mut core_node = iter.unwrap();
403 iter = if let Some(core_idx) = core {
404 let phandle = *cpu_phandles.get(core_idx).unwrap();
405 let value = u32::from(phandle).to_be_bytes();
406 core_node.setprop_inplace(cstr!("cpu"), &value)?;
407 core_node.next_subnode()?
408 } else {
409 core_node.delete_and_next_subnode()?
410 };
411 }
412 assert!(iter.is_none());
413 } else {
414 cluster_node.nop()?;
415 }
416 }
417 } else {
418 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
419 }
420
Jiyong Park6a8789a2023-03-21 14:50:59 +0900421 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000422}
423
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900424/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900425fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900426 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900427 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900428 for property in avf_node.properties()? {
429 let name = property.name()?;
430 let value = property.value()?;
431 property_map.insert(
432 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
433 value.to_vec(),
434 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900435 }
436 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900437 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900438}
439
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900440/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
441/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
442fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900443 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900444 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900445 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900446) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900447 let mut root_vm_dt = vm_dt.root_mut()?;
448 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900449 // TODO(b/318431677): Validate nodes beyond /avf.
450 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900451 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900452 if let Some(ref_value) = avf_node.getprop(name)? {
453 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900454 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900455 "Property mismatches while applying overlay VM reference DT. \
456 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
457 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900458 );
459 return Err(FdtError::BadValue);
460 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900461 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900462 }
463 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900464 Ok(())
465}
466
Jiyong Park00ceff32023-03-13 05:43:23 +0000467#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000468struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900469 ranges: [PciAddrRange; 2],
470 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
471 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000472}
473
Jiyong Park6a8789a2023-03-21 14:50:59 +0900474impl PciInfo {
475 const IRQ_MASK_CELLS: usize = 4;
476 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100477 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000478}
479
Jiyong Park6a8789a2023-03-21 14:50:59 +0900480type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
481type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
482type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000483
484/// Iterator that takes N cells as a chunk
485struct CellChunkIterator<'a, const N: usize> {
486 cells: CellIterator<'a>,
487}
488
489impl<'a, const N: usize> CellChunkIterator<'a, N> {
490 fn new(cells: CellIterator<'a>) -> Self {
491 Self { cells }
492 }
493}
494
495impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
496 type Item = [u32; N];
497 fn next(&mut self) -> Option<Self::Item> {
498 let mut ret: Self::Item = [0; N];
499 for i in ret.iter_mut() {
500 *i = self.cells.next()?;
501 }
502 Some(ret)
503 }
504}
505
Jiyong Park6a8789a2023-03-21 14:50:59 +0900506/// Read pci host controller ranges, irq maps, and irq map masks from DT
507fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
508 let node =
509 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
510
511 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
512 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
513 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
514
515 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000516 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
517 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
518
519 if chunks.next().is_some() {
520 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
521 return Err(FdtError::NoSpace);
522 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900523
524 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000525 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
526 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
527
528 if chunks.next().is_some() {
529 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
530 return Err(FdtError::NoSpace);
531 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900532
533 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
534}
535
Jiyong Park0ee65392023-03-27 20:52:45 +0900536fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900537 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900538 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900539 }
540 for irq_mask in pci_info.irq_masks.iter() {
541 validate_pci_irq_mask(irq_mask)?;
542 }
543 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
544 validate_pci_irq_map(irq_map, idx)?;
545 }
546 Ok(())
547}
548
Jiyong Park0ee65392023-03-27 20:52:45 +0900549fn validate_pci_addr_range(
550 range: &PciAddrRange,
551 memory_range: &Range<usize>,
552) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900553 let mem_flags = PciMemoryFlags(range.addr.0);
554 let range_type = mem_flags.range_type();
555 let prefetchable = mem_flags.prefetchable();
556 let bus_addr = range.addr.1;
557 let cpu_addr = range.parent_addr;
558 let size = range.size;
559
560 if range_type != PciRangeType::Memory64 {
561 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
562 return Err(RebootReason::InvalidFdt);
563 }
564 if prefetchable {
565 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
566 return Err(RebootReason::InvalidFdt);
567 }
568 // Enforce ID bus-to-cpu mappings, as used by crosvm.
569 if bus_addr != cpu_addr {
570 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
571 return Err(RebootReason::InvalidFdt);
572 }
573
Jiyong Park0ee65392023-03-27 20:52:45 +0900574 let Some(bus_end) = bus_addr.checked_add(size) else {
575 error!("PCI address range size {:#x} overflows", size);
576 return Err(RebootReason::InvalidFdt);
577 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000578 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900579 error!("PCI address end {:#x} is outside of translatable range", bus_end);
580 return Err(RebootReason::InvalidFdt);
581 }
582
583 let memory_start = memory_range.start.try_into().unwrap();
584 let memory_end = memory_range.end.try_into().unwrap();
585
586 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
587 error!(
588 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
589 bus_addr, bus_end, memory_start, memory_end
590 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900591 return Err(RebootReason::InvalidFdt);
592 }
593
594 Ok(())
595}
596
597fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000598 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
599 const IRQ_MASK_ADDR_ME: u32 = 0x0;
600 const IRQ_MASK_ADDR_LO: u32 = 0x0;
601 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900602 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000603 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604 if *irq_mask != EXPECTED {
605 error!("Invalid PCI irq mask {:#?}", irq_mask);
606 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000607 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900608 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000609}
610
Jiyong Park6a8789a2023-03-21 14:50:59 +0900611fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000612 const PCI_DEVICE_IDX: usize = 11;
613 const PCI_IRQ_ADDR_ME: u32 = 0;
614 const PCI_IRQ_ADDR_LO: u32 = 0;
615 const PCI_IRQ_INTC: u32 = 1;
616 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
617 const GIC_SPI: u32 = 0;
618 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
619
Jiyong Park6a8789a2023-03-21 14:50:59 +0900620 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
621 let pci_irq_number = irq_map[3];
622 let _controller_phandle = irq_map[4]; // skipped.
623 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
624 // interrupt-cells is <3> for GIC
625 let gic_peripheral_interrupt_type = irq_map[7];
626 let gic_irq_number = irq_map[8];
627 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000628
Jiyong Park6a8789a2023-03-21 14:50:59 +0900629 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
630 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000631
Jiyong Park6a8789a2023-03-21 14:50:59 +0900632 if pci_addr != expected_pci_addr {
633 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
634 {:#x} {:#x} {:#x}",
635 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
636 return Err(RebootReason::InvalidFdt);
637 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000638
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639 if pci_irq_number != PCI_IRQ_INTC {
640 error!(
641 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
642 pci_irq_number, PCI_IRQ_INTC
643 );
644 return Err(RebootReason::InvalidFdt);
645 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000646
Jiyong Park6a8789a2023-03-21 14:50:59 +0900647 if gic_addr != (0, 0) {
648 error!(
649 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
650 {:#x} {:#x}",
651 gic_addr.0, gic_addr.1, 0, 0
652 );
653 return Err(RebootReason::InvalidFdt);
654 }
655
656 if gic_peripheral_interrupt_type != GIC_SPI {
657 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
658 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
659 return Err(RebootReason::InvalidFdt);
660 }
661
662 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
663 if gic_irq_number != irq_nr {
664 error!(
665 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
666 gic_irq_number, irq_nr
667 );
668 return Err(RebootReason::InvalidFdt);
669 }
670
671 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
672 error!(
673 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
674 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
675 );
676 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000677 }
678 Ok(())
679}
680
Jiyong Park9c63cd12023-03-21 17:53:07 +0900681fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
682 let mut node = fdt
683 .root_mut()?
684 .next_compatible(cstr!("pci-host-cam-generic"))?
685 .ok_or(FdtError::NotFound)?;
686
687 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
688 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
689
690 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
691 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
692
693 node.setprop_inplace(
694 cstr!("ranges"),
695 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
696 )
697}
698
Jiyong Park00ceff32023-03-13 05:43:23 +0000699#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900700struct SerialInfo {
701 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000702}
703
704impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900705 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000706}
707
Jiyong Park6a8789a2023-03-21 14:50:59 +0900708fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000709 let mut addrs = ArrayVec::new();
710
711 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
712 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000713 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900714 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000715 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000716 if serial_nodes.next().is_some() {
717 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
718 }
719
Jiyong Park6a8789a2023-03-21 14:50:59 +0900720 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000721}
722
Jiyong Park9c63cd12023-03-21 17:53:07 +0900723/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
724fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
725 let name = cstr!("ns16550a");
726 let mut next = fdt.root_mut()?.next_compatible(name);
727 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000728 let reg =
729 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900730 next = if !serial_info.addrs.contains(&reg.addr) {
731 current.delete_and_next_compatible(name)
732 } else {
733 current.next_compatible(name)
734 }
735 }
736 Ok(())
737}
738
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700739fn validate_swiotlb_info(
740 swiotlb_info: &SwiotlbInfo,
741 memory: &Range<usize>,
742) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900743 let size = swiotlb_info.size;
744 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000745
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700746 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000747 error!("Invalid swiotlb size {:#x}", size);
748 return Err(RebootReason::InvalidFdt);
749 }
750
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000751 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000752 error!("Invalid swiotlb alignment {:#x}", align);
753 return Err(RebootReason::InvalidFdt);
754 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700755
Alice Wang9cfbfd62023-06-14 11:19:03 +0000756 if let Some(addr) = swiotlb_info.addr {
757 if addr.checked_add(size).is_none() {
758 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
759 return Err(RebootReason::InvalidFdt);
760 }
761 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700762 if let Some(range) = swiotlb_info.fixed_range() {
763 if !range.is_within(memory) {
764 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
765 return Err(RebootReason::InvalidFdt);
766 }
767 }
768
Jiyong Park6a8789a2023-03-21 14:50:59 +0900769 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000770}
771
Jiyong Park9c63cd12023-03-21 17:53:07 +0900772fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
773 let mut node =
774 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700775
776 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000777 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700778 cstr!("reg"),
779 range.start.try_into().unwrap(),
780 range.len().try_into().unwrap(),
781 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000782 node.nop_property(cstr!("size"))?;
783 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700784 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000785 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700786 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000787 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700788 }
789
Jiyong Park9c63cd12023-03-21 17:53:07 +0900790 Ok(())
791}
792
793fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
794 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
795 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
796 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
797 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
798
799 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000800 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
801 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000802 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900803
804 // range1 is just below range0
805 range1.addr = addr - size;
806 range1.size = Some(size);
807
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000808 let (addr0, size0) = range0.to_cells();
809 let (addr1, size1) = range1.to_cells();
810 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900811
812 let mut node =
813 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
814 node.setprop_inplace(cstr!("reg"), flatten(&value))
815}
816
817fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
818 const NUM_INTERRUPTS: usize = 4;
819 const CELLS_PER_INTERRUPT: usize = 3;
820 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
821 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
822 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
823 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
824
825 let num_cpus: u32 = num_cpus.try_into().unwrap();
826 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
827 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
828 *v |= cpu_mask;
829 }
830 for v in value.iter_mut() {
831 *v = v.to_be();
832 }
833
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000834 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900835
836 let mut node =
837 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000838 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900839}
840
Jiyong Park00ceff32023-03-13 05:43:23 +0000841#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800842struct VcpufreqInfo {
843 addr: u64,
844 size: u64,
845}
846
847fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
848 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
849 if let Some(info) = vcpufreq_info {
850 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
851 } else {
852 node.nop()
853 }
854}
855
856#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900857pub struct DeviceTreeInfo {
858 pub kernel_range: Option<Range<usize>>,
859 pub initrd_range: Option<Range<usize>>,
860 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900861 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000862 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000863 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000864 pci_info: PciInfo,
865 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700866 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900867 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900868 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800869 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000870}
871
872impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000873 const MAX_CPUS: usize = 16;
874
875 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000876 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
877
878 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
879 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000880}
881
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900882pub fn sanitize_device_tree(
883 fdt: &mut [u8],
884 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900885 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900886) -> Result<DeviceTreeInfo, RebootReason> {
887 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
888 error!("Failed to load FDT: {e}");
889 RebootReason::InvalidFdt
890 })?;
891
892 let vm_dtbo = match vm_dtbo {
893 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
894 error!("Failed to load VM DTBO: {e}");
895 RebootReason::InvalidFdt
896 })?),
897 None => None,
898 };
899
900 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900901
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000902 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
903 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
904 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900905 error!("Failed to instantiate FDT from the template DT: {e}");
906 RebootReason::InvalidFdt
907 })?;
908
Jaewan Kim9220e852023-12-01 10:58:40 +0900909 fdt.unpack().map_err(|e| {
910 error!("Failed to unpack DT for patching: {e}");
911 RebootReason::InvalidFdt
912 })?;
913
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900914 if let Some(device_assignment_info) = &info.device_assignment {
915 let vm_dtbo = vm_dtbo.unwrap();
916 device_assignment_info.filter(vm_dtbo).map_err(|e| {
917 error!("Failed to filter VM DTBO: {e}");
918 RebootReason::InvalidFdt
919 })?;
920 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
921 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
922 // it can only be instantiated after validation.
923 unsafe {
924 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
925 error!("Failed to apply filtered VM DTBO: {e}");
926 RebootReason::InvalidFdt
927 })?;
928 }
929 }
930
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900931 if let Some(vm_ref_dt) = vm_ref_dt {
932 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
933 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900934 RebootReason::InvalidFdt
935 })?;
936
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900937 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
938 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900939 RebootReason::InvalidFdt
940 })?;
941 }
942
Jiyong Park9c63cd12023-03-21 17:53:07 +0900943 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900944
Jaewan Kim19b984f2023-12-04 15:16:50 +0900945 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
946
Jaewan Kim9220e852023-12-01 10:58:40 +0900947 fdt.pack().map_err(|e| {
948 error!("Failed to unpack DT after patching: {e}");
949 RebootReason::InvalidFdt
950 })?;
951
Jiyong Park6a8789a2023-03-21 14:50:59 +0900952 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900953}
954
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900955fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900956 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
957 error!("Failed to read kernel range from DT: {e}");
958 RebootReason::InvalidFdt
959 })?;
960
961 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
962 error!("Failed to read initrd range from DT: {e}");
963 RebootReason::InvalidFdt
964 })?;
965
Alice Wang0d527472023-06-13 14:55:38 +0000966 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900967
Jiyong Parke9d87e82023-03-21 19:28:40 +0900968 let bootargs = read_bootargs_from(fdt).map_err(|e| {
969 error!("Failed to read bootargs from DT: {e}");
970 RebootReason::InvalidFdt
971 })?;
972
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000973 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000974 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900975 RebootReason::InvalidFdt
976 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000977 validate_cpu_info(&cpus).map_err(|e| {
978 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +0000979 RebootReason::InvalidFdt
980 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900981
David Dai9bdb10c2024-02-01 22:42:54 -0800982 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
983 error!("Failed to read vcpufreq info from DT: {e}");
984 RebootReason::InvalidFdt
985 })?;
986 if let Some(ref info) = vcpufreq_info {
987 validate_vcpufreq_info(info, &cpus).map_err(|e| {
988 error!("Failed to validate vcpufreq info from DT: {e}");
989 RebootReason::InvalidFdt
990 })?;
991 }
992
Jiyong Park6a8789a2023-03-21 14:50:59 +0900993 let pci_info = read_pci_info_from(fdt).map_err(|e| {
994 error!("Failed to read pci info from DT: {e}");
995 RebootReason::InvalidFdt
996 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900997 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900998
999 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1000 error!("Failed to read serial info from DT: {e}");
1001 RebootReason::InvalidFdt
1002 })?;
1003
Alice Wang9cfbfd62023-06-14 11:19:03 +00001004 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001005 error!("Failed to read swiotlb info from DT: {e}");
1006 RebootReason::InvalidFdt
1007 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001008 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001009
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001010 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001011 Some(vm_dtbo) => {
1012 if let Some(hypervisor) = hyp::get_device_assigner() {
1013 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1014 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1015 RebootReason::InvalidFdt
1016 })?
1017 } else {
1018 warn!(
1019 "Device assignment is ignored because device assigning hypervisor is missing"
1020 );
1021 None
1022 }
1023 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001024 None => None,
1025 };
1026
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001027 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001028 error!("Failed to read names of properties under /avf from DT: {e}");
1029 RebootReason::InvalidFdt
1030 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001031
Jiyong Park00ceff32023-03-13 05:43:23 +00001032 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001033 kernel_range,
1034 initrd_range,
1035 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001036 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001037 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001038 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001039 pci_info,
1040 serial_info,
1041 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001042 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001043 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001044 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001045 })
1046}
1047
Jiyong Park9c63cd12023-03-21 17:53:07 +09001048fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1049 if let Some(initrd_range) = &info.initrd_range {
1050 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1051 error!("Failed to patch initrd range to DT: {e}");
1052 RebootReason::InvalidFdt
1053 })?;
1054 }
1055 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1056 error!("Failed to patch memory range to DT: {e}");
1057 RebootReason::InvalidFdt
1058 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001059 if let Some(bootargs) = &info.bootargs {
1060 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1061 error!("Failed to patch bootargs to DT: {e}");
1062 RebootReason::InvalidFdt
1063 })?;
1064 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001065 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001066 error!("Failed to patch cpus to DT: {e}");
1067 RebootReason::InvalidFdt
1068 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001069 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1070 error!("Failed to patch vcpufreq info to DT: {e}");
1071 RebootReason::InvalidFdt
1072 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001073 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1074 error!("Failed to patch pci info to DT: {e}");
1075 RebootReason::InvalidFdt
1076 })?;
1077 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1078 error!("Failed to patch serial info to DT: {e}");
1079 RebootReason::InvalidFdt
1080 })?;
1081 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1082 error!("Failed to patch swiotlb info to DT: {e}");
1083 RebootReason::InvalidFdt
1084 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001085 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001086 error!("Failed to patch gic info to DT: {e}");
1087 RebootReason::InvalidFdt
1088 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001089 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001090 error!("Failed to patch timer info to DT: {e}");
1091 RebootReason::InvalidFdt
1092 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001093 if let Some(device_assignment) = &info.device_assignment {
1094 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1095 // then VM DTBO's underlying slice is allocated.
1096 device_assignment.patch(fdt).map_err(|e| {
1097 error!("Failed to patch device assignment info to DT: {e}");
1098 RebootReason::InvalidFdt
1099 })?;
1100 }
Jiyong Parke9d87e82023-03-21 19:28:40 +09001101
Jiyong Park9c63cd12023-03-21 17:53:07 +09001102 Ok(())
1103}
1104
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001105/// Modifies the input DT according to the fields of the configuration.
1106pub fn modify_for_next_stage(
1107 fdt: &mut Fdt,
1108 bcc: &[u8],
1109 new_instance: bool,
1110 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001111 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001112 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001113 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001114) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001115 if let Some(debug_policy) = debug_policy {
1116 let backup = Vec::from(fdt.as_slice());
1117 fdt.unpack()?;
1118 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1119 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1120 info!("Debug policy applied.");
1121 } else {
1122 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1123 fdt.unpack()?;
1124 }
1125 } else {
1126 info!("No debug policy found.");
1127 fdt.unpack()?;
1128 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001129
Jiyong Parke9d87e82023-03-21 19:28:40 +09001130 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001131
Alice Wang56ec45b2023-06-15 08:30:32 +00001132 if let Some(mut chosen) = fdt.chosen_mut()? {
1133 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1134 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001135 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001136 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001137 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001138 if let Some(bootargs) = read_bootargs_from(fdt)? {
1139 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1140 }
1141 }
1142
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001143 fdt.pack()?;
1144
1145 Ok(())
1146}
1147
Jiyong Parke9d87e82023-03-21 19:28:40 +09001148/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1149fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001150 // We reject DTs with missing reserved-memory node as validation should have checked that the
1151 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001152 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001153
Jiyong Parke9d87e82023-03-21 19:28:40 +09001154 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001155
Jiyong Parke9d87e82023-03-21 19:28:40 +09001156 let addr: u64 = addr.try_into().unwrap();
1157 let size: u64 = size.try_into().unwrap();
1158 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001159}
1160
Alice Wang56ec45b2023-06-15 08:30:32 +00001161fn empty_or_delete_prop(
1162 fdt_node: &mut FdtNodeMut,
1163 prop_name: &CStr,
1164 keep_prop: bool,
1165) -> libfdt::Result<()> {
1166 if keep_prop {
1167 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001168 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001169 fdt_node
1170 .delprop(prop_name)
1171 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001172 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001173}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001174
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001175/// Apply the debug policy overlay to the guest DT.
1176///
1177/// 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 +00001178fn apply_debug_policy(
1179 fdt: &mut Fdt,
1180 backup_fdt: &Fdt,
1181 debug_policy: &[u8],
1182) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001183 let mut debug_policy = Vec::from(debug_policy);
1184 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001185 Ok(overlay) => overlay,
1186 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001187 warn!("Corrupted debug policy found: {e}. Not applying.");
1188 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001189 }
1190 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001191
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001192 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001193 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001194 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001195 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001196 // A successful restoration is considered success because an invalid debug policy
1197 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001198 Ok(false)
1199 } else {
1200 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001201 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001202}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001203
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001204fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001205 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1206 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1207 return Ok(value == 1);
1208 }
1209 }
1210 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1211}
1212
1213fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001214 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1215 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001216
1217 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1218 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1219 ("crashkernel", Box::new(|_| has_crashkernel)),
1220 ("console", Box::new(|_| has_console)),
1221 ];
1222
1223 // parse and filter out unwanted
1224 let mut filtered = Vec::new();
1225 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1226 info!("Invalid bootarg: {e}");
1227 FdtError::BadValue
1228 })? {
1229 match accepted.iter().find(|&t| t.0 == arg.name()) {
1230 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1231 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1232 }
1233 }
1234
1235 // flatten into a new C-string
1236 let mut new_bootargs = Vec::new();
1237 for (i, arg) in filtered.iter().enumerate() {
1238 if i != 0 {
1239 new_bootargs.push(b' '); // separator
1240 }
1241 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1242 }
1243 new_bootargs.push(b'\0');
1244
1245 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1246 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1247}