blob: 0381f3e3dd9ceb4809cd7d844946ef1d9693f0d4 [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 libfdt::AddressRange;
34use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000035use libfdt::Fdt;
36use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080037use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000039use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090040use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000041use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090042use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000043use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000044use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000045use tinyvec::ArrayVec;
Pierre-Clément Tosif2c19d42024-10-01 17:42:04 +010046use vmbase::fdt::pci::PciMemoryFlags;
47use vmbase::fdt::pci::PciRangeType;
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;
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
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +000055// SAFETY: The template DT is automatically generated through DTC, which should produce valid DTBs.
56const FDT_TEMPLATE: &Fdt = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
57
Alice Wangabc7d632023-06-14 09:10:14 +000058/// An enumeration of errors that can occur during the FDT validation.
59#[derive(Clone, Debug)]
60pub enum FdtValidationError {
61 /// Invalid CPU count.
62 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080063 /// Invalid VCpufreq Range.
64 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000065 /// Forbidden /avf/untrusted property.
66 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000067}
68
69impl fmt::Display for FdtValidationError {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 match self {
72 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000073 Self::InvalidVcpufreq(addr, size) => {
74 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
75 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000076 Self::ForbiddenUntrustedProp(name) => {
77 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
78 }
Alice Wangabc7d632023-06-14 09:10:14 +000079 }
80 }
81}
82
Jiyong Park6a8789a2023-03-21 14:50:59 +090083/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
84/// not an error.
85fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090086 let addr = cstr!("kernel-address");
87 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000088
Jiyong Parkb87f3302023-03-21 10:03:11 +090089 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000090 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
91 let addr = addr as usize;
92 let size = size as usize;
93
94 return Ok(Some(addr..(addr + size)));
95 }
96 }
97
98 Ok(None)
99}
100
Jiyong Park6a8789a2023-03-21 14:50:59 +0900101/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
102/// error as there can be initrd-less VM.
103fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +0900104 let start = cstr!("linux,initrd-start");
105 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000106
107 if let Some(chosen) = fdt.chosen()? {
108 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
109 return Ok(Some((start as usize)..(end as usize)));
110 }
111 }
112
113 Ok(None)
114}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000115
Jiyong Park9c63cd12023-03-21 17:53:07 +0900116fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
117 let start = u32::try_from(initrd_range.start).unwrap();
118 let end = u32::try_from(initrd_range.end).unwrap();
119
120 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
121 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
122 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
123 Ok(())
124}
125
Jiyong Parke9d87e82023-03-21 19:28:40 +0900126fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
127 if let Some(chosen) = fdt.chosen()? {
128 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
129 // We need to copy the string to heap because the original fdt will be invalidated
130 // by the templated DT
131 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
132 return Ok(Some(copy));
133 }
134 }
135 Ok(None)
136}
137
138fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
139 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900140 // This function is called before the verification is done. So, we just copy the bootargs to
141 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
142 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900143 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
144}
145
Alice Wang0d527472023-06-13 14:55:38 +0000146/// Reads and validates the memory range in the DT.
147///
148/// Only one memory range is expected with the crosvm setup for now.
149fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
150 let mut memory = fdt.memory().map_err(|e| {
151 error!("Failed to read memory range from DT: {e}");
152 RebootReason::InvalidFdt
153 })?;
154 let range = memory.next().ok_or_else(|| {
155 error!("The /memory node in the DT contains no range.");
156 RebootReason::InvalidFdt
157 })?;
158 if memory.next().is_some() {
159 warn!(
160 "The /memory node in the DT contains more than one memory range, \
161 while only one is expected."
162 );
163 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900164 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000165 if base != MEM_START {
166 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000167 return Err(RebootReason::InvalidFdt);
168 }
169
Jiyong Park6a8789a2023-03-21 14:50:59 +0900170 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000171 if size % GUEST_PAGE_SIZE != 0 {
172 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
173 return Err(RebootReason::InvalidFdt);
174 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000175
Jiyong Park6a8789a2023-03-21 14:50:59 +0900176 if size == 0 {
177 error!("Memory size is 0");
178 return Err(RebootReason::InvalidFdt);
179 }
Alice Wang0d527472023-06-13 14:55:38 +0000180 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000181}
182
Jiyong Park9c63cd12023-03-21 17:53:07 +0900183fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000184 let addr = u64::try_from(MEM_START).unwrap();
185 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900186 fdt.node_mut(cstr!("/memory"))?
187 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000188 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900189}
190
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000191#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800192struct CpuInfo {
193 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800194 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800195}
196
197impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800198 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800199}
200
201fn read_opp_info_from(
202 opp_node: FdtNode,
203) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
204 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100205 let mut opp_nodes = opp_node.subnodes()?;
206 for subnode in opp_nodes.by_ref().take(table.capacity()) {
David Dai9bdb10c2024-02-01 22:42:54 -0800207 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
208 table.push(prop);
209 }
210
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100211 if opp_nodes.next().is_some() {
212 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
213 }
214
David Dai9bdb10c2024-02-01 22:42:54 -0800215 Ok(table)
216}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900217
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000218#[derive(Debug, Default)]
219struct ClusterTopology {
220 // TODO: Support multi-level clusters & threads.
221 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
222}
223
224impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700225 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000226}
227
228#[derive(Debug, Default)]
229struct CpuTopology {
230 // TODO: Support sockets.
231 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
232}
233
234impl CpuTopology {
235 const MAX_CLUSTERS: usize = 3;
236}
237
238fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
239 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
240 return Ok(None);
241 };
242
243 let mut topology = BTreeMap::new();
244 for n in 0..CpuTopology::MAX_CLUSTERS {
245 let name = CString::new(format!("cluster{n}")).unwrap();
246 let Some(cluster) = cpu_map.subnode(&name)? else {
247 break;
248 };
249 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800250 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000251 let Some(core) = cluster.subnode(&name)? else {
252 break;
253 };
254 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
255 let prev = topology.insert(cpu.try_into()?, (n, m));
256 if prev.is_some() {
257 return Err(FdtError::BadValue);
258 }
259 }
260 }
261
262 Ok(Some(topology))
263}
264
265fn read_cpu_info_from(
266 fdt: &Fdt,
267) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000268 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000269
270 let cpu_map = read_cpu_map_from(fdt)?;
271 let mut topology: CpuTopology = Default::default();
272
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100273 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,armv8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000274 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800275 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800276 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
277 let opptable_info = if let Some(phandle) = opp_phandle {
278 let phandle = phandle.try_into()?;
279 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
280 Some(read_opp_info_from(node)?)
281 } else {
282 None
283 };
David Dai50168a32024-02-14 17:00:48 -0800284 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000285 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000286
287 if let Some(ref cpu_map) = cpu_map {
288 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800289 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000290 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800291 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000292 return Err(FdtError::BadValue);
293 }
David Dai8f476cb2024-02-15 21:57:01 -0800294 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000295 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900296 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000297
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000298 if cpu_nodes.next().is_some() {
299 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
300 }
301
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000302 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900303}
304
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000305fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
306 if cpus.is_empty() {
307 return Err(FdtValidationError::InvalidCpuCount(0));
308 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000309 Ok(())
310}
311
David Dai9bdb10c2024-02-01 22:42:54 -0800312fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000313 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
314 let Some(node) = nodes.next() else {
315 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800316 };
317
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000318 if nodes.next().is_some() {
319 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
320 }
321
322 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
323 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000324 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000325
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000326 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800327}
328
329fn validate_vcpufreq_info(
330 vcpufreq_info: &VcpufreqInfo,
331 cpus: &[CpuInfo],
332) -> Result<(), FdtValidationError> {
333 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000334 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800335
336 let base = vcpufreq_info.addr;
337 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000338 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
339
340 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800341 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000342 }
David Dai9bdb10c2024-02-01 22:42:54 -0800343
344 Ok(())
345}
346
347fn patch_opptable(
348 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800349 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800350) -> libfdt::Result<()> {
351 let oppcompat = cstr!("operating-points-v2");
352 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000353
354 let Some(opptable) = opptable else {
355 return next.nop();
356 };
357
David Dai9bdb10c2024-02-01 22:42:54 -0800358 let mut next_subnode = next.first_subnode()?;
359
360 for entry in opptable {
361 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
362 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
363 next_subnode = subnode.next_subnode()?;
364 }
365
366 while let Some(current) = next_subnode {
367 next_subnode = current.delete_and_next_subnode()?;
368 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000369
David Dai9bdb10c2024-02-01 22:42:54 -0800370 Ok(())
371}
372
373// TODO(ptosi): Rework FdtNodeMut and replace this function.
374fn get_nth_compatible<'a>(
375 fdt: &'a mut Fdt,
376 n: usize,
377 compat: &CStr,
378) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000379 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800380 for _ in 0..n {
381 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
382 }
383 Ok(node)
384}
385
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000386fn patch_cpus(
387 fdt: &mut Fdt,
388 cpus: &[CpuInfo],
389 topology: &Option<CpuTopology>,
390) -> libfdt::Result<()> {
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100391 const COMPAT: &CStr = cstr!("arm,armv8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000392 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800393 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800394 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000395 let phandle = cur.as_node().get_phandle()?.unwrap();
396 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800397 if let Some(cpu_capacity) = cpu.cpu_capacity {
398 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
399 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000400 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900401 }
David Dai9bdb10c2024-02-01 22:42:54 -0800402 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900403 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000404 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900405 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000406
407 if let Some(topology) = topology {
408 for (n, cluster) in topology.clusters.iter().enumerate() {
409 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
410 let cluster_node = fdt.node_mut(&path)?.unwrap();
411 if let Some(cluster) = cluster {
412 let mut iter = cluster_node.first_subnode()?;
413 for core in cluster.cores {
414 let mut core_node = iter.unwrap();
415 iter = if let Some(core_idx) = core {
416 let phandle = *cpu_phandles.get(core_idx).unwrap();
417 let value = u32::from(phandle).to_be_bytes();
418 core_node.setprop_inplace(cstr!("cpu"), &value)?;
419 core_node.next_subnode()?
420 } else {
421 core_node.delete_and_next_subnode()?
422 };
423 }
424 assert!(iter.is_none());
425 } else {
426 cluster_node.nop()?;
427 }
428 }
429 } else {
430 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
431 }
432
Jiyong Park6a8789a2023-03-21 14:50:59 +0900433 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000434}
435
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000436/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
437/// the guest that don't require being validated by pvmfw.
438fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
439 let mut props = BTreeMap::new();
440 if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
441 for property in node.properties()? {
442 let name = property.name()?;
443 let value = property.value()?;
444 props.insert(CString::from(name), value.to_vec());
445 }
446 if node.subnodes()?.next().is_some() {
447 warn!("Discarding unexpected /avf/untrusted subnodes.");
448 }
449 }
450
451 Ok(props)
452}
453
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900454/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900455fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900456 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900457 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900458 for property in avf_node.properties()? {
459 let name = property.name()?;
460 let value = property.value()?;
461 property_map.insert(
462 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
463 value.to_vec(),
464 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900465 }
466 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900467 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900468}
469
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000470fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
471 const FORBIDDEN_PROPS: &[&CStr] =
472 &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
473
474 for name in FORBIDDEN_PROPS {
475 if props.contains_key(*name) {
476 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
477 }
478 }
479
480 Ok(())
481}
482
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900483/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
484/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
485fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900486 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900487 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900488 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900489) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000490 let root_vm_dt = vm_dt.root_mut();
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900491 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900492 // TODO(b/318431677): Validate nodes beyond /avf.
493 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900494 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900495 if let Some(ref_value) = avf_node.getprop(name)? {
496 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900497 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900498 "Property mismatches while applying overlay VM reference DT. \
499 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
500 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900501 );
502 return Err(FdtError::BadValue);
503 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900504 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900505 }
506 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900507 Ok(())
508}
509
Jiyong Park00ceff32023-03-13 05:43:23 +0000510#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000511struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900512 ranges: [PciAddrRange; 2],
513 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
514 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000515}
516
Jiyong Park6a8789a2023-03-21 14:50:59 +0900517impl PciInfo {
518 const IRQ_MASK_CELLS: usize = 4;
519 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe2d0969c2024-06-06 12:59:12 +0000520 const MAX_IRQS: usize = 16;
Jiyong Park00ceff32023-03-13 05:43:23 +0000521}
522
Jiyong Park6a8789a2023-03-21 14:50:59 +0900523type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
524type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
525type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000526
527/// Iterator that takes N cells as a chunk
528struct CellChunkIterator<'a, const N: usize> {
529 cells: CellIterator<'a>,
530}
531
532impl<'a, const N: usize> CellChunkIterator<'a, N> {
533 fn new(cells: CellIterator<'a>) -> Self {
534 Self { cells }
535 }
536}
537
538impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
539 type Item = [u32; N];
540 fn next(&mut self) -> Option<Self::Item> {
541 let mut ret: Self::Item = [0; N];
542 for i in ret.iter_mut() {
543 *i = self.cells.next()?;
544 }
545 Some(ret)
546 }
547}
548
Jiyong Park6a8789a2023-03-21 14:50:59 +0900549/// Read pci host controller ranges, irq maps, and irq map masks from DT
550fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
551 let node =
552 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
553
554 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
555 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
556 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
557
558 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000559 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
560 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
561
562 if chunks.next().is_some() {
563 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
564 return Err(FdtError::NoSpace);
565 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900566
567 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000568 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
569 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
570
571 if chunks.next().is_some() {
572 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
573 return Err(FdtError::NoSpace);
574 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900575
576 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
577}
578
Jiyong Park0ee65392023-03-27 20:52:45 +0900579fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900580 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900581 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900582 }
583 for irq_mask in pci_info.irq_masks.iter() {
584 validate_pci_irq_mask(irq_mask)?;
585 }
586 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
587 validate_pci_irq_map(irq_map, idx)?;
588 }
589 Ok(())
590}
591
Jiyong Park0ee65392023-03-27 20:52:45 +0900592fn validate_pci_addr_range(
593 range: &PciAddrRange,
594 memory_range: &Range<usize>,
595) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900596 let mem_flags = PciMemoryFlags(range.addr.0);
597 let range_type = mem_flags.range_type();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900598 let bus_addr = range.addr.1;
599 let cpu_addr = range.parent_addr;
600 let size = range.size;
601
602 if range_type != PciRangeType::Memory64 {
603 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
604 return Err(RebootReason::InvalidFdt);
605 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900606 // Enforce ID bus-to-cpu mappings, as used by crosvm.
607 if bus_addr != cpu_addr {
608 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
609 return Err(RebootReason::InvalidFdt);
610 }
611
Jiyong Park0ee65392023-03-27 20:52:45 +0900612 let Some(bus_end) = bus_addr.checked_add(size) else {
613 error!("PCI address range size {:#x} overflows", size);
614 return Err(RebootReason::InvalidFdt);
615 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000616 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900617 error!("PCI address end {:#x} is outside of translatable range", bus_end);
618 return Err(RebootReason::InvalidFdt);
619 }
620
621 let memory_start = memory_range.start.try_into().unwrap();
622 let memory_end = memory_range.end.try_into().unwrap();
623
624 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
625 error!(
626 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
627 bus_addr, bus_end, memory_start, memory_end
628 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900629 return Err(RebootReason::InvalidFdt);
630 }
631
632 Ok(())
633}
634
635fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000636 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
637 const IRQ_MASK_ADDR_ME: u32 = 0x0;
638 const IRQ_MASK_ADDR_LO: u32 = 0x0;
639 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900640 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000641 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900642 if *irq_mask != EXPECTED {
643 error!("Invalid PCI irq mask {:#?}", irq_mask);
644 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000645 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900646 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000647}
648
Jiyong Park6a8789a2023-03-21 14:50:59 +0900649fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000650 const PCI_DEVICE_IDX: usize = 11;
651 const PCI_IRQ_ADDR_ME: u32 = 0;
652 const PCI_IRQ_ADDR_LO: u32 = 0;
653 const PCI_IRQ_INTC: u32 = 1;
654 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
655 const GIC_SPI: u32 = 0;
656 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
657
Jiyong Park6a8789a2023-03-21 14:50:59 +0900658 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
659 let pci_irq_number = irq_map[3];
660 let _controller_phandle = irq_map[4]; // skipped.
661 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
662 // interrupt-cells is <3> for GIC
663 let gic_peripheral_interrupt_type = irq_map[7];
664 let gic_irq_number = irq_map[8];
665 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000666
Jiyong Park6a8789a2023-03-21 14:50:59 +0900667 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
668 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000669
Jiyong Park6a8789a2023-03-21 14:50:59 +0900670 if pci_addr != expected_pci_addr {
671 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
672 {:#x} {:#x} {:#x}",
673 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
674 return Err(RebootReason::InvalidFdt);
675 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000676
Jiyong Park6a8789a2023-03-21 14:50:59 +0900677 if pci_irq_number != PCI_IRQ_INTC {
678 error!(
679 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
680 pci_irq_number, PCI_IRQ_INTC
681 );
682 return Err(RebootReason::InvalidFdt);
683 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000684
Jiyong Park6a8789a2023-03-21 14:50:59 +0900685 if gic_addr != (0, 0) {
686 error!(
687 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
688 {:#x} {:#x}",
689 gic_addr.0, gic_addr.1, 0, 0
690 );
691 return Err(RebootReason::InvalidFdt);
692 }
693
694 if gic_peripheral_interrupt_type != GIC_SPI {
695 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
696 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
697 return Err(RebootReason::InvalidFdt);
698 }
699
700 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
701 if gic_irq_number != irq_nr {
702 error!(
703 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
704 gic_irq_number, irq_nr
705 );
706 return Err(RebootReason::InvalidFdt);
707 }
708
709 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
710 error!(
711 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
712 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
713 );
714 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000715 }
716 Ok(())
717}
718
Jiyong Park9c63cd12023-03-21 17:53:07 +0900719fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000720 let mut node =
721 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900722
723 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
724 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
725
726 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
727 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
728
729 node.setprop_inplace(
730 cstr!("ranges"),
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000731 [pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()].as_flattened(),
Jiyong Park9c63cd12023-03-21 17:53:07 +0900732 )
733}
734
Jiyong Park00ceff32023-03-13 05:43:23 +0000735#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900736struct SerialInfo {
737 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000738}
739
740impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900741 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000742}
743
Jiyong Park6a8789a2023-03-21 14:50:59 +0900744fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000745 let mut addrs = ArrayVec::new();
746
747 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
748 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000749 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900750 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000751 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000752 if serial_nodes.next().is_some() {
753 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
754 }
755
Jiyong Park6a8789a2023-03-21 14:50:59 +0900756 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000757}
758
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000759#[derive(Default, Debug, PartialEq)]
760struct WdtInfo {
761 addr: u64,
762 size: u64,
763 irq: [u32; WdtInfo::IRQ_CELLS],
764}
765
766impl WdtInfo {
767 const IRQ_CELLS: usize = 3;
768 const IRQ_NR: u32 = 0xf;
769 const ADDR: u64 = 0x3000;
770 const SIZE: u64 = 0x1000;
771 const GIC_PPI: u32 = 1;
772 const IRQ_TYPE_EDGE_RISING: u32 = 1;
773 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100774 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000775 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
776
777 const fn get_expected(num_cpus: usize) -> Self {
778 Self {
779 addr: Self::ADDR,
780 size: Self::SIZE,
781 irq: [
782 Self::GIC_PPI,
783 Self::IRQ_NR,
784 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
785 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
786 | Self::IRQ_TYPE_EDGE_RISING,
787 ],
788 }
789 }
790}
791
792fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
793 let mut node_iter = fdt.compatible_nodes(cstr!("qemu,vcpu-stall-detector"))?;
794 let node = node_iter.next().ok_or(FdtError::NotFound)?;
795 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
796
797 let reg = ranges.next().ok_or(FdtError::NotFound)?;
798 let size = reg.size.ok_or(FdtError::NotFound)?;
799 if ranges.next().is_some() {
800 warn!("Discarding extra vmwdt <reg> entries.");
801 }
802
803 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
804 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
805 let irq = chunks.next().ok_or(FdtError::NotFound)?;
806
807 if chunks.next().is_some() {
808 warn!("Discarding extra vmwdt <interrupts> entries.");
809 }
810
811 Ok(WdtInfo { addr: reg.addr, size, irq })
812}
813
814fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
815 if *wdt != WdtInfo::get_expected(num_cpus) {
816 error!("Invalid watchdog timer: {wdt:?}");
817 return Err(RebootReason::InvalidFdt);
818 }
819
820 Ok(())
821}
822
823fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
824 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
825 for v in interrupts.iter_mut() {
826 *v = v.to_be();
827 }
828
829 let mut node = fdt
830 .root_mut()
831 .next_compatible(cstr!("qemu,vcpu-stall-detector"))?
832 .ok_or(libfdt::FdtError::NotFound)?;
833 node.setprop_inplace(cstr!("interrupts"), interrupts.as_bytes())?;
834 Ok(())
835}
836
Jiyong Park9c63cd12023-03-21 17:53:07 +0900837/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
838fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
839 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000840 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900841 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000842 let reg =
843 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900844 next = if !serial_info.addrs.contains(&reg.addr) {
845 current.delete_and_next_compatible(name)
846 } else {
847 current.next_compatible(name)
848 }
849 }
850 Ok(())
851}
852
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700853fn validate_swiotlb_info(
854 swiotlb_info: &SwiotlbInfo,
855 memory: &Range<usize>,
856) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900857 let size = swiotlb_info.size;
858 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000859
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700860 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000861 error!("Invalid swiotlb size {:#x}", size);
862 return Err(RebootReason::InvalidFdt);
863 }
864
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000865 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000866 error!("Invalid swiotlb alignment {:#x}", align);
867 return Err(RebootReason::InvalidFdt);
868 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700869
Alice Wang9cfbfd62023-06-14 11:19:03 +0000870 if let Some(addr) = swiotlb_info.addr {
871 if addr.checked_add(size).is_none() {
872 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
873 return Err(RebootReason::InvalidFdt);
874 }
875 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700876 if let Some(range) = swiotlb_info.fixed_range() {
877 if !range.is_within(memory) {
878 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
879 return Err(RebootReason::InvalidFdt);
880 }
881 }
882
Jiyong Park6a8789a2023-03-21 14:50:59 +0900883 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000884}
885
Jiyong Park9c63cd12023-03-21 17:53:07 +0900886fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
887 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000888 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700889
890 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000891 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700892 cstr!("reg"),
893 range.start.try_into().unwrap(),
894 range.len().try_into().unwrap(),
895 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000896 node.nop_property(cstr!("size"))?;
897 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700898 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000899 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700900 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000901 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700902 }
903
Jiyong Park9c63cd12023-03-21 17:53:07 +0900904 Ok(())
905}
906
907fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
908 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
909 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
910 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
911 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
912
913 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000914 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
915 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000916 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900917
918 // range1 is just below range0
919 range1.addr = addr - size;
920 range1.size = Some(size);
921
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000922 let (addr0, size0) = range0.to_cells();
923 let (addr1, size1) = range1.to_cells();
924 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900925
926 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000927 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +0000928 node.setprop_inplace(cstr!("reg"), value.as_flattened())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900929}
930
931fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
932 const NUM_INTERRUPTS: usize = 4;
933 const CELLS_PER_INTERRUPT: usize = 3;
934 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
935 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
936 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
937 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
938
939 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100940 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900941 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000942
Jiyong Park9c63cd12023-03-21 17:53:07 +0900943 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
944 *v |= cpu_mask;
945 }
946 for v in value.iter_mut() {
947 *v = v.to_be();
948 }
949
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000950 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900951
952 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000953 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000954 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900955}
956
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000957fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
958 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
959 node
960 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000961 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000962 };
963
964 // The node shouldn't already be present; if it is, return the error.
965 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
966
967 for (name, value) in props {
968 node.setprop(name, value)?;
969 }
970
971 Ok(())
972}
973
Jiyong Park00ceff32023-03-13 05:43:23 +0000974#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800975struct VcpufreqInfo {
976 addr: u64,
977 size: u64,
978}
979
980fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
981 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
982 if let Some(info) = vcpufreq_info {
983 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
984 } else {
985 node.nop()
986 }
987}
988
989#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900990pub struct DeviceTreeInfo {
991 pub kernel_range: Option<Range<usize>>,
992 pub initrd_range: Option<Range<usize>>,
993 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900994 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000995 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000996 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000997 pci_info: PciInfo,
998 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700999 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001000 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001001 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001002 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001003 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001004}
1005
1006impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001007 const MAX_CPUS: usize = 16;
1008
1009 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001010 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1011
1012 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1013 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001014}
1015
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001016pub fn sanitize_device_tree(
1017 fdt: &mut [u8],
1018 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001019 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001020) -> Result<DeviceTreeInfo, RebootReason> {
1021 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
1022 error!("Failed to load FDT: {e}");
1023 RebootReason::InvalidFdt
1024 })?;
1025
1026 let vm_dtbo = match vm_dtbo {
1027 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1028 error!("Failed to load VM DTBO: {e}");
1029 RebootReason::InvalidFdt
1030 })?),
1031 None => None,
1032 };
1033
1034 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +09001035
Pierre-Clément Tosi84ba1a82024-10-30 11:27:32 +00001036 fdt.clone_from(FDT_TEMPLATE).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001037 error!("Failed to instantiate FDT from the template DT: {e}");
1038 RebootReason::InvalidFdt
1039 })?;
1040
Jaewan Kim9220e852023-12-01 10:58:40 +09001041 fdt.unpack().map_err(|e| {
1042 error!("Failed to unpack DT for patching: {e}");
1043 RebootReason::InvalidFdt
1044 })?;
1045
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001046 if let Some(device_assignment_info) = &info.device_assignment {
1047 let vm_dtbo = vm_dtbo.unwrap();
1048 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1049 error!("Failed to filter VM DTBO: {e}");
1050 RebootReason::InvalidFdt
1051 })?;
1052 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1053 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1054 // it can only be instantiated after validation.
1055 unsafe {
1056 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1057 error!("Failed to apply filtered VM DTBO: {e}");
1058 RebootReason::InvalidFdt
1059 })?;
1060 }
1061 }
1062
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001063 if let Some(vm_ref_dt) = vm_ref_dt {
1064 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1065 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001066 RebootReason::InvalidFdt
1067 })?;
1068
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001069 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1070 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001071 RebootReason::InvalidFdt
1072 })?;
1073 }
1074
Jiyong Park9c63cd12023-03-21 17:53:07 +09001075 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001076
Jaewan Kim19b984f2023-12-04 15:16:50 +09001077 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1078
Jaewan Kim9220e852023-12-01 10:58:40 +09001079 fdt.pack().map_err(|e| {
1080 error!("Failed to unpack DT after patching: {e}");
1081 RebootReason::InvalidFdt
1082 })?;
1083
Jiyong Park6a8789a2023-03-21 14:50:59 +09001084 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001085}
1086
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001087fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001088 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1089 error!("Failed to read kernel range from DT: {e}");
1090 RebootReason::InvalidFdt
1091 })?;
1092
1093 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1094 error!("Failed to read initrd range from DT: {e}");
1095 RebootReason::InvalidFdt
1096 })?;
1097
Alice Wang0d527472023-06-13 14:55:38 +00001098 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001099
Jiyong Parke9d87e82023-03-21 19:28:40 +09001100 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1101 error!("Failed to read bootargs from DT: {e}");
1102 RebootReason::InvalidFdt
1103 })?;
1104
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001105 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001106 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001107 RebootReason::InvalidFdt
1108 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001109 validate_cpu_info(&cpus).map_err(|e| {
1110 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001111 RebootReason::InvalidFdt
1112 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001113
David Dai9bdb10c2024-02-01 22:42:54 -08001114 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1115 error!("Failed to read vcpufreq info from DT: {e}");
1116 RebootReason::InvalidFdt
1117 })?;
1118 if let Some(ref info) = vcpufreq_info {
1119 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1120 error!("Failed to validate vcpufreq info from DT: {e}");
1121 RebootReason::InvalidFdt
1122 })?;
1123 }
1124
Jiyong Park6a8789a2023-03-21 14:50:59 +09001125 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1126 error!("Failed to read pci info from DT: {e}");
1127 RebootReason::InvalidFdt
1128 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001129 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001130
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001131 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1132 error!("Failed to read vCPU stall detector info from DT: {e}");
1133 RebootReason::InvalidFdt
1134 })?;
1135 validate_wdt_info(&wdt_info, cpus.len())?;
1136
Jiyong Park6a8789a2023-03-21 14:50:59 +09001137 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1138 error!("Failed to read serial info from DT: {e}");
1139 RebootReason::InvalidFdt
1140 })?;
1141
Alice Wang9cfbfd62023-06-14 11:19:03 +00001142 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001143 error!("Failed to read swiotlb info from DT: {e}");
1144 RebootReason::InvalidFdt
1145 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001146 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001147
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001148 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001149 Some(vm_dtbo) => {
1150 if let Some(hypervisor) = hyp::get_device_assigner() {
Pierre-Clément Tosieacdd0f2024-10-22 16:31:01 +01001151 // TODO(ptosi): Cache the (single?) granule once, in vmbase.
1152 let granule = hyp::get_mem_sharer()
1153 .ok_or_else(|| {
1154 error!("No MEM_SHARE found during device assignment validation");
1155 RebootReason::InternalError
1156 })?
1157 .granule()
1158 .map_err(|e| {
1159 error!("Failed to get granule for device assignment validation: {e}");
1160 RebootReason::InternalError
1161 })?;
1162 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor, granule).map_err(|e| {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001163 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1164 RebootReason::InvalidFdt
1165 })?
1166 } else {
1167 warn!(
1168 "Device assignment is ignored because device assigning hypervisor is missing"
1169 );
1170 None
1171 }
1172 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001173 None => None,
1174 };
1175
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001176 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1177 error!("Failed to read untrusted properties: {e}");
1178 RebootReason::InvalidFdt
1179 })?;
1180 validate_untrusted_props(&untrusted_props).map_err(|e| {
1181 error!("Failed to validate untrusted properties: {e}");
1182 RebootReason::InvalidFdt
1183 })?;
1184
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001185 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001186 error!("Failed to read names of properties under /avf from DT: {e}");
1187 RebootReason::InvalidFdt
1188 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001189
Jiyong Park00ceff32023-03-13 05:43:23 +00001190 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001191 kernel_range,
1192 initrd_range,
1193 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001194 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001195 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001196 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001197 pci_info,
1198 serial_info,
1199 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001200 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001201 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001202 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001203 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001204 })
1205}
1206
Jiyong Park9c63cd12023-03-21 17:53:07 +09001207fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1208 if let Some(initrd_range) = &info.initrd_range {
1209 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1210 error!("Failed to patch initrd range to DT: {e}");
1211 RebootReason::InvalidFdt
1212 })?;
1213 }
1214 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1215 error!("Failed to patch memory range to DT: {e}");
1216 RebootReason::InvalidFdt
1217 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001218 if let Some(bootargs) = &info.bootargs {
1219 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1220 error!("Failed to patch bootargs to DT: {e}");
1221 RebootReason::InvalidFdt
1222 })?;
1223 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001224 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001225 error!("Failed to patch cpus to DT: {e}");
1226 RebootReason::InvalidFdt
1227 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001228 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1229 error!("Failed to patch vcpufreq info to DT: {e}");
1230 RebootReason::InvalidFdt
1231 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001232 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1233 error!("Failed to patch pci info to DT: {e}");
1234 RebootReason::InvalidFdt
1235 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001236 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1237 error!("Failed to patch wdt info to DT: {e}");
1238 RebootReason::InvalidFdt
1239 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001240 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1241 error!("Failed to patch serial info to DT: {e}");
1242 RebootReason::InvalidFdt
1243 })?;
1244 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1245 error!("Failed to patch swiotlb info to DT: {e}");
1246 RebootReason::InvalidFdt
1247 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001248 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001249 error!("Failed to patch gic info to DT: {e}");
1250 RebootReason::InvalidFdt
1251 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001252 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001253 error!("Failed to patch timer info to DT: {e}");
1254 RebootReason::InvalidFdt
1255 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001256 if let Some(device_assignment) = &info.device_assignment {
1257 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1258 // then VM DTBO's underlying slice is allocated.
1259 device_assignment.patch(fdt).map_err(|e| {
1260 error!("Failed to patch device assignment info to DT: {e}");
1261 RebootReason::InvalidFdt
1262 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001263 } else {
1264 device_assignment::clean(fdt).map_err(|e| {
1265 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1266 RebootReason::InvalidFdt
1267 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001268 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001269 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1270 error!("Failed to patch untrusted properties: {e}");
1271 RebootReason::InvalidFdt
1272 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001273
Jiyong Park9c63cd12023-03-21 17:53:07 +09001274 Ok(())
1275}
1276
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001277/// Modifies the input DT according to the fields of the configuration.
1278pub fn modify_for_next_stage(
1279 fdt: &mut Fdt,
1280 bcc: &[u8],
1281 new_instance: bool,
1282 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001283 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001284 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001285 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001286) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001287 if let Some(debug_policy) = debug_policy {
1288 let backup = Vec::from(fdt.as_slice());
1289 fdt.unpack()?;
1290 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1291 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1292 info!("Debug policy applied.");
1293 } else {
1294 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1295 fdt.unpack()?;
1296 }
1297 } else {
1298 info!("No debug policy found.");
1299 fdt.unpack()?;
1300 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001301
Jiyong Parke9d87e82023-03-21 19:28:40 +09001302 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001303
Alice Wang56ec45b2023-06-15 08:30:32 +00001304 if let Some(mut chosen) = fdt.chosen_mut()? {
1305 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1306 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001307 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001308 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001309 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001310 if let Some(bootargs) = read_bootargs_from(fdt)? {
1311 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1312 }
1313 }
1314
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001315 fdt.pack()?;
1316
1317 Ok(())
1318}
1319
Jiyong Parke9d87e82023-03-21 19:28:40 +09001320/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1321fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001322 // We reject DTs with missing reserved-memory node as validation should have checked that the
1323 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001324 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001325
Jiyong Parke9d87e82023-03-21 19:28:40 +09001326 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001327
Jiyong Parke9d87e82023-03-21 19:28:40 +09001328 let addr: u64 = addr.try_into().unwrap();
1329 let size: u64 = size.try_into().unwrap();
Pierre-Clément Tosid0818b22024-10-30 20:09:31 +00001330 node.setprop_inplace(cstr!("reg"), [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001331}
1332
Alice Wang56ec45b2023-06-15 08:30:32 +00001333fn empty_or_delete_prop(
1334 fdt_node: &mut FdtNodeMut,
1335 prop_name: &CStr,
1336 keep_prop: bool,
1337) -> libfdt::Result<()> {
1338 if keep_prop {
1339 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001340 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001341 fdt_node
1342 .delprop(prop_name)
1343 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001344 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001345}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001346
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001347/// Apply the debug policy overlay to the guest DT.
1348///
1349/// 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 +00001350fn apply_debug_policy(
1351 fdt: &mut Fdt,
1352 backup_fdt: &Fdt,
1353 debug_policy: &[u8],
1354) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001355 let mut debug_policy = Vec::from(debug_policy);
1356 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001357 Ok(overlay) => overlay,
1358 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001359 warn!("Corrupted debug policy found: {e}. Not applying.");
1360 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001361 }
1362 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001363
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001364 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001365 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001366 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001367 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001368 // A successful restoration is considered success because an invalid debug policy
1369 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001370 Ok(false)
1371 } else {
1372 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001373 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001374}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001375
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001376fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001377 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1378 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1379 return Ok(value == 1);
1380 }
1381 }
1382 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1383}
1384
1385fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001386 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1387 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001388
1389 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1390 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1391 ("crashkernel", Box::new(|_| has_crashkernel)),
1392 ("console", Box::new(|_| has_console)),
1393 ];
1394
1395 // parse and filter out unwanted
1396 let mut filtered = Vec::new();
1397 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1398 info!("Invalid bootarg: {e}");
1399 FdtError::BadValue
1400 })? {
1401 match accepted.iter().find(|&t| t.0 == arg.name()) {
1402 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1403 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1404 }
1405 }
1406
1407 // flatten into a new C-string
1408 let mut new_bootargs = Vec::new();
1409 for (i, arg) in filtered.iter().enumerate() {
1410 if i != 0 {
1411 new_bootargs.push(b' '); // separator
1412 }
1413 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1414 }
1415 new_bootargs.push(b'\0');
1416
1417 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1418 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1419}