blob: d847ca2f385c00953a6226b6a3d5a0a5a927b529 [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;
Alice Wang63f4c9e2023-06-12 09:36:43 +000049use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000050use vmbase::memory::SIZE_4KB;
51use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000052use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000053use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054
Alice Wangabc7d632023-06-14 09:10:14 +000055/// An enumeration of errors that can occur during the FDT validation.
56#[derive(Clone, Debug)]
57pub enum FdtValidationError {
58 /// Invalid CPU count.
59 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080060 /// Invalid VCpufreq Range.
61 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000062 /// Forbidden /avf/untrusted property.
63 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000064}
65
66impl fmt::Display for FdtValidationError {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 match self {
69 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000070 Self::InvalidVcpufreq(addr, size) => {
71 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
72 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000073 Self::ForbiddenUntrustedProp(name) => {
74 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
75 }
Alice Wangabc7d632023-06-14 09:10:14 +000076 }
77 }
78}
79
Jiyong Park6a8789a2023-03-21 14:50:59 +090080/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
81/// not an error.
82fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090083 let addr = cstr!("kernel-address");
84 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000085
Jiyong Parkb87f3302023-03-21 10:03:11 +090086 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000087 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
88 let addr = addr as usize;
89 let size = size as usize;
90
91 return Ok(Some(addr..(addr + size)));
92 }
93 }
94
95 Ok(None)
96}
97
Jiyong Park6a8789a2023-03-21 14:50:59 +090098/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
99/// error as there can be initrd-less VM.
100fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +0900101 let start = cstr!("linux,initrd-start");
102 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000103
104 if let Some(chosen) = fdt.chosen()? {
105 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
106 return Ok(Some((start as usize)..(end as usize)));
107 }
108 }
109
110 Ok(None)
111}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000112
Jiyong Park9c63cd12023-03-21 17:53:07 +0900113fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
114 let start = u32::try_from(initrd_range.start).unwrap();
115 let end = u32::try_from(initrd_range.end).unwrap();
116
117 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
118 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
119 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
120 Ok(())
121}
122
Jiyong Parke9d87e82023-03-21 19:28:40 +0900123fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
124 if let Some(chosen) = fdt.chosen()? {
125 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
126 // We need to copy the string to heap because the original fdt will be invalidated
127 // by the templated DT
128 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
129 return Ok(Some(copy));
130 }
131 }
132 Ok(None)
133}
134
135fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
136 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900137 // This function is called before the verification is done. So, we just copy the bootargs to
138 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
139 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900140 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
141}
142
Alice Wang0d527472023-06-13 14:55:38 +0000143/// Reads and validates the memory range in the DT.
144///
145/// Only one memory range is expected with the crosvm setup for now.
146fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
147 let mut memory = fdt.memory().map_err(|e| {
148 error!("Failed to read memory range from DT: {e}");
149 RebootReason::InvalidFdt
150 })?;
151 let range = memory.next().ok_or_else(|| {
152 error!("The /memory node in the DT contains no range.");
153 RebootReason::InvalidFdt
154 })?;
155 if memory.next().is_some() {
156 warn!(
157 "The /memory node in the DT contains more than one memory range, \
158 while only one is expected."
159 );
160 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900161 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000162 if base != MEM_START {
163 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000164 return Err(RebootReason::InvalidFdt);
165 }
166
Jiyong Park6a8789a2023-03-21 14:50:59 +0900167 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000168 if size % GUEST_PAGE_SIZE != 0 {
169 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
170 return Err(RebootReason::InvalidFdt);
171 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000172
Jiyong Park6a8789a2023-03-21 14:50:59 +0900173 if size == 0 {
174 error!("Memory size is 0");
175 return Err(RebootReason::InvalidFdt);
176 }
Alice Wang0d527472023-06-13 14:55:38 +0000177 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000178}
179
Jiyong Park9c63cd12023-03-21 17:53:07 +0900180fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000181 let addr = u64::try_from(MEM_START).unwrap();
182 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900183 fdt.node_mut(cstr!("/memory"))?
184 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000185 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900186}
187
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000188#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800189struct CpuInfo {
190 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800191 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800192}
193
194impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800195 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800196}
197
198fn read_opp_info_from(
199 opp_node: FdtNode,
200) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
201 let mut table = ArrayVec::new();
202 for subnode in opp_node.subnodes()? {
203 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
204 table.push(prop);
205 }
206
207 Ok(table)
208}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900209
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000210#[derive(Debug, Default)]
211struct ClusterTopology {
212 // TODO: Support multi-level clusters & threads.
213 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
214}
215
216impl ClusterTopology {
217 const MAX_CORES_PER_CLUSTER: usize = 6;
218}
219
220#[derive(Debug, Default)]
221struct CpuTopology {
222 // TODO: Support sockets.
223 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
224}
225
226impl CpuTopology {
227 const MAX_CLUSTERS: usize = 3;
228}
229
230fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
231 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
232 return Ok(None);
233 };
234
235 let mut topology = BTreeMap::new();
236 for n in 0..CpuTopology::MAX_CLUSTERS {
237 let name = CString::new(format!("cluster{n}")).unwrap();
238 let Some(cluster) = cpu_map.subnode(&name)? else {
239 break;
240 };
241 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800242 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000243 let Some(core) = cluster.subnode(&name)? else {
244 break;
245 };
246 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
247 let prev = topology.insert(cpu.try_into()?, (n, m));
248 if prev.is_some() {
249 return Err(FdtError::BadValue);
250 }
251 }
252 }
253
254 Ok(Some(topology))
255}
256
257fn read_cpu_info_from(
258 fdt: &Fdt,
259) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000260 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000261
262 let cpu_map = read_cpu_map_from(fdt)?;
263 let mut topology: CpuTopology = Default::default();
264
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000265 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000266 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800267 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800268 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
269 let opptable_info = if let Some(phandle) = opp_phandle {
270 let phandle = phandle.try_into()?;
271 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
272 Some(read_opp_info_from(node)?)
273 } else {
274 None
275 };
David Dai50168a32024-02-14 17:00:48 -0800276 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000277 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000278
279 if let Some(ref cpu_map) = cpu_map {
280 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800281 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000282 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800283 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000284 return Err(FdtError::BadValue);
285 }
David Dai8f476cb2024-02-15 21:57:01 -0800286 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000287 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900288 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000289
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000290 if cpu_nodes.next().is_some() {
291 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
292 }
293
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000294 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900295}
296
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000297fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
298 if cpus.is_empty() {
299 return Err(FdtValidationError::InvalidCpuCount(0));
300 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000301 Ok(())
302}
303
David Dai9bdb10c2024-02-01 22:42:54 -0800304fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000305 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
306 let Some(node) = nodes.next() else {
307 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800308 };
309
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000310 if nodes.next().is_some() {
311 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
312 }
313
314 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
315 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000316 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000317
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000318 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800319}
320
321fn validate_vcpufreq_info(
322 vcpufreq_info: &VcpufreqInfo,
323 cpus: &[CpuInfo],
324) -> Result<(), FdtValidationError> {
325 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000326 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800327
328 let base = vcpufreq_info.addr;
329 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000330 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
331
332 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800333 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000334 }
David Dai9bdb10c2024-02-01 22:42:54 -0800335
336 Ok(())
337}
338
339fn patch_opptable(
340 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800341 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800342) -> libfdt::Result<()> {
343 let oppcompat = cstr!("operating-points-v2");
344 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000345
346 let Some(opptable) = opptable else {
347 return next.nop();
348 };
349
David Dai9bdb10c2024-02-01 22:42:54 -0800350 let mut next_subnode = next.first_subnode()?;
351
352 for entry in opptable {
353 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
354 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
355 next_subnode = subnode.next_subnode()?;
356 }
357
358 while let Some(current) = next_subnode {
359 next_subnode = current.delete_and_next_subnode()?;
360 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000361
David Dai9bdb10c2024-02-01 22:42:54 -0800362 Ok(())
363}
364
365// TODO(ptosi): Rework FdtNodeMut and replace this function.
366fn get_nth_compatible<'a>(
367 fdt: &'a mut Fdt,
368 n: usize,
369 compat: &CStr,
370) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000371 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800372 for _ in 0..n {
373 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
374 }
375 Ok(node)
376}
377
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000378fn patch_cpus(
379 fdt: &mut Fdt,
380 cpus: &[CpuInfo],
381 topology: &Option<CpuTopology>,
382) -> libfdt::Result<()> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000383 const COMPAT: &CStr = cstr!("arm,arm-v8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000384 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800385 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800386 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000387 let phandle = cur.as_node().get_phandle()?.unwrap();
388 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800389 if let Some(cpu_capacity) = cpu.cpu_capacity {
390 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
391 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000392 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900393 }
David Dai9bdb10c2024-02-01 22:42:54 -0800394 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900395 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000396 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900397 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000398
399 if let Some(topology) = topology {
400 for (n, cluster) in topology.clusters.iter().enumerate() {
401 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
402 let cluster_node = fdt.node_mut(&path)?.unwrap();
403 if let Some(cluster) = cluster {
404 let mut iter = cluster_node.first_subnode()?;
405 for core in cluster.cores {
406 let mut core_node = iter.unwrap();
407 iter = if let Some(core_idx) = core {
408 let phandle = *cpu_phandles.get(core_idx).unwrap();
409 let value = u32::from(phandle).to_be_bytes();
410 core_node.setprop_inplace(cstr!("cpu"), &value)?;
411 core_node.next_subnode()?
412 } else {
413 core_node.delete_and_next_subnode()?
414 };
415 }
416 assert!(iter.is_none());
417 } else {
418 cluster_node.nop()?;
419 }
420 }
421 } else {
422 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
423 }
424
Jiyong Park6a8789a2023-03-21 14:50:59 +0900425 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000426}
427
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000428/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
429/// the guest that don't require being validated by pvmfw.
430fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
431 let mut props = BTreeMap::new();
432 if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
433 for property in node.properties()? {
434 let name = property.name()?;
435 let value = property.value()?;
436 props.insert(CString::from(name), value.to_vec());
437 }
438 if node.subnodes()?.next().is_some() {
439 warn!("Discarding unexpected /avf/untrusted subnodes.");
440 }
441 }
442
443 Ok(props)
444}
445
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900446/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900447fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900448 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900449 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900450 for property in avf_node.properties()? {
451 let name = property.name()?;
452 let value = property.value()?;
453 property_map.insert(
454 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
455 value.to_vec(),
456 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900457 }
458 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900459 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900460}
461
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000462fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
463 const FORBIDDEN_PROPS: &[&CStr] =
464 &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
465
466 for name in FORBIDDEN_PROPS {
467 if props.contains_key(*name) {
468 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
469 }
470 }
471
472 Ok(())
473}
474
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900475/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
476/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
477fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900478 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900479 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900480 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900481) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000482 let root_vm_dt = vm_dt.root_mut();
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900483 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900484 // TODO(b/318431677): Validate nodes beyond /avf.
485 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900486 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900487 if let Some(ref_value) = avf_node.getprop(name)? {
488 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900489 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900490 "Property mismatches while applying overlay VM reference DT. \
491 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
492 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900493 );
494 return Err(FdtError::BadValue);
495 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900496 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900497 }
498 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900499 Ok(())
500}
501
Jiyong Park00ceff32023-03-13 05:43:23 +0000502#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000503struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900504 ranges: [PciAddrRange; 2],
505 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
506 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000507}
508
Jiyong Park6a8789a2023-03-21 14:50:59 +0900509impl PciInfo {
510 const IRQ_MASK_CELLS: usize = 4;
511 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100512 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000513}
514
Jiyong Park6a8789a2023-03-21 14:50:59 +0900515type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
516type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
517type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000518
519/// Iterator that takes N cells as a chunk
520struct CellChunkIterator<'a, const N: usize> {
521 cells: CellIterator<'a>,
522}
523
524impl<'a, const N: usize> CellChunkIterator<'a, N> {
525 fn new(cells: CellIterator<'a>) -> Self {
526 Self { cells }
527 }
528}
529
530impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
531 type Item = [u32; N];
532 fn next(&mut self) -> Option<Self::Item> {
533 let mut ret: Self::Item = [0; N];
534 for i in ret.iter_mut() {
535 *i = self.cells.next()?;
536 }
537 Some(ret)
538 }
539}
540
Jiyong Park6a8789a2023-03-21 14:50:59 +0900541/// Read pci host controller ranges, irq maps, and irq map masks from DT
542fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
543 let node =
544 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
545
546 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
547 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
548 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
549
550 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000551 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
552 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
553
554 if chunks.next().is_some() {
555 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
556 return Err(FdtError::NoSpace);
557 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900558
559 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000560 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
561 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
562
563 if chunks.next().is_some() {
564 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
565 return Err(FdtError::NoSpace);
566 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900567
568 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
569}
570
Jiyong Park0ee65392023-03-27 20:52:45 +0900571fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900572 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900573 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900574 }
575 for irq_mask in pci_info.irq_masks.iter() {
576 validate_pci_irq_mask(irq_mask)?;
577 }
578 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
579 validate_pci_irq_map(irq_map, idx)?;
580 }
581 Ok(())
582}
583
Jiyong Park0ee65392023-03-27 20:52:45 +0900584fn validate_pci_addr_range(
585 range: &PciAddrRange,
586 memory_range: &Range<usize>,
587) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900588 let mem_flags = PciMemoryFlags(range.addr.0);
589 let range_type = mem_flags.range_type();
590 let prefetchable = mem_flags.prefetchable();
591 let bus_addr = range.addr.1;
592 let cpu_addr = range.parent_addr;
593 let size = range.size;
594
595 if range_type != PciRangeType::Memory64 {
596 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
597 return Err(RebootReason::InvalidFdt);
598 }
599 if prefetchable {
600 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
601 return Err(RebootReason::InvalidFdt);
602 }
603 // Enforce ID bus-to-cpu mappings, as used by crosvm.
604 if bus_addr != cpu_addr {
605 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
606 return Err(RebootReason::InvalidFdt);
607 }
608
Jiyong Park0ee65392023-03-27 20:52:45 +0900609 let Some(bus_end) = bus_addr.checked_add(size) else {
610 error!("PCI address range size {:#x} overflows", size);
611 return Err(RebootReason::InvalidFdt);
612 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000613 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900614 error!("PCI address end {:#x} is outside of translatable range", bus_end);
615 return Err(RebootReason::InvalidFdt);
616 }
617
618 let memory_start = memory_range.start.try_into().unwrap();
619 let memory_end = memory_range.end.try_into().unwrap();
620
621 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
622 error!(
623 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
624 bus_addr, bus_end, memory_start, memory_end
625 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900626 return Err(RebootReason::InvalidFdt);
627 }
628
629 Ok(())
630}
631
632fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000633 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
634 const IRQ_MASK_ADDR_ME: u32 = 0x0;
635 const IRQ_MASK_ADDR_LO: u32 = 0x0;
636 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900637 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000638 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639 if *irq_mask != EXPECTED {
640 error!("Invalid PCI irq mask {:#?}", irq_mask);
641 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000642 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900643 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000644}
645
Jiyong Park6a8789a2023-03-21 14:50:59 +0900646fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000647 const PCI_DEVICE_IDX: usize = 11;
648 const PCI_IRQ_ADDR_ME: u32 = 0;
649 const PCI_IRQ_ADDR_LO: u32 = 0;
650 const PCI_IRQ_INTC: u32 = 1;
651 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
652 const GIC_SPI: u32 = 0;
653 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
654
Jiyong Park6a8789a2023-03-21 14:50:59 +0900655 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
656 let pci_irq_number = irq_map[3];
657 let _controller_phandle = irq_map[4]; // skipped.
658 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
659 // interrupt-cells is <3> for GIC
660 let gic_peripheral_interrupt_type = irq_map[7];
661 let gic_irq_number = irq_map[8];
662 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000663
Jiyong Park6a8789a2023-03-21 14:50:59 +0900664 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
665 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000666
Jiyong Park6a8789a2023-03-21 14:50:59 +0900667 if pci_addr != expected_pci_addr {
668 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
669 {:#x} {:#x} {:#x}",
670 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
671 return Err(RebootReason::InvalidFdt);
672 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000673
Jiyong Park6a8789a2023-03-21 14:50:59 +0900674 if pci_irq_number != PCI_IRQ_INTC {
675 error!(
676 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
677 pci_irq_number, PCI_IRQ_INTC
678 );
679 return Err(RebootReason::InvalidFdt);
680 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000681
Jiyong Park6a8789a2023-03-21 14:50:59 +0900682 if gic_addr != (0, 0) {
683 error!(
684 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
685 {:#x} {:#x}",
686 gic_addr.0, gic_addr.1, 0, 0
687 );
688 return Err(RebootReason::InvalidFdt);
689 }
690
691 if gic_peripheral_interrupt_type != GIC_SPI {
692 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
693 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
694 return Err(RebootReason::InvalidFdt);
695 }
696
697 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
698 if gic_irq_number != irq_nr {
699 error!(
700 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
701 gic_irq_number, irq_nr
702 );
703 return Err(RebootReason::InvalidFdt);
704 }
705
706 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
707 error!(
708 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
709 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
710 );
711 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000712 }
713 Ok(())
714}
715
Jiyong Park9c63cd12023-03-21 17:53:07 +0900716fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000717 let mut node =
718 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900719
720 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
721 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
722
723 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
724 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
725
726 node.setprop_inplace(
727 cstr!("ranges"),
728 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
729 )
730}
731
Jiyong Park00ceff32023-03-13 05:43:23 +0000732#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900733struct SerialInfo {
734 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000735}
736
737impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900738 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000739}
740
Jiyong Park6a8789a2023-03-21 14:50:59 +0900741fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000742 let mut addrs = ArrayVec::new();
743
744 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
745 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000746 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900747 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000748 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000749 if serial_nodes.next().is_some() {
750 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
751 }
752
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000754}
755
Jiyong Park9c63cd12023-03-21 17:53:07 +0900756/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
757fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
758 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000759 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900760 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000761 let reg =
762 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900763 next = if !serial_info.addrs.contains(&reg.addr) {
764 current.delete_and_next_compatible(name)
765 } else {
766 current.next_compatible(name)
767 }
768 }
769 Ok(())
770}
771
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700772fn validate_swiotlb_info(
773 swiotlb_info: &SwiotlbInfo,
774 memory: &Range<usize>,
775) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900776 let size = swiotlb_info.size;
777 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000778
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700779 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000780 error!("Invalid swiotlb size {:#x}", size);
781 return Err(RebootReason::InvalidFdt);
782 }
783
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000784 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000785 error!("Invalid swiotlb alignment {:#x}", align);
786 return Err(RebootReason::InvalidFdt);
787 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700788
Alice Wang9cfbfd62023-06-14 11:19:03 +0000789 if let Some(addr) = swiotlb_info.addr {
790 if addr.checked_add(size).is_none() {
791 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
792 return Err(RebootReason::InvalidFdt);
793 }
794 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700795 if let Some(range) = swiotlb_info.fixed_range() {
796 if !range.is_within(memory) {
797 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
798 return Err(RebootReason::InvalidFdt);
799 }
800 }
801
Jiyong Park6a8789a2023-03-21 14:50:59 +0900802 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000803}
804
Jiyong Park9c63cd12023-03-21 17:53:07 +0900805fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
806 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000807 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700808
809 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000810 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700811 cstr!("reg"),
812 range.start.try_into().unwrap(),
813 range.len().try_into().unwrap(),
814 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000815 node.nop_property(cstr!("size"))?;
816 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700817 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000818 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700819 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000820 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700821 }
822
Jiyong Park9c63cd12023-03-21 17:53:07 +0900823 Ok(())
824}
825
826fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
827 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
828 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
829 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
830 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
831
832 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000833 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
834 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000835 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900836
837 // range1 is just below range0
838 range1.addr = addr - size;
839 range1.size = Some(size);
840
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000841 let (addr0, size0) = range0.to_cells();
842 let (addr1, size1) = range1.to_cells();
843 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900844
845 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000846 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900847 node.setprop_inplace(cstr!("reg"), flatten(&value))
848}
849
850fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
851 const NUM_INTERRUPTS: usize = 4;
852 const CELLS_PER_INTERRUPT: usize = 3;
853 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
854 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
855 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
856 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
857
858 let num_cpus: u32 = num_cpus.try_into().unwrap();
859 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
860 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
861 *v |= cpu_mask;
862 }
863 for v in value.iter_mut() {
864 *v = v.to_be();
865 }
866
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000867 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900868
869 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000870 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000871 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900872}
873
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000874fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
875 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
876 node
877 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000878 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000879 };
880
881 // The node shouldn't already be present; if it is, return the error.
882 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
883
884 for (name, value) in props {
885 node.setprop(name, value)?;
886 }
887
888 Ok(())
889}
890
Jiyong Park00ceff32023-03-13 05:43:23 +0000891#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800892struct VcpufreqInfo {
893 addr: u64,
894 size: u64,
895}
896
897fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
898 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
899 if let Some(info) = vcpufreq_info {
900 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
901 } else {
902 node.nop()
903 }
904}
905
906#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900907pub struct DeviceTreeInfo {
908 pub kernel_range: Option<Range<usize>>,
909 pub initrd_range: Option<Range<usize>>,
910 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900911 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000912 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000913 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000914 pci_info: PciInfo,
915 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700916 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900917 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000918 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900919 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800920 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000921}
922
923impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000924 const MAX_CPUS: usize = 16;
925
926 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000927 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
928
929 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
930 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000931}
932
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900933pub fn sanitize_device_tree(
934 fdt: &mut [u8],
935 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900936 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900937) -> Result<DeviceTreeInfo, RebootReason> {
938 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
939 error!("Failed to load FDT: {e}");
940 RebootReason::InvalidFdt
941 })?;
942
943 let vm_dtbo = match vm_dtbo {
944 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
945 error!("Failed to load VM DTBO: {e}");
946 RebootReason::InvalidFdt
947 })?),
948 None => None,
949 };
950
951 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900952
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000953 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
954 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
955 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900956 error!("Failed to instantiate FDT from the template DT: {e}");
957 RebootReason::InvalidFdt
958 })?;
959
Jaewan Kim9220e852023-12-01 10:58:40 +0900960 fdt.unpack().map_err(|e| {
961 error!("Failed to unpack DT for patching: {e}");
962 RebootReason::InvalidFdt
963 })?;
964
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900965 if let Some(device_assignment_info) = &info.device_assignment {
966 let vm_dtbo = vm_dtbo.unwrap();
967 device_assignment_info.filter(vm_dtbo).map_err(|e| {
968 error!("Failed to filter VM DTBO: {e}");
969 RebootReason::InvalidFdt
970 })?;
971 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
972 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
973 // it can only be instantiated after validation.
974 unsafe {
975 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
976 error!("Failed to apply filtered VM DTBO: {e}");
977 RebootReason::InvalidFdt
978 })?;
979 }
980 }
981
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900982 if let Some(vm_ref_dt) = vm_ref_dt {
983 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
984 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900985 RebootReason::InvalidFdt
986 })?;
987
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900988 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
989 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900990 RebootReason::InvalidFdt
991 })?;
992 }
993
Jiyong Park9c63cd12023-03-21 17:53:07 +0900994 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900995
Jaewan Kim19b984f2023-12-04 15:16:50 +0900996 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
997
Jaewan Kim9220e852023-12-01 10:58:40 +0900998 fdt.pack().map_err(|e| {
999 error!("Failed to unpack DT after patching: {e}");
1000 RebootReason::InvalidFdt
1001 })?;
1002
Jiyong Park6a8789a2023-03-21 14:50:59 +09001003 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001004}
1005
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001006fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001007 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1008 error!("Failed to read kernel range from DT: {e}");
1009 RebootReason::InvalidFdt
1010 })?;
1011
1012 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1013 error!("Failed to read initrd range from DT: {e}");
1014 RebootReason::InvalidFdt
1015 })?;
1016
Alice Wang0d527472023-06-13 14:55:38 +00001017 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001018
Jiyong Parke9d87e82023-03-21 19:28:40 +09001019 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1020 error!("Failed to read bootargs from DT: {e}");
1021 RebootReason::InvalidFdt
1022 })?;
1023
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001024 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001025 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001026 RebootReason::InvalidFdt
1027 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001028 validate_cpu_info(&cpus).map_err(|e| {
1029 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001030 RebootReason::InvalidFdt
1031 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001032
David Dai9bdb10c2024-02-01 22:42:54 -08001033 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1034 error!("Failed to read vcpufreq info from DT: {e}");
1035 RebootReason::InvalidFdt
1036 })?;
1037 if let Some(ref info) = vcpufreq_info {
1038 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1039 error!("Failed to validate vcpufreq info from DT: {e}");
1040 RebootReason::InvalidFdt
1041 })?;
1042 }
1043
Jiyong Park6a8789a2023-03-21 14:50:59 +09001044 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1045 error!("Failed to read pci info from DT: {e}");
1046 RebootReason::InvalidFdt
1047 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001048 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001049
1050 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1051 error!("Failed to read serial info from DT: {e}");
1052 RebootReason::InvalidFdt
1053 })?;
1054
Alice Wang9cfbfd62023-06-14 11:19:03 +00001055 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001056 error!("Failed to read swiotlb info from DT: {e}");
1057 RebootReason::InvalidFdt
1058 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001059 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001060
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001061 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001062 Some(vm_dtbo) => {
1063 if let Some(hypervisor) = hyp::get_device_assigner() {
1064 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1065 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1066 RebootReason::InvalidFdt
1067 })?
1068 } else {
1069 warn!(
1070 "Device assignment is ignored because device assigning hypervisor is missing"
1071 );
1072 None
1073 }
1074 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001075 None => None,
1076 };
1077
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001078 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1079 error!("Failed to read untrusted properties: {e}");
1080 RebootReason::InvalidFdt
1081 })?;
1082 validate_untrusted_props(&untrusted_props).map_err(|e| {
1083 error!("Failed to validate untrusted properties: {e}");
1084 RebootReason::InvalidFdt
1085 })?;
1086
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001087 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001088 error!("Failed to read names of properties under /avf from DT: {e}");
1089 RebootReason::InvalidFdt
1090 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001091
Jiyong Park00ceff32023-03-13 05:43:23 +00001092 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001093 kernel_range,
1094 initrd_range,
1095 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001096 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001097 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001098 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001099 pci_info,
1100 serial_info,
1101 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001102 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001103 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001104 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001105 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001106 })
1107}
1108
Jiyong Park9c63cd12023-03-21 17:53:07 +09001109fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1110 if let Some(initrd_range) = &info.initrd_range {
1111 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1112 error!("Failed to patch initrd range to DT: {e}");
1113 RebootReason::InvalidFdt
1114 })?;
1115 }
1116 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1117 error!("Failed to patch memory range to DT: {e}");
1118 RebootReason::InvalidFdt
1119 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001120 if let Some(bootargs) = &info.bootargs {
1121 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1122 error!("Failed to patch bootargs to DT: {e}");
1123 RebootReason::InvalidFdt
1124 })?;
1125 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001126 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001127 error!("Failed to patch cpus to DT: {e}");
1128 RebootReason::InvalidFdt
1129 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001130 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1131 error!("Failed to patch vcpufreq info to DT: {e}");
1132 RebootReason::InvalidFdt
1133 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001134 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1135 error!("Failed to patch pci info to DT: {e}");
1136 RebootReason::InvalidFdt
1137 })?;
1138 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1139 error!("Failed to patch serial info to DT: {e}");
1140 RebootReason::InvalidFdt
1141 })?;
1142 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1143 error!("Failed to patch swiotlb info to DT: {e}");
1144 RebootReason::InvalidFdt
1145 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001146 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001147 error!("Failed to patch gic info to DT: {e}");
1148 RebootReason::InvalidFdt
1149 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001150 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001151 error!("Failed to patch timer info to DT: {e}");
1152 RebootReason::InvalidFdt
1153 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001154 if let Some(device_assignment) = &info.device_assignment {
1155 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1156 // then VM DTBO's underlying slice is allocated.
1157 device_assignment.patch(fdt).map_err(|e| {
1158 error!("Failed to patch device assignment info to DT: {e}");
1159 RebootReason::InvalidFdt
1160 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001161 } else {
1162 device_assignment::clean(fdt).map_err(|e| {
1163 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1164 RebootReason::InvalidFdt
1165 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001166 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001167 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1168 error!("Failed to patch untrusted properties: {e}");
1169 RebootReason::InvalidFdt
1170 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001171
Jiyong Park9c63cd12023-03-21 17:53:07 +09001172 Ok(())
1173}
1174
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001175/// Modifies the input DT according to the fields of the configuration.
1176pub fn modify_for_next_stage(
1177 fdt: &mut Fdt,
1178 bcc: &[u8],
1179 new_instance: bool,
1180 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001181 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001182 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001183 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001184) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001185 if let Some(debug_policy) = debug_policy {
1186 let backup = Vec::from(fdt.as_slice());
1187 fdt.unpack()?;
1188 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1189 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1190 info!("Debug policy applied.");
1191 } else {
1192 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1193 fdt.unpack()?;
1194 }
1195 } else {
1196 info!("No debug policy found.");
1197 fdt.unpack()?;
1198 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001199
Jiyong Parke9d87e82023-03-21 19:28:40 +09001200 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001201
Alice Wang56ec45b2023-06-15 08:30:32 +00001202 if let Some(mut chosen) = fdt.chosen_mut()? {
1203 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1204 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001205 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001206 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001207 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001208 if let Some(bootargs) = read_bootargs_from(fdt)? {
1209 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1210 }
1211 }
1212
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001213 fdt.pack()?;
1214
1215 Ok(())
1216}
1217
Jiyong Parke9d87e82023-03-21 19:28:40 +09001218/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1219fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001220 // We reject DTs with missing reserved-memory node as validation should have checked that the
1221 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001222 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001223
Jiyong Parke9d87e82023-03-21 19:28:40 +09001224 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001225
Jiyong Parke9d87e82023-03-21 19:28:40 +09001226 let addr: u64 = addr.try_into().unwrap();
1227 let size: u64 = size.try_into().unwrap();
1228 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001229}
1230
Alice Wang56ec45b2023-06-15 08:30:32 +00001231fn empty_or_delete_prop(
1232 fdt_node: &mut FdtNodeMut,
1233 prop_name: &CStr,
1234 keep_prop: bool,
1235) -> libfdt::Result<()> {
1236 if keep_prop {
1237 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001238 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001239 fdt_node
1240 .delprop(prop_name)
1241 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001242 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001243}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001244
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001245/// Apply the debug policy overlay to the guest DT.
1246///
1247/// 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 +00001248fn apply_debug_policy(
1249 fdt: &mut Fdt,
1250 backup_fdt: &Fdt,
1251 debug_policy: &[u8],
1252) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001253 let mut debug_policy = Vec::from(debug_policy);
1254 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001255 Ok(overlay) => overlay,
1256 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001257 warn!("Corrupted debug policy found: {e}. Not applying.");
1258 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001259 }
1260 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001261
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001262 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001263 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001264 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001265 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001266 // A successful restoration is considered success because an invalid debug policy
1267 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001268 Ok(false)
1269 } else {
1270 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001271 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001272}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001273
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001274fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001275 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1276 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1277 return Ok(value == 1);
1278 }
1279 }
1280 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1281}
1282
1283fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001284 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1285 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001286
1287 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1288 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1289 ("crashkernel", Box::new(|_| has_crashkernel)),
1290 ("console", Box::new(|_| has_console)),
1291 ];
1292
1293 // parse and filter out unwanted
1294 let mut filtered = Vec::new();
1295 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1296 info!("Invalid bootarg: {e}");
1297 FdtError::BadValue
1298 })? {
1299 match accepted.iter().find(|&t| t.0 == arg.name()) {
1300 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1301 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1302 }
1303 }
1304
1305 // flatten into a new C-string
1306 let mut new_bootargs = Vec::new();
1307 for (i, arg) in filtered.iter().enumerate() {
1308 if i != 0 {
1309 new_bootargs.push(b' '); // separator
1310 }
1311 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1312 }
1313 new_bootargs.push(b'\0');
1314
1315 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1316 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1317}