blob: 92065880f0b9c729995c052545115abfa85a7bec [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! High-level FDT functions.
16
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090017use crate::bootargs::BootArgsIterator;
Jaewan Kim50246682024-03-11 23:18:54 +090018use crate::device_assignment::{self, DeviceAssignmentInfo, VmDtbo};
Jiyong Park00ceff32023-03-13 05:43:23 +000019use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090020use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000024use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090025use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090026use core::cmp::max;
27use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000029use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090030use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use 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;
Pierre-Clément Tosia9b345f2024-04-27 01:01:42 +010049use vmbase::hyp;
Alice Wang63f4c9e2023-06-12 09:36:43 +000050use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000051use vmbase::memory::SIZE_4KB;
52use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000053use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000054use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000055
Alice Wangabc7d632023-06-14 09:10:14 +000056/// An enumeration of errors that can occur during the FDT validation.
57#[derive(Clone, Debug)]
58pub enum FdtValidationError {
59 /// Invalid CPU count.
60 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080061 /// Invalid VCpufreq Range.
62 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000063 /// Forbidden /avf/untrusted property.
64 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000065}
66
67impl fmt::Display for FdtValidationError {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 match self {
70 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000071 Self::InvalidVcpufreq(addr, size) => {
72 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
73 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000074 Self::ForbiddenUntrustedProp(name) => {
75 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
76 }
Alice Wangabc7d632023-06-14 09:10:14 +000077 }
78 }
79}
80
Jiyong Park6a8789a2023-03-21 14:50:59 +090081/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
82/// not an error.
83fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090084 let addr = cstr!("kernel-address");
85 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000086
Jiyong Parkb87f3302023-03-21 10:03:11 +090087 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000088 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
89 let addr = addr as usize;
90 let size = size as usize;
91
92 return Ok(Some(addr..(addr + size)));
93 }
94 }
95
96 Ok(None)
97}
98
Jiyong Park6a8789a2023-03-21 14:50:59 +090099/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
100/// error as there can be initrd-less VM.
101fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +0900102 let start = cstr!("linux,initrd-start");
103 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000104
105 if let Some(chosen) = fdt.chosen()? {
106 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
107 return Ok(Some((start as usize)..(end as usize)));
108 }
109 }
110
111 Ok(None)
112}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000113
Jiyong Park9c63cd12023-03-21 17:53:07 +0900114fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
115 let start = u32::try_from(initrd_range.start).unwrap();
116 let end = u32::try_from(initrd_range.end).unwrap();
117
118 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
119 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
120 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
121 Ok(())
122}
123
Jiyong Parke9d87e82023-03-21 19:28:40 +0900124fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
125 if let Some(chosen) = fdt.chosen()? {
126 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
127 // We need to copy the string to heap because the original fdt will be invalidated
128 // by the templated DT
129 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
130 return Ok(Some(copy));
131 }
132 }
133 Ok(None)
134}
135
136fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
137 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900138 // This function is called before the verification is done. So, we just copy the bootargs to
139 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
140 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900141 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
142}
143
Alice Wang0d527472023-06-13 14:55:38 +0000144/// Reads and validates the memory range in the DT.
145///
146/// Only one memory range is expected with the crosvm setup for now.
147fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
148 let mut memory = fdt.memory().map_err(|e| {
149 error!("Failed to read memory range from DT: {e}");
150 RebootReason::InvalidFdt
151 })?;
152 let range = memory.next().ok_or_else(|| {
153 error!("The /memory node in the DT contains no range.");
154 RebootReason::InvalidFdt
155 })?;
156 if memory.next().is_some() {
157 warn!(
158 "The /memory node in the DT contains more than one memory range, \
159 while only one is expected."
160 );
161 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900162 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000163 if base != MEM_START {
164 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000165 return Err(RebootReason::InvalidFdt);
166 }
167
Jiyong Park6a8789a2023-03-21 14:50:59 +0900168 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000169 if size % GUEST_PAGE_SIZE != 0 {
170 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
171 return Err(RebootReason::InvalidFdt);
172 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000173
Jiyong Park6a8789a2023-03-21 14:50:59 +0900174 if size == 0 {
175 error!("Memory size is 0");
176 return Err(RebootReason::InvalidFdt);
177 }
Alice Wang0d527472023-06-13 14:55:38 +0000178 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000179}
180
Jiyong Park9c63cd12023-03-21 17:53:07 +0900181fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000182 let addr = u64::try_from(MEM_START).unwrap();
183 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900184 fdt.node_mut(cstr!("/memory"))?
185 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000186 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900187}
188
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000189#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800190struct CpuInfo {
191 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800192 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800193}
194
195impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800196 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800197}
198
199fn read_opp_info_from(
200 opp_node: FdtNode,
201) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
202 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100203 let mut opp_nodes = opp_node.subnodes()?;
204 for subnode in opp_nodes.by_ref().take(table.capacity()) {
David Dai9bdb10c2024-02-01 22:42:54 -0800205 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
206 table.push(prop);
207 }
208
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100209 if opp_nodes.next().is_some() {
210 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
211 }
212
David Dai9bdb10c2024-02-01 22:42:54 -0800213 Ok(table)
214}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900215
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000216#[derive(Debug, Default)]
217struct ClusterTopology {
218 // TODO: Support multi-level clusters & threads.
219 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
220}
221
222impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700223 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000224}
225
226#[derive(Debug, Default)]
227struct CpuTopology {
228 // TODO: Support sockets.
229 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
230}
231
232impl CpuTopology {
233 const MAX_CLUSTERS: usize = 3;
234}
235
236fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
237 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
238 return Ok(None);
239 };
240
241 let mut topology = BTreeMap::new();
242 for n in 0..CpuTopology::MAX_CLUSTERS {
243 let name = CString::new(format!("cluster{n}")).unwrap();
244 let Some(cluster) = cpu_map.subnode(&name)? else {
245 break;
246 };
247 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800248 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000249 let Some(core) = cluster.subnode(&name)? else {
250 break;
251 };
252 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
253 let prev = topology.insert(cpu.try_into()?, (n, m));
254 if prev.is_some() {
255 return Err(FdtError::BadValue);
256 }
257 }
258 }
259
260 Ok(Some(topology))
261}
262
263fn read_cpu_info_from(
264 fdt: &Fdt,
265) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000266 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000267
268 let cpu_map = read_cpu_map_from(fdt)?;
269 let mut topology: CpuTopology = Default::default();
270
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100271 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,armv8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000272 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800273 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800274 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
275 let opptable_info = if let Some(phandle) = opp_phandle {
276 let phandle = phandle.try_into()?;
277 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
278 Some(read_opp_info_from(node)?)
279 } else {
280 None
281 };
David Dai50168a32024-02-14 17:00:48 -0800282 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000283 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000284
285 if let Some(ref cpu_map) = cpu_map {
286 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800287 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000288 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800289 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000290 return Err(FdtError::BadValue);
291 }
David Dai8f476cb2024-02-15 21:57:01 -0800292 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000293 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900294 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000295
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000296 if cpu_nodes.next().is_some() {
297 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
298 }
299
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000300 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900301}
302
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000303fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
304 if cpus.is_empty() {
305 return Err(FdtValidationError::InvalidCpuCount(0));
306 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000307 Ok(())
308}
309
David Dai9bdb10c2024-02-01 22:42:54 -0800310fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000311 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
312 let Some(node) = nodes.next() else {
313 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800314 };
315
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000316 if nodes.next().is_some() {
317 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
318 }
319
320 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
321 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000322 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000323
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000324 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800325}
326
327fn validate_vcpufreq_info(
328 vcpufreq_info: &VcpufreqInfo,
329 cpus: &[CpuInfo],
330) -> Result<(), FdtValidationError> {
331 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000332 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800333
334 let base = vcpufreq_info.addr;
335 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000336 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
337
338 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800339 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000340 }
David Dai9bdb10c2024-02-01 22:42:54 -0800341
342 Ok(())
343}
344
345fn patch_opptable(
346 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800347 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800348) -> libfdt::Result<()> {
349 let oppcompat = cstr!("operating-points-v2");
350 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000351
352 let Some(opptable) = opptable else {
353 return next.nop();
354 };
355
David Dai9bdb10c2024-02-01 22:42:54 -0800356 let mut next_subnode = next.first_subnode()?;
357
358 for entry in opptable {
359 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
360 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
361 next_subnode = subnode.next_subnode()?;
362 }
363
364 while let Some(current) = next_subnode {
365 next_subnode = current.delete_and_next_subnode()?;
366 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000367
David Dai9bdb10c2024-02-01 22:42:54 -0800368 Ok(())
369}
370
371// TODO(ptosi): Rework FdtNodeMut and replace this function.
372fn get_nth_compatible<'a>(
373 fdt: &'a mut Fdt,
374 n: usize,
375 compat: &CStr,
376) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000377 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800378 for _ in 0..n {
379 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
380 }
381 Ok(node)
382}
383
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000384fn patch_cpus(
385 fdt: &mut Fdt,
386 cpus: &[CpuInfo],
387 topology: &Option<CpuTopology>,
388) -> libfdt::Result<()> {
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100389 const COMPAT: &CStr = cstr!("arm,armv8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000390 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800391 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800392 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000393 let phandle = cur.as_node().get_phandle()?.unwrap();
394 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800395 if let Some(cpu_capacity) = cpu.cpu_capacity {
396 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
397 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000398 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900399 }
David Dai9bdb10c2024-02-01 22:42:54 -0800400 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900401 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000402 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900403 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000404
405 if let Some(topology) = topology {
406 for (n, cluster) in topology.clusters.iter().enumerate() {
407 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
408 let cluster_node = fdt.node_mut(&path)?.unwrap();
409 if let Some(cluster) = cluster {
410 let mut iter = cluster_node.first_subnode()?;
411 for core in cluster.cores {
412 let mut core_node = iter.unwrap();
413 iter = if let Some(core_idx) = core {
414 let phandle = *cpu_phandles.get(core_idx).unwrap();
415 let value = u32::from(phandle).to_be_bytes();
416 core_node.setprop_inplace(cstr!("cpu"), &value)?;
417 core_node.next_subnode()?
418 } else {
419 core_node.delete_and_next_subnode()?
420 };
421 }
422 assert!(iter.is_none());
423 } else {
424 cluster_node.nop()?;
425 }
426 }
427 } else {
428 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
429 }
430
Jiyong Park6a8789a2023-03-21 14:50:59 +0900431 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000432}
433
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000434/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
435/// the guest that don't require being validated by pvmfw.
436fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
437 let mut props = BTreeMap::new();
438 if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
439 for property in node.properties()? {
440 let name = property.name()?;
441 let value = property.value()?;
442 props.insert(CString::from(name), value.to_vec());
443 }
444 if node.subnodes()?.next().is_some() {
445 warn!("Discarding unexpected /avf/untrusted subnodes.");
446 }
447 }
448
449 Ok(props)
450}
451
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900452/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900453fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900454 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900455 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900456 for property in avf_node.properties()? {
457 let name = property.name()?;
458 let value = property.value()?;
459 property_map.insert(
460 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
461 value.to_vec(),
462 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900463 }
464 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900465 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900466}
467
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000468fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
469 const FORBIDDEN_PROPS: &[&CStr] =
470 &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
471
472 for name in FORBIDDEN_PROPS {
473 if props.contains_key(*name) {
474 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
475 }
476 }
477
478 Ok(())
479}
480
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900481/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
482/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
483fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900484 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900485 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900486 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900487) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000488 let root_vm_dt = vm_dt.root_mut();
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900489 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900490 // TODO(b/318431677): Validate nodes beyond /avf.
491 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900492 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900493 if let Some(ref_value) = avf_node.getprop(name)? {
494 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900495 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900496 "Property mismatches while applying overlay VM reference DT. \
497 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
498 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900499 );
500 return Err(FdtError::BadValue);
501 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900502 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900503 }
504 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900505 Ok(())
506}
507
Jiyong Park00ceff32023-03-13 05:43:23 +0000508#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000509struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900510 ranges: [PciAddrRange; 2],
511 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
512 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000513}
514
Jiyong Park6a8789a2023-03-21 14:50:59 +0900515impl PciInfo {
516 const IRQ_MASK_CELLS: usize = 4;
517 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100518 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000519}
520
Jiyong Park6a8789a2023-03-21 14:50:59 +0900521type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
522type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
523type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000524
525/// Iterator that takes N cells as a chunk
526struct CellChunkIterator<'a, const N: usize> {
527 cells: CellIterator<'a>,
528}
529
530impl<'a, const N: usize> CellChunkIterator<'a, N> {
531 fn new(cells: CellIterator<'a>) -> Self {
532 Self { cells }
533 }
534}
535
536impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
537 type Item = [u32; N];
538 fn next(&mut self) -> Option<Self::Item> {
539 let mut ret: Self::Item = [0; N];
540 for i in ret.iter_mut() {
541 *i = self.cells.next()?;
542 }
543 Some(ret)
544 }
545}
546
Jiyong Park6a8789a2023-03-21 14:50:59 +0900547/// Read pci host controller ranges, irq maps, and irq map masks from DT
548fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
549 let node =
550 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
551
552 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
553 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
554 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
555
556 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000557 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
558 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
559
560 if chunks.next().is_some() {
561 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
562 return Err(FdtError::NoSpace);
563 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900564
565 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000566 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
567 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
568
569 if chunks.next().is_some() {
570 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
571 return Err(FdtError::NoSpace);
572 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900573
574 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
575}
576
Jiyong Park0ee65392023-03-27 20:52:45 +0900577fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900578 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900579 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900580 }
581 for irq_mask in pci_info.irq_masks.iter() {
582 validate_pci_irq_mask(irq_mask)?;
583 }
584 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
585 validate_pci_irq_map(irq_map, idx)?;
586 }
587 Ok(())
588}
589
Jiyong Park0ee65392023-03-27 20:52:45 +0900590fn validate_pci_addr_range(
591 range: &PciAddrRange,
592 memory_range: &Range<usize>,
593) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900594 let mem_flags = PciMemoryFlags(range.addr.0);
595 let range_type = mem_flags.range_type();
596 let prefetchable = mem_flags.prefetchable();
597 let bus_addr = range.addr.1;
598 let cpu_addr = range.parent_addr;
599 let size = range.size;
600
601 if range_type != PciRangeType::Memory64 {
602 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
603 return Err(RebootReason::InvalidFdt);
604 }
605 if prefetchable {
606 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
607 return Err(RebootReason::InvalidFdt);
608 }
609 // Enforce ID bus-to-cpu mappings, as used by crosvm.
610 if bus_addr != cpu_addr {
611 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
612 return Err(RebootReason::InvalidFdt);
613 }
614
Jiyong Park0ee65392023-03-27 20:52:45 +0900615 let Some(bus_end) = bus_addr.checked_add(size) else {
616 error!("PCI address range size {:#x} overflows", size);
617 return Err(RebootReason::InvalidFdt);
618 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000619 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900620 error!("PCI address end {:#x} is outside of translatable range", bus_end);
621 return Err(RebootReason::InvalidFdt);
622 }
623
624 let memory_start = memory_range.start.try_into().unwrap();
625 let memory_end = memory_range.end.try_into().unwrap();
626
627 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
628 error!(
629 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
630 bus_addr, bus_end, memory_start, memory_end
631 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900632 return Err(RebootReason::InvalidFdt);
633 }
634
635 Ok(())
636}
637
638fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000639 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
640 const IRQ_MASK_ADDR_ME: u32 = 0x0;
641 const IRQ_MASK_ADDR_LO: u32 = 0x0;
642 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900643 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000644 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900645 if *irq_mask != EXPECTED {
646 error!("Invalid PCI irq mask {:#?}", irq_mask);
647 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000648 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900649 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000650}
651
Jiyong Park6a8789a2023-03-21 14:50:59 +0900652fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000653 const PCI_DEVICE_IDX: usize = 11;
654 const PCI_IRQ_ADDR_ME: u32 = 0;
655 const PCI_IRQ_ADDR_LO: u32 = 0;
656 const PCI_IRQ_INTC: u32 = 1;
657 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
658 const GIC_SPI: u32 = 0;
659 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
660
Jiyong Park6a8789a2023-03-21 14:50:59 +0900661 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
662 let pci_irq_number = irq_map[3];
663 let _controller_phandle = irq_map[4]; // skipped.
664 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
665 // interrupt-cells is <3> for GIC
666 let gic_peripheral_interrupt_type = irq_map[7];
667 let gic_irq_number = irq_map[8];
668 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000669
Jiyong Park6a8789a2023-03-21 14:50:59 +0900670 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
671 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000672
Jiyong Park6a8789a2023-03-21 14:50:59 +0900673 if pci_addr != expected_pci_addr {
674 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
675 {:#x} {:#x} {:#x}",
676 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
677 return Err(RebootReason::InvalidFdt);
678 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000679
Jiyong Park6a8789a2023-03-21 14:50:59 +0900680 if pci_irq_number != PCI_IRQ_INTC {
681 error!(
682 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
683 pci_irq_number, PCI_IRQ_INTC
684 );
685 return Err(RebootReason::InvalidFdt);
686 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000687
Jiyong Park6a8789a2023-03-21 14:50:59 +0900688 if gic_addr != (0, 0) {
689 error!(
690 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
691 {:#x} {:#x}",
692 gic_addr.0, gic_addr.1, 0, 0
693 );
694 return Err(RebootReason::InvalidFdt);
695 }
696
697 if gic_peripheral_interrupt_type != GIC_SPI {
698 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
699 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
700 return Err(RebootReason::InvalidFdt);
701 }
702
703 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
704 if gic_irq_number != irq_nr {
705 error!(
706 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
707 gic_irq_number, irq_nr
708 );
709 return Err(RebootReason::InvalidFdt);
710 }
711
712 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
713 error!(
714 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
715 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
716 );
717 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000718 }
719 Ok(())
720}
721
Jiyong Park9c63cd12023-03-21 17:53:07 +0900722fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000723 let mut node =
724 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900725
726 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
727 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
728
729 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
730 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
731
732 node.setprop_inplace(
733 cstr!("ranges"),
734 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
735 )
736}
737
Jiyong Park00ceff32023-03-13 05:43:23 +0000738#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900739struct SerialInfo {
740 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000741}
742
743impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900744 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000745}
746
Jiyong Park6a8789a2023-03-21 14:50:59 +0900747fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000748 let mut addrs = ArrayVec::new();
749
750 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
751 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000752 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000754 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000755 if serial_nodes.next().is_some() {
756 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
757 }
758
Jiyong Park6a8789a2023-03-21 14:50:59 +0900759 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000760}
761
Jiyong Park9c63cd12023-03-21 17:53:07 +0900762/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
763fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
764 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000765 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900766 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000767 let reg =
768 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900769 next = if !serial_info.addrs.contains(&reg.addr) {
770 current.delete_and_next_compatible(name)
771 } else {
772 current.next_compatible(name)
773 }
774 }
775 Ok(())
776}
777
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700778fn validate_swiotlb_info(
779 swiotlb_info: &SwiotlbInfo,
780 memory: &Range<usize>,
781) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900782 let size = swiotlb_info.size;
783 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000784
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700785 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000786 error!("Invalid swiotlb size {:#x}", size);
787 return Err(RebootReason::InvalidFdt);
788 }
789
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000790 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000791 error!("Invalid swiotlb alignment {:#x}", align);
792 return Err(RebootReason::InvalidFdt);
793 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700794
Alice Wang9cfbfd62023-06-14 11:19:03 +0000795 if let Some(addr) = swiotlb_info.addr {
796 if addr.checked_add(size).is_none() {
797 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
798 return Err(RebootReason::InvalidFdt);
799 }
800 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700801 if let Some(range) = swiotlb_info.fixed_range() {
802 if !range.is_within(memory) {
803 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
804 return Err(RebootReason::InvalidFdt);
805 }
806 }
807
Jiyong Park6a8789a2023-03-21 14:50:59 +0900808 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000809}
810
Jiyong Park9c63cd12023-03-21 17:53:07 +0900811fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
812 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000813 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700814
815 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000816 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700817 cstr!("reg"),
818 range.start.try_into().unwrap(),
819 range.len().try_into().unwrap(),
820 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000821 node.nop_property(cstr!("size"))?;
822 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700823 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000824 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700825 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000826 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700827 }
828
Jiyong Park9c63cd12023-03-21 17:53:07 +0900829 Ok(())
830}
831
832fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
833 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
834 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
835 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
836 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
837
838 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000839 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
840 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000841 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900842
843 // range1 is just below range0
844 range1.addr = addr - size;
845 range1.size = Some(size);
846
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000847 let (addr0, size0) = range0.to_cells();
848 let (addr1, size1) = range1.to_cells();
849 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900850
851 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000852 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900853 node.setprop_inplace(cstr!("reg"), flatten(&value))
854}
855
856fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
857 const NUM_INTERRUPTS: usize = 4;
858 const CELLS_PER_INTERRUPT: usize = 3;
859 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
860 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
861 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
862 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
863
864 let num_cpus: u32 = num_cpus.try_into().unwrap();
865 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
866 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
867 *v |= cpu_mask;
868 }
869 for v in value.iter_mut() {
870 *v = v.to_be();
871 }
872
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000873 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900874
875 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000876 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000877 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900878}
879
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000880fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
881 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
882 node
883 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000884 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000885 };
886
887 // The node shouldn't already be present; if it is, return the error.
888 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
889
890 for (name, value) in props {
891 node.setprop(name, value)?;
892 }
893
894 Ok(())
895}
896
Jiyong Park00ceff32023-03-13 05:43:23 +0000897#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800898struct VcpufreqInfo {
899 addr: u64,
900 size: u64,
901}
902
903fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
904 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
905 if let Some(info) = vcpufreq_info {
906 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
907 } else {
908 node.nop()
909 }
910}
911
912#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900913pub struct DeviceTreeInfo {
914 pub kernel_range: Option<Range<usize>>,
915 pub initrd_range: Option<Range<usize>>,
916 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900917 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000918 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000919 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000920 pci_info: PciInfo,
921 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700922 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900923 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000924 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900925 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800926 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000927}
928
929impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000930 const MAX_CPUS: usize = 16;
931
932 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000933 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
934
935 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
936 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000937}
938
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900939pub fn sanitize_device_tree(
940 fdt: &mut [u8],
941 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900942 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900943) -> Result<DeviceTreeInfo, RebootReason> {
944 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
945 error!("Failed to load FDT: {e}");
946 RebootReason::InvalidFdt
947 })?;
948
949 let vm_dtbo = match vm_dtbo {
950 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
951 error!("Failed to load VM DTBO: {e}");
952 RebootReason::InvalidFdt
953 })?),
954 None => None,
955 };
956
957 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900958
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000959 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
960 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
961 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900962 error!("Failed to instantiate FDT from the template DT: {e}");
963 RebootReason::InvalidFdt
964 })?;
965
Jaewan Kim9220e852023-12-01 10:58:40 +0900966 fdt.unpack().map_err(|e| {
967 error!("Failed to unpack DT for patching: {e}");
968 RebootReason::InvalidFdt
969 })?;
970
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900971 if let Some(device_assignment_info) = &info.device_assignment {
972 let vm_dtbo = vm_dtbo.unwrap();
973 device_assignment_info.filter(vm_dtbo).map_err(|e| {
974 error!("Failed to filter VM DTBO: {e}");
975 RebootReason::InvalidFdt
976 })?;
977 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
978 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
979 // it can only be instantiated after validation.
980 unsafe {
981 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
982 error!("Failed to apply filtered VM DTBO: {e}");
983 RebootReason::InvalidFdt
984 })?;
985 }
986 }
987
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900988 if let Some(vm_ref_dt) = vm_ref_dt {
989 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
990 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900991 RebootReason::InvalidFdt
992 })?;
993
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900994 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
995 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900996 RebootReason::InvalidFdt
997 })?;
998 }
999
Jiyong Park9c63cd12023-03-21 17:53:07 +09001000 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001001
Jaewan Kim19b984f2023-12-04 15:16:50 +09001002 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1003
Jaewan Kim9220e852023-12-01 10:58:40 +09001004 fdt.pack().map_err(|e| {
1005 error!("Failed to unpack DT after patching: {e}");
1006 RebootReason::InvalidFdt
1007 })?;
1008
Jiyong Park6a8789a2023-03-21 14:50:59 +09001009 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001010}
1011
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001012fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001013 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1014 error!("Failed to read kernel range from DT: {e}");
1015 RebootReason::InvalidFdt
1016 })?;
1017
1018 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1019 error!("Failed to read initrd range from DT: {e}");
1020 RebootReason::InvalidFdt
1021 })?;
1022
Alice Wang0d527472023-06-13 14:55:38 +00001023 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001024
Jiyong Parke9d87e82023-03-21 19:28:40 +09001025 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1026 error!("Failed to read bootargs from DT: {e}");
1027 RebootReason::InvalidFdt
1028 })?;
1029
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001030 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001031 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001032 RebootReason::InvalidFdt
1033 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001034 validate_cpu_info(&cpus).map_err(|e| {
1035 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001036 RebootReason::InvalidFdt
1037 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001038
David Dai9bdb10c2024-02-01 22:42:54 -08001039 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1040 error!("Failed to read vcpufreq info from DT: {e}");
1041 RebootReason::InvalidFdt
1042 })?;
1043 if let Some(ref info) = vcpufreq_info {
1044 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1045 error!("Failed to validate vcpufreq info from DT: {e}");
1046 RebootReason::InvalidFdt
1047 })?;
1048 }
1049
Jiyong Park6a8789a2023-03-21 14:50:59 +09001050 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1051 error!("Failed to read pci info from DT: {e}");
1052 RebootReason::InvalidFdt
1053 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001054 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001055
1056 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1057 error!("Failed to read serial info from DT: {e}");
1058 RebootReason::InvalidFdt
1059 })?;
1060
Alice Wang9cfbfd62023-06-14 11:19:03 +00001061 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001062 error!("Failed to read swiotlb info from DT: {e}");
1063 RebootReason::InvalidFdt
1064 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001065 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001066
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001067 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001068 Some(vm_dtbo) => {
1069 if let Some(hypervisor) = hyp::get_device_assigner() {
1070 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1071 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1072 RebootReason::InvalidFdt
1073 })?
1074 } else {
1075 warn!(
1076 "Device assignment is ignored because device assigning hypervisor is missing"
1077 );
1078 None
1079 }
1080 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001081 None => None,
1082 };
1083
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001084 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1085 error!("Failed to read untrusted properties: {e}");
1086 RebootReason::InvalidFdt
1087 })?;
1088 validate_untrusted_props(&untrusted_props).map_err(|e| {
1089 error!("Failed to validate untrusted properties: {e}");
1090 RebootReason::InvalidFdt
1091 })?;
1092
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001093 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001094 error!("Failed to read names of properties under /avf from DT: {e}");
1095 RebootReason::InvalidFdt
1096 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001097
Jiyong Park00ceff32023-03-13 05:43:23 +00001098 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001099 kernel_range,
1100 initrd_range,
1101 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001102 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001103 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001104 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001105 pci_info,
1106 serial_info,
1107 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001108 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001109 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001110 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001111 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001112 })
1113}
1114
Jiyong Park9c63cd12023-03-21 17:53:07 +09001115fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1116 if let Some(initrd_range) = &info.initrd_range {
1117 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1118 error!("Failed to patch initrd range to DT: {e}");
1119 RebootReason::InvalidFdt
1120 })?;
1121 }
1122 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1123 error!("Failed to patch memory range to DT: {e}");
1124 RebootReason::InvalidFdt
1125 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001126 if let Some(bootargs) = &info.bootargs {
1127 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1128 error!("Failed to patch bootargs to DT: {e}");
1129 RebootReason::InvalidFdt
1130 })?;
1131 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001132 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001133 error!("Failed to patch cpus to DT: {e}");
1134 RebootReason::InvalidFdt
1135 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001136 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1137 error!("Failed to patch vcpufreq info to DT: {e}");
1138 RebootReason::InvalidFdt
1139 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001140 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1141 error!("Failed to patch pci info to DT: {e}");
1142 RebootReason::InvalidFdt
1143 })?;
1144 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1145 error!("Failed to patch serial info to DT: {e}");
1146 RebootReason::InvalidFdt
1147 })?;
1148 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1149 error!("Failed to patch swiotlb info to DT: {e}");
1150 RebootReason::InvalidFdt
1151 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001152 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001153 error!("Failed to patch gic info to DT: {e}");
1154 RebootReason::InvalidFdt
1155 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001156 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001157 error!("Failed to patch timer info to DT: {e}");
1158 RebootReason::InvalidFdt
1159 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001160 if let Some(device_assignment) = &info.device_assignment {
1161 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1162 // then VM DTBO's underlying slice is allocated.
1163 device_assignment.patch(fdt).map_err(|e| {
1164 error!("Failed to patch device assignment info to DT: {e}");
1165 RebootReason::InvalidFdt
1166 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001167 } else {
1168 device_assignment::clean(fdt).map_err(|e| {
1169 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1170 RebootReason::InvalidFdt
1171 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001172 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001173 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1174 error!("Failed to patch untrusted properties: {e}");
1175 RebootReason::InvalidFdt
1176 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001177
Jiyong Park9c63cd12023-03-21 17:53:07 +09001178 Ok(())
1179}
1180
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001181/// Modifies the input DT according to the fields of the configuration.
1182pub fn modify_for_next_stage(
1183 fdt: &mut Fdt,
1184 bcc: &[u8],
1185 new_instance: bool,
1186 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001187 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001188 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001189 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001190) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001191 if let Some(debug_policy) = debug_policy {
1192 let backup = Vec::from(fdt.as_slice());
1193 fdt.unpack()?;
1194 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1195 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1196 info!("Debug policy applied.");
1197 } else {
1198 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1199 fdt.unpack()?;
1200 }
1201 } else {
1202 info!("No debug policy found.");
1203 fdt.unpack()?;
1204 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001205
Jiyong Parke9d87e82023-03-21 19:28:40 +09001206 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001207
Alice Wang56ec45b2023-06-15 08:30:32 +00001208 if let Some(mut chosen) = fdt.chosen_mut()? {
1209 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1210 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001211 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001212 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001213 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001214 if let Some(bootargs) = read_bootargs_from(fdt)? {
1215 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1216 }
1217 }
1218
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001219 fdt.pack()?;
1220
1221 Ok(())
1222}
1223
Jiyong Parke9d87e82023-03-21 19:28:40 +09001224/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1225fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001226 // We reject DTs with missing reserved-memory node as validation should have checked that the
1227 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001228 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001229
Jiyong Parke9d87e82023-03-21 19:28:40 +09001230 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001231
Jiyong Parke9d87e82023-03-21 19:28:40 +09001232 let addr: u64 = addr.try_into().unwrap();
1233 let size: u64 = size.try_into().unwrap();
1234 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001235}
1236
Alice Wang56ec45b2023-06-15 08:30:32 +00001237fn empty_or_delete_prop(
1238 fdt_node: &mut FdtNodeMut,
1239 prop_name: &CStr,
1240 keep_prop: bool,
1241) -> libfdt::Result<()> {
1242 if keep_prop {
1243 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001244 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001245 fdt_node
1246 .delprop(prop_name)
1247 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001248 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001249}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001250
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001251/// Apply the debug policy overlay to the guest DT.
1252///
1253/// 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 +00001254fn apply_debug_policy(
1255 fdt: &mut Fdt,
1256 backup_fdt: &Fdt,
1257 debug_policy: &[u8],
1258) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001259 let mut debug_policy = Vec::from(debug_policy);
1260 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001261 Ok(overlay) => overlay,
1262 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001263 warn!("Corrupted debug policy found: {e}. Not applying.");
1264 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001265 }
1266 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001267
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001268 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001269 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001270 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001271 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001272 // A successful restoration is considered success because an invalid debug policy
1273 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001274 Ok(false)
1275 } else {
1276 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001277 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001278}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001279
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001280fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001281 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1282 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1283 return Ok(value == 1);
1284 }
1285 }
1286 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1287}
1288
1289fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001290 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1291 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001292
1293 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1294 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1295 ("crashkernel", Box::new(|_| has_crashkernel)),
1296 ("console", Box::new(|_| has_console)),
1297 ];
1298
1299 // parse and filter out unwanted
1300 let mut filtered = Vec::new();
1301 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1302 info!("Invalid bootarg: {e}");
1303 FdtError::BadValue
1304 })? {
1305 match accepted.iter().find(|&t| t.0 == arg.name()) {
1306 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1307 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1308 }
1309 }
1310
1311 // flatten into a new C-string
1312 let mut new_bootargs = Vec::new();
1313 for (i, arg) in filtered.iter().enumerate() {
1314 if i != 0 {
1315 new_bootargs.push(b' '); // separator
1316 }
1317 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1318 }
1319 new_bootargs.push(b'\0');
1320
1321 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1322 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1323}