blob: 146d012e2eb7b64ff9c082d144e63ab6f2d08292 [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! High-level FDT functions.
16
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090017use crate::bootargs::BootArgsIterator;
Jaewan Kim52477ae2023-11-21 21:20:52 +090018use crate::device_assignment::{DeviceAssignmentInfo, VmDtbo};
Jiyong Park00ceff32023-03-13 05:43:23 +000019use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090020use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000024use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090025use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090026use core::cmp::max;
27use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000029use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090030use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use fdtpci::PciMemoryFlags;
34use fdtpci::PciRangeType;
35use libfdt::AddressRange;
36use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000037use libfdt::Fdt;
38use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080039use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000040use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000041use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090042use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090044use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000045use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000046use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000047use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000048use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000049use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000050use vmbase::memory::SIZE_4KB;
51use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000052use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000053use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054
Alice Wangabc7d632023-06-14 09:10:14 +000055/// An enumeration of errors that can occur during the FDT validation.
56#[derive(Clone, Debug)]
57pub enum FdtValidationError {
58 /// Invalid CPU count.
59 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080060 /// Invalid VCpufreq Range.
61 InvalidVcpufreq(u64, u64),
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>>> {
371 let mut node = fdt.root_mut()?.next_compatible(compat)?;
372 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 Tosia3c4ec32024-02-15 20:05:15 +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<()> {
717 let mut node = fdt
718 .root_mut()?
719 .next_compatible(cstr!("pci-host-cam-generic"))?
720 .ok_or(FdtError::NotFound)?;
721
722 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
723 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
724
725 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
726 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
727
728 node.setprop_inplace(
729 cstr!("ranges"),
730 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
731 )
732}
733
Jiyong Park00ceff32023-03-13 05:43:23 +0000734#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900735struct SerialInfo {
736 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000737}
738
739impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900740 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000741}
742
Jiyong Park6a8789a2023-03-21 14:50:59 +0900743fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000744 let mut addrs = ArrayVec::new();
745
746 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
747 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000748 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900749 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000750 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000751 if serial_nodes.next().is_some() {
752 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
753 }
754
Jiyong Park6a8789a2023-03-21 14:50:59 +0900755 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000756}
757
Jiyong Park9c63cd12023-03-21 17:53:07 +0900758/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
759fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
760 let name = cstr!("ns16550a");
761 let mut next = fdt.root_mut()?.next_compatible(name);
762 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000763 let reg =
764 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900765 next = if !serial_info.addrs.contains(&reg.addr) {
766 current.delete_and_next_compatible(name)
767 } else {
768 current.next_compatible(name)
769 }
770 }
771 Ok(())
772}
773
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700774fn validate_swiotlb_info(
775 swiotlb_info: &SwiotlbInfo,
776 memory: &Range<usize>,
777) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900778 let size = swiotlb_info.size;
779 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000780
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700781 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000782 error!("Invalid swiotlb size {:#x}", size);
783 return Err(RebootReason::InvalidFdt);
784 }
785
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000786 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000787 error!("Invalid swiotlb alignment {:#x}", align);
788 return Err(RebootReason::InvalidFdt);
789 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700790
Alice Wang9cfbfd62023-06-14 11:19:03 +0000791 if let Some(addr) = swiotlb_info.addr {
792 if addr.checked_add(size).is_none() {
793 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
794 return Err(RebootReason::InvalidFdt);
795 }
796 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700797 if let Some(range) = swiotlb_info.fixed_range() {
798 if !range.is_within(memory) {
799 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
800 return Err(RebootReason::InvalidFdt);
801 }
802 }
803
Jiyong Park6a8789a2023-03-21 14:50:59 +0900804 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000805}
806
Jiyong Park9c63cd12023-03-21 17:53:07 +0900807fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
808 let mut node =
809 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700810
811 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000812 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700813 cstr!("reg"),
814 range.start.try_into().unwrap(),
815 range.len().try_into().unwrap(),
816 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000817 node.nop_property(cstr!("size"))?;
818 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700819 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000820 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700821 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000822 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700823 }
824
Jiyong Park9c63cd12023-03-21 17:53:07 +0900825 Ok(())
826}
827
828fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
829 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
830 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
831 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
832 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
833
834 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000835 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
836 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000837 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900838
839 // range1 is just below range0
840 range1.addr = addr - size;
841 range1.size = Some(size);
842
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000843 let (addr0, size0) = range0.to_cells();
844 let (addr1, size1) = range1.to_cells();
845 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900846
847 let mut node =
848 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
849 node.setprop_inplace(cstr!("reg"), flatten(&value))
850}
851
852fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
853 const NUM_INTERRUPTS: usize = 4;
854 const CELLS_PER_INTERRUPT: usize = 3;
855 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
856 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
857 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
858 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
859
860 let num_cpus: u32 = num_cpus.try_into().unwrap();
861 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
862 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
863 *v |= cpu_mask;
864 }
865 for v in value.iter_mut() {
866 *v = v.to_be();
867 }
868
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000869 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900870
871 let mut node =
872 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000873 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900874}
875
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000876fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
877 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
878 node
879 } else {
880 fdt.root_mut()?.add_subnode(cstr!("avf"))?
881 };
882
883 // The node shouldn't already be present; if it is, return the error.
884 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
885
886 for (name, value) in props {
887 node.setprop(name, value)?;
888 }
889
890 Ok(())
891}
892
Jiyong Park00ceff32023-03-13 05:43:23 +0000893#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800894struct VcpufreqInfo {
895 addr: u64,
896 size: u64,
897}
898
899fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
900 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
901 if let Some(info) = vcpufreq_info {
902 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
903 } else {
904 node.nop()
905 }
906}
907
908#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900909pub struct DeviceTreeInfo {
910 pub kernel_range: Option<Range<usize>>,
911 pub initrd_range: Option<Range<usize>>,
912 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900913 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000914 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000915 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000916 pci_info: PciInfo,
917 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700918 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900919 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000920 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900921 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800922 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000923}
924
925impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000926 const MAX_CPUS: usize = 16;
927
928 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000929 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
930
931 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
932 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000933}
934
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900935pub fn sanitize_device_tree(
936 fdt: &mut [u8],
937 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900938 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900939) -> Result<DeviceTreeInfo, RebootReason> {
940 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
941 error!("Failed to load FDT: {e}");
942 RebootReason::InvalidFdt
943 })?;
944
945 let vm_dtbo = match vm_dtbo {
946 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
947 error!("Failed to load VM DTBO: {e}");
948 RebootReason::InvalidFdt
949 })?),
950 None => None,
951 };
952
953 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900954
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000955 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
956 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
957 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900958 error!("Failed to instantiate FDT from the template DT: {e}");
959 RebootReason::InvalidFdt
960 })?;
961
Jaewan Kim9220e852023-12-01 10:58:40 +0900962 fdt.unpack().map_err(|e| {
963 error!("Failed to unpack DT for patching: {e}");
964 RebootReason::InvalidFdt
965 })?;
966
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900967 if let Some(device_assignment_info) = &info.device_assignment {
968 let vm_dtbo = vm_dtbo.unwrap();
969 device_assignment_info.filter(vm_dtbo).map_err(|e| {
970 error!("Failed to filter VM DTBO: {e}");
971 RebootReason::InvalidFdt
972 })?;
973 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
974 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
975 // it can only be instantiated after validation.
976 unsafe {
977 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
978 error!("Failed to apply filtered VM DTBO: {e}");
979 RebootReason::InvalidFdt
980 })?;
981 }
982 }
983
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900984 if let Some(vm_ref_dt) = vm_ref_dt {
985 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
986 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900987 RebootReason::InvalidFdt
988 })?;
989
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900990 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
991 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900992 RebootReason::InvalidFdt
993 })?;
994 }
995
Jiyong Park9c63cd12023-03-21 17:53:07 +0900996 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900997
Jaewan Kim19b984f2023-12-04 15:16:50 +0900998 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
999
Jaewan Kim9220e852023-12-01 10:58:40 +09001000 fdt.pack().map_err(|e| {
1001 error!("Failed to unpack DT after patching: {e}");
1002 RebootReason::InvalidFdt
1003 })?;
1004
Jiyong Park6a8789a2023-03-21 14:50:59 +09001005 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001006}
1007
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001008fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001009 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1010 error!("Failed to read kernel range from DT: {e}");
1011 RebootReason::InvalidFdt
1012 })?;
1013
1014 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1015 error!("Failed to read initrd range from DT: {e}");
1016 RebootReason::InvalidFdt
1017 })?;
1018
Alice Wang0d527472023-06-13 14:55:38 +00001019 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001020
Jiyong Parke9d87e82023-03-21 19:28:40 +09001021 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1022 error!("Failed to read bootargs from DT: {e}");
1023 RebootReason::InvalidFdt
1024 })?;
1025
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001026 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001027 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001028 RebootReason::InvalidFdt
1029 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001030 validate_cpu_info(&cpus).map_err(|e| {
1031 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001032 RebootReason::InvalidFdt
1033 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001034
David Dai9bdb10c2024-02-01 22:42:54 -08001035 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1036 error!("Failed to read vcpufreq info from DT: {e}");
1037 RebootReason::InvalidFdt
1038 })?;
1039 if let Some(ref info) = vcpufreq_info {
1040 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1041 error!("Failed to validate vcpufreq info from DT: {e}");
1042 RebootReason::InvalidFdt
1043 })?;
1044 }
1045
Jiyong Park6a8789a2023-03-21 14:50:59 +09001046 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1047 error!("Failed to read pci info from DT: {e}");
1048 RebootReason::InvalidFdt
1049 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001050 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001051
1052 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1053 error!("Failed to read serial info from DT: {e}");
1054 RebootReason::InvalidFdt
1055 })?;
1056
Alice Wang9cfbfd62023-06-14 11:19:03 +00001057 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001058 error!("Failed to read swiotlb info from DT: {e}");
1059 RebootReason::InvalidFdt
1060 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001061 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001062
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001063 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001064 Some(vm_dtbo) => {
1065 if let Some(hypervisor) = hyp::get_device_assigner() {
1066 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
1067 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1068 RebootReason::InvalidFdt
1069 })?
1070 } else {
1071 warn!(
1072 "Device assignment is ignored because device assigning hypervisor is missing"
1073 );
1074 None
1075 }
1076 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001077 None => None,
1078 };
1079
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001080 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1081 error!("Failed to read untrusted properties: {e}");
1082 RebootReason::InvalidFdt
1083 })?;
1084 validate_untrusted_props(&untrusted_props).map_err(|e| {
1085 error!("Failed to validate untrusted properties: {e}");
1086 RebootReason::InvalidFdt
1087 })?;
1088
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001089 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001090 error!("Failed to read names of properties under /avf from DT: {e}");
1091 RebootReason::InvalidFdt
1092 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001093
Jiyong Park00ceff32023-03-13 05:43:23 +00001094 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001095 kernel_range,
1096 initrd_range,
1097 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001098 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001099 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001100 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001101 pci_info,
1102 serial_info,
1103 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001104 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001105 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001106 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001107 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001108 })
1109}
1110
Jiyong Park9c63cd12023-03-21 17:53:07 +09001111fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1112 if let Some(initrd_range) = &info.initrd_range {
1113 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1114 error!("Failed to patch initrd range to DT: {e}");
1115 RebootReason::InvalidFdt
1116 })?;
1117 }
1118 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1119 error!("Failed to patch memory range to DT: {e}");
1120 RebootReason::InvalidFdt
1121 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001122 if let Some(bootargs) = &info.bootargs {
1123 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1124 error!("Failed to patch bootargs to DT: {e}");
1125 RebootReason::InvalidFdt
1126 })?;
1127 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001128 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001129 error!("Failed to patch cpus to DT: {e}");
1130 RebootReason::InvalidFdt
1131 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001132 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1133 error!("Failed to patch vcpufreq info to DT: {e}");
1134 RebootReason::InvalidFdt
1135 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001136 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1137 error!("Failed to patch pci info to DT: {e}");
1138 RebootReason::InvalidFdt
1139 })?;
1140 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1141 error!("Failed to patch serial info to DT: {e}");
1142 RebootReason::InvalidFdt
1143 })?;
1144 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1145 error!("Failed to patch swiotlb info to DT: {e}");
1146 RebootReason::InvalidFdt
1147 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001148 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001149 error!("Failed to patch gic info to DT: {e}");
1150 RebootReason::InvalidFdt
1151 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001152 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001153 error!("Failed to patch timer info to DT: {e}");
1154 RebootReason::InvalidFdt
1155 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001156 if let Some(device_assignment) = &info.device_assignment {
1157 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1158 // then VM DTBO's underlying slice is allocated.
1159 device_assignment.patch(fdt).map_err(|e| {
1160 error!("Failed to patch device assignment info to DT: {e}");
1161 RebootReason::InvalidFdt
1162 })?;
1163 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001164 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1165 error!("Failed to patch untrusted properties: {e}");
1166 RebootReason::InvalidFdt
1167 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001168
Jiyong Park9c63cd12023-03-21 17:53:07 +09001169 Ok(())
1170}
1171
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001172/// Modifies the input DT according to the fields of the configuration.
1173pub fn modify_for_next_stage(
1174 fdt: &mut Fdt,
1175 bcc: &[u8],
1176 new_instance: bool,
1177 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001178 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001179 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001180 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001181) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001182 if let Some(debug_policy) = debug_policy {
1183 let backup = Vec::from(fdt.as_slice());
1184 fdt.unpack()?;
1185 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1186 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1187 info!("Debug policy applied.");
1188 } else {
1189 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1190 fdt.unpack()?;
1191 }
1192 } else {
1193 info!("No debug policy found.");
1194 fdt.unpack()?;
1195 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001196
Jiyong Parke9d87e82023-03-21 19:28:40 +09001197 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001198
Alice Wang56ec45b2023-06-15 08:30:32 +00001199 if let Some(mut chosen) = fdt.chosen_mut()? {
1200 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1201 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001202 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001203 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001204 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001205 if let Some(bootargs) = read_bootargs_from(fdt)? {
1206 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1207 }
1208 }
1209
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001210 fdt.pack()?;
1211
1212 Ok(())
1213}
1214
Jiyong Parke9d87e82023-03-21 19:28:40 +09001215/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1216fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001217 // We reject DTs with missing reserved-memory node as validation should have checked that the
1218 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001219 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001220
Jiyong Parke9d87e82023-03-21 19:28:40 +09001221 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001222
Jiyong Parke9d87e82023-03-21 19:28:40 +09001223 let addr: u64 = addr.try_into().unwrap();
1224 let size: u64 = size.try_into().unwrap();
1225 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001226}
1227
Alice Wang56ec45b2023-06-15 08:30:32 +00001228fn empty_or_delete_prop(
1229 fdt_node: &mut FdtNodeMut,
1230 prop_name: &CStr,
1231 keep_prop: bool,
1232) -> libfdt::Result<()> {
1233 if keep_prop {
1234 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001235 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001236 fdt_node
1237 .delprop(prop_name)
1238 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001239 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001240}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001241
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001242/// Apply the debug policy overlay to the guest DT.
1243///
1244/// 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 +00001245fn apply_debug_policy(
1246 fdt: &mut Fdt,
1247 backup_fdt: &Fdt,
1248 debug_policy: &[u8],
1249) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001250 let mut debug_policy = Vec::from(debug_policy);
1251 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001252 Ok(overlay) => overlay,
1253 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001254 warn!("Corrupted debug policy found: {e}. Not applying.");
1255 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001256 }
1257 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001258
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001259 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001260 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001261 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001262 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001263 // A successful restoration is considered success because an invalid debug policy
1264 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001265 Ok(false)
1266 } else {
1267 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001268 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001269}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001270
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001271fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001272 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1273 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1274 return Ok(value == 1);
1275 }
1276 }
1277 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1278}
1279
1280fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001281 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1282 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001283
1284 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1285 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1286 ("crashkernel", Box::new(|_| has_crashkernel)),
1287 ("console", Box::new(|_| has_console)),
1288 ];
1289
1290 // parse and filter out unwanted
1291 let mut filtered = Vec::new();
1292 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1293 info!("Invalid bootarg: {e}");
1294 FdtError::BadValue
1295 })? {
1296 match accepted.iter().find(|&t| t.0 == arg.name()) {
1297 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1298 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1299 }
1300 }
1301
1302 // flatten into a new C-string
1303 let mut new_bootargs = Vec::new();
1304 for (i, arg) in filtered.iter().enumerate() {
1305 if i != 0 {
1306 new_bootargs.push(b' '); // separator
1307 }
1308 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1309 }
1310 new_bootargs.push(b'\0');
1311
1312 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1313 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1314}