blob: f667d60ae70285a51cded56f08cefdfb79788c31 [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! High-level FDT functions.
16
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090017use crate::bootargs::BootArgsIterator;
Jaewan Kim50246682024-03-11 23:18:54 +090018use crate::device_assignment::{self, DeviceAssignmentInfo, VmDtbo};
Jiyong Park00ceff32023-03-13 05:43:23 +000019use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090020use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000021use crate::RebootReason;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000024use alloc::format;
Jiyong Parkc23426b2023-04-10 17:32:27 +090025use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090026use core::cmp::max;
27use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000029use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090030use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use libfdt::AddressRange;
34use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000035use libfdt::Fdt;
36use libfdt::FdtError;
David Dai9bdb10c2024-02-01 22:42:54 -080037use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +000039use libfdt::Phandle;
Jiyong Park83316122023-03-21 09:39:39 +090040use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000041use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090042use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000043use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000044use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000045use tinyvec::ArrayVec;
Pierre-Clément Tosif2c19d42024-10-01 17:42:04 +010046use vmbase::fdt::pci::PciMemoryFlags;
47use vmbase::fdt::pci::PciRangeType;
Alice Wanga3971062023-06-13 11:48:53 +000048use vmbase::fdt::SwiotlbInfo;
Pierre-Clément Tosia9b345f2024-04-27 01:01:42 +010049use vmbase::hyp;
Alice Wang63f4c9e2023-06-12 09:36:43 +000050use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000051use vmbase::memory::SIZE_4KB;
52use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000053use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000054use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000055
Alice Wangabc7d632023-06-14 09:10:14 +000056/// An enumeration of errors that can occur during the FDT validation.
57#[derive(Clone, Debug)]
58pub enum FdtValidationError {
59 /// Invalid CPU count.
60 InvalidCpuCount(usize),
David Dai9bdb10c2024-02-01 22:42:54 -080061 /// Invalid VCpufreq Range.
62 InvalidVcpufreq(u64, u64),
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000063 /// Forbidden /avf/untrusted property.
64 ForbiddenUntrustedProp(&'static CStr),
Alice Wangabc7d632023-06-14 09:10:14 +000065}
66
67impl fmt::Display for FdtValidationError {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 match self {
70 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +000071 Self::InvalidVcpufreq(addr, size) => {
72 write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})")
73 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +000074 Self::ForbiddenUntrustedProp(name) => {
75 write!(f, "Forbidden /avf/untrusted property '{name:?}'")
76 }
Alice Wangabc7d632023-06-14 09:10:14 +000077 }
78 }
79}
80
Jiyong Park6a8789a2023-03-21 14:50:59 +090081/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
82/// not an error.
83fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090084 let addr = cstr!("kernel-address");
85 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000086
Jiyong Parkb87f3302023-03-21 10:03:11 +090087 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000088 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
89 let addr = addr as usize;
90 let size = size as usize;
91
92 return Ok(Some(addr..(addr + size)));
93 }
94 }
95
96 Ok(None)
97}
98
Jiyong Park6a8789a2023-03-21 14:50:59 +090099/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
100/// error as there can be initrd-less VM.
101fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +0900102 let start = cstr!("linux,initrd-start");
103 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000104
105 if let Some(chosen) = fdt.chosen()? {
106 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
107 return Ok(Some((start as usize)..(end as usize)));
108 }
109 }
110
111 Ok(None)
112}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000113
Jiyong Park9c63cd12023-03-21 17:53:07 +0900114fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
115 let start = u32::try_from(initrd_range.start).unwrap();
116 let end = u32::try_from(initrd_range.end).unwrap();
117
118 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
119 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
120 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
121 Ok(())
122}
123
Jiyong Parke9d87e82023-03-21 19:28:40 +0900124fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
125 if let Some(chosen) = fdt.chosen()? {
126 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
127 // We need to copy the string to heap because the original fdt will be invalidated
128 // by the templated DT
129 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
130 return Ok(Some(copy));
131 }
132 }
133 Ok(None)
134}
135
136fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
137 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900138 // This function is called before the verification is done. So, we just copy the bootargs to
139 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
140 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900141 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
142}
143
Alice Wang0d527472023-06-13 14:55:38 +0000144/// Reads and validates the memory range in the DT.
145///
146/// Only one memory range is expected with the crosvm setup for now.
147fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
148 let mut memory = fdt.memory().map_err(|e| {
149 error!("Failed to read memory range from DT: {e}");
150 RebootReason::InvalidFdt
151 })?;
152 let range = memory.next().ok_or_else(|| {
153 error!("The /memory node in the DT contains no range.");
154 RebootReason::InvalidFdt
155 })?;
156 if memory.next().is_some() {
157 warn!(
158 "The /memory node in the DT contains more than one memory range, \
159 while only one is expected."
160 );
161 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900162 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000163 if base != MEM_START {
164 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000165 return Err(RebootReason::InvalidFdt);
166 }
167
Jiyong Park6a8789a2023-03-21 14:50:59 +0900168 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000169 if size % GUEST_PAGE_SIZE != 0 {
170 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
171 return Err(RebootReason::InvalidFdt);
172 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000173
Jiyong Park6a8789a2023-03-21 14:50:59 +0900174 if size == 0 {
175 error!("Memory size is 0");
176 return Err(RebootReason::InvalidFdt);
177 }
Alice Wang0d527472023-06-13 14:55:38 +0000178 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000179}
180
Jiyong Park9c63cd12023-03-21 17:53:07 +0900181fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000182 let addr = u64::try_from(MEM_START).unwrap();
183 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900184 fdt.node_mut(cstr!("/memory"))?
185 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000186 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900187}
188
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000189#[derive(Debug, Default)]
David Dai9bdb10c2024-02-01 22:42:54 -0800190struct CpuInfo {
191 opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai50168a32024-02-14 17:00:48 -0800192 cpu_capacity: Option<u32>,
David Dai9bdb10c2024-02-01 22:42:54 -0800193}
194
195impl CpuInfo {
David Dai622c05d2024-02-14 14:03:26 -0800196 const MAX_OPPTABLES: usize = 20;
David Dai9bdb10c2024-02-01 22:42:54 -0800197}
198
199fn read_opp_info_from(
200 opp_node: FdtNode,
201) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> {
202 let mut table = ArrayVec::new();
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100203 let mut opp_nodes = opp_node.subnodes()?;
204 for subnode in opp_nodes.by_ref().take(table.capacity()) {
David Dai9bdb10c2024-02-01 22:42:54 -0800205 let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?;
206 table.push(prop);
207 }
208
Pierre-Clément Tosidf272a52024-04-15 16:07:58 +0100209 if opp_nodes.next().is_some() {
210 warn!("OPP table has more than {} entries: discarding extra nodes.", table.capacity());
211 }
212
David Dai9bdb10c2024-02-01 22:42:54 -0800213 Ok(table)
214}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900215
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000216#[derive(Debug, Default)]
217struct ClusterTopology {
218 // TODO: Support multi-level clusters & threads.
219 cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER],
220}
221
222impl ClusterTopology {
David Daib19fd082024-04-19 16:33:26 -0700223 const MAX_CORES_PER_CLUSTER: usize = 10;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000224}
225
226#[derive(Debug, Default)]
227struct CpuTopology {
228 // TODO: Support sockets.
229 clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS],
230}
231
232impl CpuTopology {
233 const MAX_CLUSTERS: usize = 3;
234}
235
236fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> {
237 let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else {
238 return Ok(None);
239 };
240
241 let mut topology = BTreeMap::new();
242 for n in 0..CpuTopology::MAX_CLUSTERS {
243 let name = CString::new(format!("cluster{n}")).unwrap();
244 let Some(cluster) = cpu_map.subnode(&name)? else {
245 break;
246 };
247 for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER {
David Dai8f476cb2024-02-15 21:57:01 -0800248 let name = CString::new(format!("core{m}")).unwrap();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000249 let Some(core) = cluster.subnode(&name)? else {
250 break;
251 };
252 let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?;
253 let prev = topology.insert(cpu.try_into()?, (n, m));
254 if prev.is_some() {
255 return Err(FdtError::BadValue);
256 }
257 }
258 }
259
260 Ok(Some(topology))
261}
262
263fn read_cpu_info_from(
264 fdt: &Fdt,
265) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000266 let mut cpus = ArrayVec::new();
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000267
268 let cpu_map = read_cpu_map_from(fdt)?;
269 let mut topology: CpuTopology = Default::default();
270
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100271 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,armv8"))?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000272 for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800273 let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?;
David Dai9bdb10c2024-02-01 22:42:54 -0800274 let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?;
275 let opptable_info = if let Some(phandle) = opp_phandle {
276 let phandle = phandle.try_into()?;
277 let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?;
278 Some(read_opp_info_from(node)?)
279 } else {
280 None
281 };
David Dai50168a32024-02-14 17:00:48 -0800282 let info = CpuInfo { opptable_info, cpu_capacity };
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000283 cpus.push(info);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000284
285 if let Some(ref cpu_map) = cpu_map {
286 let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?;
David Dai8f476cb2024-02-15 21:57:01 -0800287 let (cluster, core_idx) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000288 let cluster = topology.clusters[*cluster].get_or_insert(Default::default());
David Dai8f476cb2024-02-15 21:57:01 -0800289 if cluster.cores[*core_idx].is_some() {
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000290 return Err(FdtError::BadValue);
291 }
David Dai8f476cb2024-02-15 21:57:01 -0800292 cluster.cores[*core_idx] = Some(idx);
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000293 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900294 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000295
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000296 if cpu_nodes.next().is_some() {
297 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
298 }
299
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000300 Ok((cpus, cpu_map.map(|_| topology)))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900301}
302
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000303fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
304 if cpus.is_empty() {
305 return Err(FdtValidationError::InvalidCpuCount(0));
306 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000307 Ok(())
308}
309
David Dai9bdb10c2024-02-01 22:42:54 -0800310fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> {
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000311 let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?;
312 let Some(node) = nodes.next() else {
313 return Ok(None);
David Dai9bdb10c2024-02-01 22:42:54 -0800314 };
315
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000316 if nodes.next().is_some() {
317 warn!("DT has more than 1 cpufreq node: discarding extra nodes.");
318 }
319
320 let mut regs = node.reg()?.ok_or(FdtError::NotFound)?;
321 let reg = regs.next().ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000322 let size = reg.size.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000323
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000324 Ok(Some(VcpufreqInfo { addr: reg.addr, size }))
David Dai9bdb10c2024-02-01 22:42:54 -0800325}
326
327fn validate_vcpufreq_info(
328 vcpufreq_info: &VcpufreqInfo,
329 cpus: &[CpuInfo],
330) -> Result<(), FdtValidationError> {
331 const VCPUFREQ_BASE_ADDR: u64 = 0x1040000;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000332 const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8;
David Dai9bdb10c2024-02-01 22:42:54 -0800333
334 let base = vcpufreq_info.addr;
335 let size = vcpufreq_info.size;
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000336 let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64;
337
338 if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) {
David Dai9bdb10c2024-02-01 22:42:54 -0800339 return Err(FdtValidationError::InvalidVcpufreq(base, size));
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000340 }
David Dai9bdb10c2024-02-01 22:42:54 -0800341
342 Ok(())
343}
344
345fn patch_opptable(
346 node: FdtNodeMut,
David Dai622c05d2024-02-14 14:03:26 -0800347 opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>,
David Dai9bdb10c2024-02-01 22:42:54 -0800348) -> libfdt::Result<()> {
349 let oppcompat = cstr!("operating-points-v2");
350 let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000351
352 let Some(opptable) = opptable else {
353 return next.nop();
354 };
355
David Dai9bdb10c2024-02-01 22:42:54 -0800356 let mut next_subnode = next.first_subnode()?;
357
358 for entry in opptable {
359 let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?;
360 subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?;
361 next_subnode = subnode.next_subnode()?;
362 }
363
364 while let Some(current) = next_subnode {
365 next_subnode = current.delete_and_next_subnode()?;
366 }
Pierre-Clément Tosi8ba89802024-02-14 12:26:01 +0000367
David Dai9bdb10c2024-02-01 22:42:54 -0800368 Ok(())
369}
370
371// TODO(ptosi): Rework FdtNodeMut and replace this function.
372fn get_nth_compatible<'a>(
373 fdt: &'a mut Fdt,
374 n: usize,
375 compat: &CStr,
376) -> libfdt::Result<Option<FdtNodeMut<'a>>> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000377 let mut node = fdt.root_mut().next_compatible(compat)?;
David Dai9bdb10c2024-02-01 22:42:54 -0800378 for _ in 0..n {
379 node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?;
380 }
381 Ok(node)
382}
383
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000384fn patch_cpus(
385 fdt: &mut Fdt,
386 cpus: &[CpuInfo],
387 topology: &Option<CpuTopology>,
388) -> libfdt::Result<()> {
Pierre-Clément Tosi6ae8fe22024-04-17 20:02:23 +0100389 const COMPAT: &CStr = cstr!("arm,armv8");
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000390 let mut cpu_phandles = Vec::new();
David Dai9bdb10c2024-02-01 22:42:54 -0800391 for (idx, cpu) in cpus.iter().enumerate() {
David Dai50168a32024-02-14 17:00:48 -0800392 let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?;
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000393 let phandle = cur.as_node().get_phandle()?.unwrap();
394 cpu_phandles.push(phandle);
David Dai50168a32024-02-14 17:00:48 -0800395 if let Some(cpu_capacity) = cpu.cpu_capacity {
396 cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?;
397 }
Pierre-Clément Tosic37c72e2024-02-14 12:18:12 +0000398 patch_opptable(cur, cpu.opptable_info)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900399 }
David Dai9bdb10c2024-02-01 22:42:54 -0800400 let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900401 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000402 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900403 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000404
405 if let Some(topology) = topology {
406 for (n, cluster) in topology.clusters.iter().enumerate() {
407 let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap();
408 let cluster_node = fdt.node_mut(&path)?.unwrap();
409 if let Some(cluster) = cluster {
410 let mut iter = cluster_node.first_subnode()?;
411 for core in cluster.cores {
412 let mut core_node = iter.unwrap();
413 iter = if let Some(core_idx) = core {
414 let phandle = *cpu_phandles.get(core_idx).unwrap();
415 let value = u32::from(phandle).to_be_bytes();
416 core_node.setprop_inplace(cstr!("cpu"), &value)?;
417 core_node.next_subnode()?
418 } else {
419 core_node.delete_and_next_subnode()?
420 };
421 }
422 assert!(iter.is_none());
423 } else {
424 cluster_node.nop()?;
425 }
426 }
427 } else {
428 fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?;
429 }
430
Jiyong Park6a8789a2023-03-21 14:50:59 +0900431 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000432}
433
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000434/// Reads the /avf/untrusted DT node, which the host can use to pass properties (no subnodes) to
435/// the guest that don't require being validated by pvmfw.
436fn parse_untrusted_props(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
437 let mut props = BTreeMap::new();
438 if let Some(node) = fdt.node(cstr!("/avf/untrusted"))? {
439 for property in node.properties()? {
440 let name = property.name()?;
441 let value = property.value()?;
442 props.insert(CString::from(name), value.to_vec());
443 }
444 if node.subnodes()?.next().is_some() {
445 warn!("Discarding unexpected /avf/untrusted subnodes.");
446 }
447 }
448
449 Ok(props)
450}
451
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900452/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900453fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900454 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900455 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900456 for property in avf_node.properties()? {
457 let name = property.name()?;
458 let value = property.value()?;
459 property_map.insert(
460 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
461 value.to_vec(),
462 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900463 }
464 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900465 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900466}
467
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000468fn validate_untrusted_props(props: &BTreeMap<CString, Vec<u8>>) -> Result<(), FdtValidationError> {
469 const FORBIDDEN_PROPS: &[&CStr] =
470 &[cstr!("compatible"), cstr!("linux,phandle"), cstr!("phandle")];
471
472 for name in FORBIDDEN_PROPS {
473 if props.contains_key(*name) {
474 return Err(FdtValidationError::ForbiddenUntrustedProp(name));
475 }
476 }
477
478 Ok(())
479}
480
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900481/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
482/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
483fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900484 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900485 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900486 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900487) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000488 let root_vm_dt = vm_dt.root_mut();
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900489 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900490 // TODO(b/318431677): Validate nodes beyond /avf.
491 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900492 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900493 if let Some(ref_value) = avf_node.getprop(name)? {
494 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900495 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900496 "Property mismatches while applying overlay VM reference DT. \
497 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
498 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900499 );
500 return Err(FdtError::BadValue);
501 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900502 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900503 }
504 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900505 Ok(())
506}
507
Jiyong Park00ceff32023-03-13 05:43:23 +0000508#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000509struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900510 ranges: [PciAddrRange; 2],
511 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
512 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000513}
514
Jiyong Park6a8789a2023-03-21 14:50:59 +0900515impl PciInfo {
516 const IRQ_MASK_CELLS: usize = 4;
517 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe2d0969c2024-06-06 12:59:12 +0000518 const MAX_IRQS: usize = 16;
Jiyong Park00ceff32023-03-13 05:43:23 +0000519}
520
Jiyong Park6a8789a2023-03-21 14:50:59 +0900521type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
522type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
523type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000524
525/// Iterator that takes N cells as a chunk
526struct CellChunkIterator<'a, const N: usize> {
527 cells: CellIterator<'a>,
528}
529
530impl<'a, const N: usize> CellChunkIterator<'a, N> {
531 fn new(cells: CellIterator<'a>) -> Self {
532 Self { cells }
533 }
534}
535
536impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
537 type Item = [u32; N];
538 fn next(&mut self) -> Option<Self::Item> {
539 let mut ret: Self::Item = [0; N];
540 for i in ret.iter_mut() {
541 *i = self.cells.next()?;
542 }
543 Some(ret)
544 }
545}
546
Jiyong Park6a8789a2023-03-21 14:50:59 +0900547/// Read pci host controller ranges, irq maps, and irq map masks from DT
548fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
549 let node =
550 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
551
552 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
553 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
554 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
555
556 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000557 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
558 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
559
560 if chunks.next().is_some() {
561 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
562 return Err(FdtError::NoSpace);
563 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900564
565 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000566 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
567 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
568
569 if chunks.next().is_some() {
570 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
571 return Err(FdtError::NoSpace);
572 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900573
574 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
575}
576
Jiyong Park0ee65392023-03-27 20:52:45 +0900577fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900578 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900579 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900580 }
581 for irq_mask in pci_info.irq_masks.iter() {
582 validate_pci_irq_mask(irq_mask)?;
583 }
584 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
585 validate_pci_irq_map(irq_map, idx)?;
586 }
587 Ok(())
588}
589
Jiyong Park0ee65392023-03-27 20:52:45 +0900590fn validate_pci_addr_range(
591 range: &PciAddrRange,
592 memory_range: &Range<usize>,
593) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900594 let mem_flags = PciMemoryFlags(range.addr.0);
595 let range_type = mem_flags.range_type();
Jiyong Park6a8789a2023-03-21 14:50:59 +0900596 let bus_addr = range.addr.1;
597 let cpu_addr = range.parent_addr;
598 let size = range.size;
599
600 if range_type != PciRangeType::Memory64 {
601 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
602 return Err(RebootReason::InvalidFdt);
603 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604 // Enforce ID bus-to-cpu mappings, as used by crosvm.
605 if bus_addr != cpu_addr {
606 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
607 return Err(RebootReason::InvalidFdt);
608 }
609
Jiyong Park0ee65392023-03-27 20:52:45 +0900610 let Some(bus_end) = bus_addr.checked_add(size) else {
611 error!("PCI address range size {:#x} overflows", size);
612 return Err(RebootReason::InvalidFdt);
613 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000614 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900615 error!("PCI address end {:#x} is outside of translatable range", bus_end);
616 return Err(RebootReason::InvalidFdt);
617 }
618
619 let memory_start = memory_range.start.try_into().unwrap();
620 let memory_end = memory_range.end.try_into().unwrap();
621
622 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
623 error!(
624 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
625 bus_addr, bus_end, memory_start, memory_end
626 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900627 return Err(RebootReason::InvalidFdt);
628 }
629
630 Ok(())
631}
632
633fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000634 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
635 const IRQ_MASK_ADDR_ME: u32 = 0x0;
636 const IRQ_MASK_ADDR_LO: u32 = 0x0;
637 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900638 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000639 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900640 if *irq_mask != EXPECTED {
641 error!("Invalid PCI irq mask {:#?}", irq_mask);
642 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000643 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900644 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000645}
646
Jiyong Park6a8789a2023-03-21 14:50:59 +0900647fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000648 const PCI_DEVICE_IDX: usize = 11;
649 const PCI_IRQ_ADDR_ME: u32 = 0;
650 const PCI_IRQ_ADDR_LO: u32 = 0;
651 const PCI_IRQ_INTC: u32 = 1;
652 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
653 const GIC_SPI: u32 = 0;
654 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
655
Jiyong Park6a8789a2023-03-21 14:50:59 +0900656 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
657 let pci_irq_number = irq_map[3];
658 let _controller_phandle = irq_map[4]; // skipped.
659 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
660 // interrupt-cells is <3> for GIC
661 let gic_peripheral_interrupt_type = irq_map[7];
662 let gic_irq_number = irq_map[8];
663 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000664
Jiyong Park6a8789a2023-03-21 14:50:59 +0900665 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
666 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000667
Jiyong Park6a8789a2023-03-21 14:50:59 +0900668 if pci_addr != expected_pci_addr {
669 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
670 {:#x} {:#x} {:#x}",
671 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
672 return Err(RebootReason::InvalidFdt);
673 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000674
Jiyong Park6a8789a2023-03-21 14:50:59 +0900675 if pci_irq_number != PCI_IRQ_INTC {
676 error!(
677 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
678 pci_irq_number, PCI_IRQ_INTC
679 );
680 return Err(RebootReason::InvalidFdt);
681 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000682
Jiyong Park6a8789a2023-03-21 14:50:59 +0900683 if gic_addr != (0, 0) {
684 error!(
685 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
686 {:#x} {:#x}",
687 gic_addr.0, gic_addr.1, 0, 0
688 );
689 return Err(RebootReason::InvalidFdt);
690 }
691
692 if gic_peripheral_interrupt_type != GIC_SPI {
693 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
694 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
695 return Err(RebootReason::InvalidFdt);
696 }
697
698 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
699 if gic_irq_number != irq_nr {
700 error!(
701 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
702 gic_irq_number, irq_nr
703 );
704 return Err(RebootReason::InvalidFdt);
705 }
706
707 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
708 error!(
709 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
710 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
711 );
712 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000713 }
714 Ok(())
715}
716
Jiyong Park9c63cd12023-03-21 17:53:07 +0900717fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000718 let mut node =
719 fdt.root_mut().next_compatible(cstr!("pci-host-cam-generic"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900720
721 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
722 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
723
724 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
725 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
726
727 node.setprop_inplace(
728 cstr!("ranges"),
729 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
730 )
731}
732
Jiyong Park00ceff32023-03-13 05:43:23 +0000733#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900734struct SerialInfo {
735 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000736}
737
738impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900739 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000740}
741
Jiyong Park6a8789a2023-03-21 14:50:59 +0900742fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000743 let mut addrs = ArrayVec::new();
744
745 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
746 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000747 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900748 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000749 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000750 if serial_nodes.next().is_some() {
751 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
752 }
753
Jiyong Park6a8789a2023-03-21 14:50:59 +0900754 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000755}
756
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000757#[derive(Default, Debug, PartialEq)]
758struct WdtInfo {
759 addr: u64,
760 size: u64,
761 irq: [u32; WdtInfo::IRQ_CELLS],
762}
763
764impl WdtInfo {
765 const IRQ_CELLS: usize = 3;
766 const IRQ_NR: u32 = 0xf;
767 const ADDR: u64 = 0x3000;
768 const SIZE: u64 = 0x1000;
769 const GIC_PPI: u32 = 1;
770 const IRQ_TYPE_EDGE_RISING: u32 = 1;
771 const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100772 // TODO(b/350498812): Rework this for >8 vCPUs.
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000773 const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT;
774
775 const fn get_expected(num_cpus: usize) -> Self {
776 Self {
777 addr: Self::ADDR,
778 size: Self::SIZE,
779 irq: [
780 Self::GIC_PPI,
781 Self::IRQ_NR,
782 ((((1 << num_cpus) - 1) << Self::GIC_FDT_IRQ_PPI_CPU_SHIFT)
783 & Self::GIC_FDT_IRQ_PPI_CPU_MASK)
784 | Self::IRQ_TYPE_EDGE_RISING,
785 ],
786 }
787 }
788}
789
790fn read_wdt_info_from(fdt: &Fdt) -> libfdt::Result<WdtInfo> {
791 let mut node_iter = fdt.compatible_nodes(cstr!("qemu,vcpu-stall-detector"))?;
792 let node = node_iter.next().ok_or(FdtError::NotFound)?;
793 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
794
795 let reg = ranges.next().ok_or(FdtError::NotFound)?;
796 let size = reg.size.ok_or(FdtError::NotFound)?;
797 if ranges.next().is_some() {
798 warn!("Discarding extra vmwdt <reg> entries.");
799 }
800
801 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
802 let mut chunks = CellChunkIterator::<{ WdtInfo::IRQ_CELLS }>::new(interrupts);
803 let irq = chunks.next().ok_or(FdtError::NotFound)?;
804
805 if chunks.next().is_some() {
806 warn!("Discarding extra vmwdt <interrupts> entries.");
807 }
808
809 Ok(WdtInfo { addr: reg.addr, size, irq })
810}
811
812fn validate_wdt_info(wdt: &WdtInfo, num_cpus: usize) -> Result<(), RebootReason> {
813 if *wdt != WdtInfo::get_expected(num_cpus) {
814 error!("Invalid watchdog timer: {wdt:?}");
815 return Err(RebootReason::InvalidFdt);
816 }
817
818 Ok(())
819}
820
821fn patch_wdt_info(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
822 let mut interrupts = WdtInfo::get_expected(num_cpus).irq;
823 for v in interrupts.iter_mut() {
824 *v = v.to_be();
825 }
826
827 let mut node = fdt
828 .root_mut()
829 .next_compatible(cstr!("qemu,vcpu-stall-detector"))?
830 .ok_or(libfdt::FdtError::NotFound)?;
831 node.setprop_inplace(cstr!("interrupts"), interrupts.as_bytes())?;
832 Ok(())
833}
834
Jiyong Park9c63cd12023-03-21 17:53:07 +0900835/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
836fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
837 let name = cstr!("ns16550a");
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000838 let mut next = fdt.root_mut().next_compatible(name);
Jiyong Park9c63cd12023-03-21 17:53:07 +0900839 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000840 let reg =
841 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900842 next = if !serial_info.addrs.contains(&reg.addr) {
843 current.delete_and_next_compatible(name)
844 } else {
845 current.next_compatible(name)
846 }
847 }
848 Ok(())
849}
850
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700851fn validate_swiotlb_info(
852 swiotlb_info: &SwiotlbInfo,
853 memory: &Range<usize>,
854) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900855 let size = swiotlb_info.size;
856 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000857
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700858 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000859 error!("Invalid swiotlb size {:#x}", size);
860 return Err(RebootReason::InvalidFdt);
861 }
862
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000863 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000864 error!("Invalid swiotlb alignment {:#x}", align);
865 return Err(RebootReason::InvalidFdt);
866 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700867
Alice Wang9cfbfd62023-06-14 11:19:03 +0000868 if let Some(addr) = swiotlb_info.addr {
869 if addr.checked_add(size).is_none() {
870 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
871 return Err(RebootReason::InvalidFdt);
872 }
873 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700874 if let Some(range) = swiotlb_info.fixed_range() {
875 if !range.is_within(memory) {
876 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
877 return Err(RebootReason::InvalidFdt);
878 }
879 }
880
Jiyong Park6a8789a2023-03-21 14:50:59 +0900881 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000882}
883
Jiyong Park9c63cd12023-03-21 17:53:07 +0900884fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
885 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000886 fdt.root_mut().next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700887
888 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000889 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700890 cstr!("reg"),
891 range.start.try_into().unwrap(),
892 range.len().try_into().unwrap(),
893 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000894 node.nop_property(cstr!("size"))?;
895 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700896 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000897 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700898 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000899 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700900 }
901
Jiyong Park9c63cd12023-03-21 17:53:07 +0900902 Ok(())
903}
904
905fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
906 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
907 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
908 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
909 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
910
911 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000912 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
913 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000914 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900915
916 // range1 is just below range0
917 range1.addr = addr - size;
918 range1.size = Some(size);
919
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000920 let (addr0, size0) = range0.to_cells();
921 let (addr1, size1) = range1.to_cells();
922 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900923
924 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000925 fdt.root_mut().next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900926 node.setprop_inplace(cstr!("reg"), flatten(&value))
927}
928
929fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
930 const NUM_INTERRUPTS: usize = 4;
931 const CELLS_PER_INTERRUPT: usize = 3;
932 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
933 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
934 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
935 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
936
937 let num_cpus: u32 = num_cpus.try_into().unwrap();
Pierre-Clément Tosi3ad82742024-07-04 10:23:00 +0100938 // TODO(b/350498812): Rework this for >8 vCPUs.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900939 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
Sebastian Enee8e99fa2024-05-23 14:49:41 +0000940
Jiyong Park9c63cd12023-03-21 17:53:07 +0900941 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
942 *v |= cpu_mask;
943 }
944 for v in value.iter_mut() {
945 *v = v.to_be();
946 }
947
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000948 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900949
950 let mut node =
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000951 fdt.root_mut().next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000952 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900953}
954
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000955fn patch_untrusted_props(fdt: &mut Fdt, props: &BTreeMap<CString, Vec<u8>>) -> libfdt::Result<()> {
956 let avf_node = if let Some(node) = fdt.node_mut(cstr!("/avf"))? {
957 node
958 } else {
Pierre-Clément Tosi244efea2024-02-16 14:48:14 +0000959 fdt.root_mut().add_subnode(cstr!("avf"))?
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000960 };
961
962 // The node shouldn't already be present; if it is, return the error.
963 let mut node = avf_node.add_subnode(cstr!("untrusted"))?;
964
965 for (name, value) in props {
966 node.setprop(name, value)?;
967 }
968
969 Ok(())
970}
971
Jiyong Park00ceff32023-03-13 05:43:23 +0000972#[derive(Debug)]
David Dai9bdb10c2024-02-01 22:42:54 -0800973struct VcpufreqInfo {
974 addr: u64,
975 size: u64,
976}
977
978fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> {
979 let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap();
980 if let Some(info) = vcpufreq_info {
981 node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size)
982 } else {
983 node.nop()
984 }
985}
986
987#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900988pub struct DeviceTreeInfo {
989 pub kernel_range: Option<Range<usize>>,
990 pub initrd_range: Option<Range<usize>>,
991 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900992 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000993 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +0000994 cpu_topology: Option<CpuTopology>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000995 pci_info: PciInfo,
996 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700997 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900998 device_assignment: Option<DeviceAssignmentInfo>,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +0000999 untrusted_props: BTreeMap<CString, Vec<u8>>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001000 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
David Dai9bdb10c2024-02-01 22:42:54 -08001001 vcpufreq_info: Option<VcpufreqInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +00001002}
1003
1004impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001005 const MAX_CPUS: usize = 16;
1006
1007 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +00001008 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
1009
1010 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
1011 }
Jiyong Park00ceff32023-03-13 05:43:23 +00001012}
1013
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001014pub fn sanitize_device_tree(
1015 fdt: &mut [u8],
1016 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001017 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001018) -> Result<DeviceTreeInfo, RebootReason> {
1019 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
1020 error!("Failed to load FDT: {e}");
1021 RebootReason::InvalidFdt
1022 })?;
1023
1024 let vm_dtbo = match vm_dtbo {
1025 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
1026 error!("Failed to load VM DTBO: {e}");
1027 RebootReason::InvalidFdt
1028 })?),
1029 None => None,
1030 };
1031
1032 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +09001033
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001034 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
1035 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
1036 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +09001037 error!("Failed to instantiate FDT from the template DT: {e}");
1038 RebootReason::InvalidFdt
1039 })?;
1040
Jaewan Kim9220e852023-12-01 10:58:40 +09001041 fdt.unpack().map_err(|e| {
1042 error!("Failed to unpack DT for patching: {e}");
1043 RebootReason::InvalidFdt
1044 })?;
1045
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001046 if let Some(device_assignment_info) = &info.device_assignment {
1047 let vm_dtbo = vm_dtbo.unwrap();
1048 device_assignment_info.filter(vm_dtbo).map_err(|e| {
1049 error!("Failed to filter VM DTBO: {e}");
1050 RebootReason::InvalidFdt
1051 })?;
1052 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
1053 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
1054 // it can only be instantiated after validation.
1055 unsafe {
1056 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
1057 error!("Failed to apply filtered VM DTBO: {e}");
1058 RebootReason::InvalidFdt
1059 })?;
1060 }
1061 }
1062
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001063 if let Some(vm_ref_dt) = vm_ref_dt {
1064 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
1065 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001066 RebootReason::InvalidFdt
1067 })?;
1068
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001069 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
1070 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001071 RebootReason::InvalidFdt
1072 })?;
1073 }
1074
Jiyong Park9c63cd12023-03-21 17:53:07 +09001075 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001076
Jaewan Kim19b984f2023-12-04 15:16:50 +09001077 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
1078
Jaewan Kim9220e852023-12-01 10:58:40 +09001079 fdt.pack().map_err(|e| {
1080 error!("Failed to unpack DT after patching: {e}");
1081 RebootReason::InvalidFdt
1082 })?;
1083
Jiyong Park6a8789a2023-03-21 14:50:59 +09001084 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +09001085}
1086
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001087fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001088 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
1089 error!("Failed to read kernel range from DT: {e}");
1090 RebootReason::InvalidFdt
1091 })?;
1092
1093 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
1094 error!("Failed to read initrd range from DT: {e}");
1095 RebootReason::InvalidFdt
1096 })?;
1097
Alice Wang0d527472023-06-13 14:55:38 +00001098 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001099
Jiyong Parke9d87e82023-03-21 19:28:40 +09001100 let bootargs = read_bootargs_from(fdt).map_err(|e| {
1101 error!("Failed to read bootargs from DT: {e}");
1102 RebootReason::InvalidFdt
1103 })?;
1104
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001105 let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001106 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +09001107 RebootReason::InvalidFdt
1108 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001109 validate_cpu_info(&cpus).map_err(|e| {
1110 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +00001111 RebootReason::InvalidFdt
1112 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001113
David Dai9bdb10c2024-02-01 22:42:54 -08001114 let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| {
1115 error!("Failed to read vcpufreq info from DT: {e}");
1116 RebootReason::InvalidFdt
1117 })?;
1118 if let Some(ref info) = vcpufreq_info {
1119 validate_vcpufreq_info(info, &cpus).map_err(|e| {
1120 error!("Failed to validate vcpufreq info from DT: {e}");
1121 RebootReason::InvalidFdt
1122 })?;
1123 }
1124
Jiyong Park6a8789a2023-03-21 14:50:59 +09001125 let pci_info = read_pci_info_from(fdt).map_err(|e| {
1126 error!("Failed to read pci info from DT: {e}");
1127 RebootReason::InvalidFdt
1128 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +09001129 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001130
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001131 let wdt_info = read_wdt_info_from(fdt).map_err(|e| {
1132 error!("Failed to read vCPU stall detector info from DT: {e}");
1133 RebootReason::InvalidFdt
1134 })?;
1135 validate_wdt_info(&wdt_info, cpus.len())?;
1136
Jiyong Park6a8789a2023-03-21 14:50:59 +09001137 let serial_info = read_serial_info_from(fdt).map_err(|e| {
1138 error!("Failed to read serial info from DT: {e}");
1139 RebootReason::InvalidFdt
1140 })?;
1141
Alice Wang9cfbfd62023-06-14 11:19:03 +00001142 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001143 error!("Failed to read swiotlb info from DT: {e}");
1144 RebootReason::InvalidFdt
1145 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -07001146 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +09001147
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001148 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001149 Some(vm_dtbo) => {
1150 if let Some(hypervisor) = hyp::get_device_assigner() {
Pierre-Clément Tosieacdd0f2024-10-22 16:31:01 +01001151 // TODO(ptosi): Cache the (single?) granule once, in vmbase.
1152 let granule = hyp::get_mem_sharer()
1153 .ok_or_else(|| {
1154 error!("No MEM_SHARE found during device assignment validation");
1155 RebootReason::InternalError
1156 })?
1157 .granule()
1158 .map_err(|e| {
1159 error!("Failed to get granule for device assignment validation: {e}");
1160 RebootReason::InternalError
1161 })?;
1162 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor, granule).map_err(|e| {
Jaewan Kim52477ae2023-11-21 21:20:52 +09001163 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
1164 RebootReason::InvalidFdt
1165 })?
1166 } else {
1167 warn!(
1168 "Device assignment is ignored because device assigning hypervisor is missing"
1169 );
1170 None
1171 }
1172 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001173 None => None,
1174 };
1175
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001176 let untrusted_props = parse_untrusted_props(fdt).map_err(|e| {
1177 error!("Failed to read untrusted properties: {e}");
1178 RebootReason::InvalidFdt
1179 })?;
1180 validate_untrusted_props(&untrusted_props).map_err(|e| {
1181 error!("Failed to validate untrusted properties: {e}");
1182 RebootReason::InvalidFdt
1183 })?;
1184
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001185 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +09001186 error!("Failed to read names of properties under /avf from DT: {e}");
1187 RebootReason::InvalidFdt
1188 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +09001189
Jiyong Park00ceff32023-03-13 05:43:23 +00001190 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +09001191 kernel_range,
1192 initrd_range,
1193 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +09001194 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001195 cpus,
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001196 cpu_topology,
Jiyong Park6a8789a2023-03-21 14:50:59 +09001197 pci_info,
1198 serial_info,
1199 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001200 device_assignment,
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001201 untrusted_props,
Seungjae Yoof0af81d2024-01-17 13:48:36 +09001202 vm_ref_dt_props_info,
David Dai9bdb10c2024-02-01 22:42:54 -08001203 vcpufreq_info,
Jiyong Park00ceff32023-03-13 05:43:23 +00001204 })
1205}
1206
Jiyong Park9c63cd12023-03-21 17:53:07 +09001207fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
1208 if let Some(initrd_range) = &info.initrd_range {
1209 patch_initrd_range(fdt, initrd_range).map_err(|e| {
1210 error!("Failed to patch initrd range to DT: {e}");
1211 RebootReason::InvalidFdt
1212 })?;
1213 }
1214 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
1215 error!("Failed to patch memory range to DT: {e}");
1216 RebootReason::InvalidFdt
1217 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001218 if let Some(bootargs) = &info.bootargs {
1219 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
1220 error!("Failed to patch bootargs to DT: {e}");
1221 RebootReason::InvalidFdt
1222 })?;
1223 }
Pierre-Clément Tosia0823f12024-02-15 16:41:05 +00001224 patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001225 error!("Failed to patch cpus to DT: {e}");
1226 RebootReason::InvalidFdt
1227 })?;
David Dai9bdb10c2024-02-01 22:42:54 -08001228 patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| {
1229 error!("Failed to patch vcpufreq info to DT: {e}");
1230 RebootReason::InvalidFdt
1231 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001232 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
1233 error!("Failed to patch pci info to DT: {e}");
1234 RebootReason::InvalidFdt
1235 })?;
Sebastian Enee8e99fa2024-05-23 14:49:41 +00001236 patch_wdt_info(fdt, info.cpus.len()).map_err(|e| {
1237 error!("Failed to patch wdt info to DT: {e}");
1238 RebootReason::InvalidFdt
1239 })?;
Jiyong Park9c63cd12023-03-21 17:53:07 +09001240 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
1241 error!("Failed to patch serial info to DT: {e}");
1242 RebootReason::InvalidFdt
1243 })?;
1244 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
1245 error!("Failed to patch swiotlb info to DT: {e}");
1246 RebootReason::InvalidFdt
1247 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001248 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001249 error!("Failed to patch gic info to DT: {e}");
1250 RebootReason::InvalidFdt
1251 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +00001252 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +09001253 error!("Failed to patch timer info to DT: {e}");
1254 RebootReason::InvalidFdt
1255 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001256 if let Some(device_assignment) = &info.device_assignment {
1257 // Note: We patch values after VM DTBO is overlaid because patch may require more space
1258 // then VM DTBO's underlying slice is allocated.
1259 device_assignment.patch(fdt).map_err(|e| {
1260 error!("Failed to patch device assignment info to DT: {e}");
1261 RebootReason::InvalidFdt
1262 })?;
Jaewan Kim50246682024-03-11 23:18:54 +09001263 } else {
1264 device_assignment::clean(fdt).map_err(|e| {
1265 error!("Failed to clean pre-polulated DT nodes for device assignment: {e}");
1266 RebootReason::InvalidFdt
1267 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +09001268 }
Pierre-Clément Tosi54e84b52024-02-15 20:06:22 +00001269 patch_untrusted_props(fdt, &info.untrusted_props).map_err(|e| {
1270 error!("Failed to patch untrusted properties: {e}");
1271 RebootReason::InvalidFdt
1272 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +09001273
Jiyong Park9c63cd12023-03-21 17:53:07 +09001274 Ok(())
1275}
1276
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001277/// Modifies the input DT according to the fields of the configuration.
1278pub fn modify_for_next_stage(
1279 fdt: &mut Fdt,
1280 bcc: &[u8],
1281 new_instance: bool,
1282 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +00001283 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001284 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001285 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001286) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001287 if let Some(debug_policy) = debug_policy {
1288 let backup = Vec::from(fdt.as_slice());
1289 fdt.unpack()?;
1290 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
1291 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
1292 info!("Debug policy applied.");
1293 } else {
1294 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
1295 fdt.unpack()?;
1296 }
1297 } else {
1298 info!("No debug policy found.");
1299 fdt.unpack()?;
1300 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001301
Jiyong Parke9d87e82023-03-21 19:28:40 +09001302 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001303
Alice Wang56ec45b2023-06-15 08:30:32 +00001304 if let Some(mut chosen) = fdt.chosen_mut()? {
1305 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
1306 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +00001307 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +00001308 };
Jiyong Park32f37ef2023-05-17 16:15:58 +09001309 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001310 if let Some(bootargs) = read_bootargs_from(fdt)? {
1311 filter_out_dangerous_bootargs(fdt, &bootargs)?;
1312 }
1313 }
1314
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001315 fdt.pack()?;
1316
1317 Ok(())
1318}
1319
Jiyong Parke9d87e82023-03-21 19:28:40 +09001320/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
1321fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001322 // We reject DTs with missing reserved-memory node as validation should have checked that the
1323 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +09001324 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001325
Jiyong Parke9d87e82023-03-21 19:28:40 +09001326 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001327
Jiyong Parke9d87e82023-03-21 19:28:40 +09001328 let addr: u64 = addr.try_into().unwrap();
1329 let size: u64 = size.try_into().unwrap();
1330 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001331}
1332
Alice Wang56ec45b2023-06-15 08:30:32 +00001333fn empty_or_delete_prop(
1334 fdt_node: &mut FdtNodeMut,
1335 prop_name: &CStr,
1336 keep_prop: bool,
1337) -> libfdt::Result<()> {
1338 if keep_prop {
1339 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001340 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +00001341 fdt_node
1342 .delprop(prop_name)
1343 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001344 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001345}
Jiyong Parkc23426b2023-04-10 17:32:27 +09001346
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001347/// Apply the debug policy overlay to the guest DT.
1348///
1349/// Returns Ok(true) on success, Ok(false) on recovered failure and Err(_) on corruption of the DT.
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +00001350fn apply_debug_policy(
1351 fdt: &mut Fdt,
1352 backup_fdt: &Fdt,
1353 debug_policy: &[u8],
1354) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001355 let mut debug_policy = Vec::from(debug_policy);
1356 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +09001357 Ok(overlay) => overlay,
1358 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001359 warn!("Corrupted debug policy found: {e}. Not applying.");
1360 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +09001361 }
1362 };
Jiyong Parkc23426b2023-04-10 17:32:27 +09001363
Andrew Walbran20bb4e42023-07-07 13:55:55 +01001364 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +09001365 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001366 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001367 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +09001368 // A successful restoration is considered success because an invalid debug policy
1369 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +00001370 Ok(false)
1371 } else {
1372 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +09001373 }
Jiyong Parkc23426b2023-04-10 17:32:27 +09001374}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001375
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001376fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001377 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
1378 if let Some(value) = node.getprop_u32(debug_feature_name)? {
1379 return Ok(value == 1);
1380 }
1381 }
1382 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
1383}
1384
1385fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +00001386 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
1387 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +09001388
1389 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
1390 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
1391 ("crashkernel", Box::new(|_| has_crashkernel)),
1392 ("console", Box::new(|_| has_console)),
1393 ];
1394
1395 // parse and filter out unwanted
1396 let mut filtered = Vec::new();
1397 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
1398 info!("Invalid bootarg: {e}");
1399 FdtError::BadValue
1400 })? {
1401 match accepted.iter().find(|&t| t.0 == arg.name()) {
1402 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
1403 _ => debug!("Rejected bootarg {}", arg.as_ref()),
1404 }
1405 }
1406
1407 // flatten into a new C-string
1408 let mut new_bootargs = Vec::new();
1409 for (i, arg) in filtered.iter().enumerate() {
1410 if i != 0 {
1411 new_bootargs.push(b' '); // separator
1412 }
1413 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
1414 }
1415 new_bootargs.push(b'\0');
1416
1417 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1418 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1419}