blob: ac52be9c62d7c1da6ec7a64788a126e50708cc5e [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;
Jiyong Parkc23426b2023-04-10 17:32:27 +090024use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090025use core::cmp::max;
26use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000027use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000028use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090029use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000031use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000032use fdtpci::PciMemoryFlags;
33use fdtpci::PciRangeType;
34use libfdt::AddressRange;
35use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000036use libfdt::Fdt;
37use libfdt::FdtError;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Jiyong Park83316122023-03-21 09:39:39 +090039use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000040use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090041use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000042use log::warn;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +000043use static_assertions::const_assert;
Jiyong Park00ceff32023-03-13 05:43:23 +000044use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000045use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000046use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000047use vmbase::memory::SIZE_4KB;
48use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000049use vmbase::util::RangeExt as _;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +000050use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000051
Alice Wangabc7d632023-06-14 09:10:14 +000052/// An enumeration of errors that can occur during the FDT validation.
53#[derive(Clone, Debug)]
54pub enum FdtValidationError {
55 /// Invalid CPU count.
56 InvalidCpuCount(usize),
57}
58
59impl fmt::Display for FdtValidationError {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 match self {
62 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
63 }
64 }
65}
66
Jiyong Park6a8789a2023-03-21 14:50:59 +090067/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
68/// not an error.
69fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090070 let addr = cstr!("kernel-address");
71 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000072
Jiyong Parkb87f3302023-03-21 10:03:11 +090073 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000074 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
75 let addr = addr as usize;
76 let size = size as usize;
77
78 return Ok(Some(addr..(addr + size)));
79 }
80 }
81
82 Ok(None)
83}
84
Jiyong Park6a8789a2023-03-21 14:50:59 +090085/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
86/// error as there can be initrd-less VM.
87fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090088 let start = cstr!("linux,initrd-start");
89 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000090
91 if let Some(chosen) = fdt.chosen()? {
92 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
93 return Ok(Some((start as usize)..(end as usize)));
94 }
95 }
96
97 Ok(None)
98}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000099
Jiyong Park9c63cd12023-03-21 17:53:07 +0900100fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
101 let start = u32::try_from(initrd_range.start).unwrap();
102 let end = u32::try_from(initrd_range.end).unwrap();
103
104 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
105 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
106 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
107 Ok(())
108}
109
Jiyong Parke9d87e82023-03-21 19:28:40 +0900110fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
111 if let Some(chosen) = fdt.chosen()? {
112 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
113 // We need to copy the string to heap because the original fdt will be invalidated
114 // by the templated DT
115 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
116 return Ok(Some(copy));
117 }
118 }
119 Ok(None)
120}
121
122fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
123 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900124 // This function is called before the verification is done. So, we just copy the bootargs to
125 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
126 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900127 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
128}
129
Alice Wang0d527472023-06-13 14:55:38 +0000130/// Reads and validates the memory range in the DT.
131///
132/// Only one memory range is expected with the crosvm setup for now.
133fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
134 let mut memory = fdt.memory().map_err(|e| {
135 error!("Failed to read memory range from DT: {e}");
136 RebootReason::InvalidFdt
137 })?;
138 let range = memory.next().ok_or_else(|| {
139 error!("The /memory node in the DT contains no range.");
140 RebootReason::InvalidFdt
141 })?;
142 if memory.next().is_some() {
143 warn!(
144 "The /memory node in the DT contains more than one memory range, \
145 while only one is expected."
146 );
147 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900148 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000149 if base != MEM_START {
150 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000151 return Err(RebootReason::InvalidFdt);
152 }
153
Jiyong Park6a8789a2023-03-21 14:50:59 +0900154 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000155 if size % GUEST_PAGE_SIZE != 0 {
156 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
157 return Err(RebootReason::InvalidFdt);
158 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000159
Jiyong Park6a8789a2023-03-21 14:50:59 +0900160 if size == 0 {
161 error!("Memory size is 0");
162 return Err(RebootReason::InvalidFdt);
163 }
Alice Wang0d527472023-06-13 14:55:38 +0000164 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000165}
166
Jiyong Park9c63cd12023-03-21 17:53:07 +0900167fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000168 let addr = u64::try_from(MEM_START).unwrap();
169 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900170 fdt.node_mut(cstr!("/memory"))?
171 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000172 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900173}
174
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000175#[derive(Debug, Default)]
176struct CpuInfo {}
Jiyong Park6a8789a2023-03-21 14:50:59 +0900177
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000178fn read_cpu_info_from(fdt: &Fdt) -> libfdt::Result<ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>> {
179 let mut cpus = ArrayVec::new();
180
181 let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?;
182 for _cpu in cpu_nodes.by_ref().take(cpus.capacity()) {
183 let info = CpuInfo {};
184 cpus.push(info);
Jiyong Park6a8789a2023-03-21 14:50:59 +0900185 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000186 if cpu_nodes.next().is_some() {
187 warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity());
188 }
189
190 Ok(cpus)
Jiyong Park9c63cd12023-03-21 17:53:07 +0900191}
192
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000193fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> {
194 if cpus.is_empty() {
195 return Err(FdtValidationError::InvalidCpuCount(0));
196 }
197
198 Ok(())
199}
200
201fn patch_cpus(fdt: &mut Fdt, cpus: &[CpuInfo]) -> libfdt::Result<()> {
202 const COMPAT: &CStr = cstr!("arm,arm-v8");
203 let mut next = fdt.root_mut()?.next_compatible(COMPAT)?;
204 for _cpu in cpus {
205 next = next.ok_or(FdtError::NoSpace)?.next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900206 }
207 while let Some(current) = next {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000208 next = current.delete_and_next_compatible(COMPAT)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900209 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900210 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000211}
212
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900213/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900214fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900215 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900216 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900217 for property in avf_node.properties()? {
218 let name = property.name()?;
219 let value = property.value()?;
220 property_map.insert(
221 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
222 value.to_vec(),
223 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900224 }
225 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900226 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900227}
228
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900229/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
230/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
231fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900232 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900233 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900234 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900235) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900236 let mut root_vm_dt = vm_dt.root_mut()?;
237 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900238 // TODO(b/318431677): Validate nodes beyond /avf.
239 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900240 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900241 if let Some(ref_value) = avf_node.getprop(name)? {
242 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900243 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900244 "Property mismatches while applying overlay VM reference DT. \
245 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
246 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900247 );
248 return Err(FdtError::BadValue);
249 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900250 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900251 }
252 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900253 Ok(())
254}
255
Jiyong Park00ceff32023-03-13 05:43:23 +0000256#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000257struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900258 ranges: [PciAddrRange; 2],
259 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
260 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000261}
262
Jiyong Park6a8789a2023-03-21 14:50:59 +0900263impl PciInfo {
264 const IRQ_MASK_CELLS: usize = 4;
265 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100266 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000267}
268
Jiyong Park6a8789a2023-03-21 14:50:59 +0900269type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
270type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
271type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000272
273/// Iterator that takes N cells as a chunk
274struct CellChunkIterator<'a, const N: usize> {
275 cells: CellIterator<'a>,
276}
277
278impl<'a, const N: usize> CellChunkIterator<'a, N> {
279 fn new(cells: CellIterator<'a>) -> Self {
280 Self { cells }
281 }
282}
283
284impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
285 type Item = [u32; N];
286 fn next(&mut self) -> Option<Self::Item> {
287 let mut ret: Self::Item = [0; N];
288 for i in ret.iter_mut() {
289 *i = self.cells.next()?;
290 }
291 Some(ret)
292 }
293}
294
Jiyong Park6a8789a2023-03-21 14:50:59 +0900295/// Read pci host controller ranges, irq maps, and irq map masks from DT
296fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
297 let node =
298 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
299
300 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
301 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
302 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
303
304 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000305 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
306 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
307
308 if chunks.next().is_some() {
309 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
310 return Err(FdtError::NoSpace);
311 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900312
313 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000314 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
315 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
316
317 if chunks.next().is_some() {
318 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
319 return Err(FdtError::NoSpace);
320 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900321
322 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
323}
324
Jiyong Park0ee65392023-03-27 20:52:45 +0900325fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900326 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900327 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900328 }
329 for irq_mask in pci_info.irq_masks.iter() {
330 validate_pci_irq_mask(irq_mask)?;
331 }
332 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
333 validate_pci_irq_map(irq_map, idx)?;
334 }
335 Ok(())
336}
337
Jiyong Park0ee65392023-03-27 20:52:45 +0900338fn validate_pci_addr_range(
339 range: &PciAddrRange,
340 memory_range: &Range<usize>,
341) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900342 let mem_flags = PciMemoryFlags(range.addr.0);
343 let range_type = mem_flags.range_type();
344 let prefetchable = mem_flags.prefetchable();
345 let bus_addr = range.addr.1;
346 let cpu_addr = range.parent_addr;
347 let size = range.size;
348
349 if range_type != PciRangeType::Memory64 {
350 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
351 return Err(RebootReason::InvalidFdt);
352 }
353 if prefetchable {
354 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
355 return Err(RebootReason::InvalidFdt);
356 }
357 // Enforce ID bus-to-cpu mappings, as used by crosvm.
358 if bus_addr != cpu_addr {
359 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
360 return Err(RebootReason::InvalidFdt);
361 }
362
Jiyong Park0ee65392023-03-27 20:52:45 +0900363 let Some(bus_end) = bus_addr.checked_add(size) else {
364 error!("PCI address range size {:#x} overflows", size);
365 return Err(RebootReason::InvalidFdt);
366 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000367 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900368 error!("PCI address end {:#x} is outside of translatable range", bus_end);
369 return Err(RebootReason::InvalidFdt);
370 }
371
372 let memory_start = memory_range.start.try_into().unwrap();
373 let memory_end = memory_range.end.try_into().unwrap();
374
375 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
376 error!(
377 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
378 bus_addr, bus_end, memory_start, memory_end
379 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900380 return Err(RebootReason::InvalidFdt);
381 }
382
383 Ok(())
384}
385
386fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000387 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
388 const IRQ_MASK_ADDR_ME: u32 = 0x0;
389 const IRQ_MASK_ADDR_LO: u32 = 0x0;
390 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900391 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000392 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900393 if *irq_mask != EXPECTED {
394 error!("Invalid PCI irq mask {:#?}", irq_mask);
395 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000396 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900397 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000398}
399
Jiyong Park6a8789a2023-03-21 14:50:59 +0900400fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000401 const PCI_DEVICE_IDX: usize = 11;
402 const PCI_IRQ_ADDR_ME: u32 = 0;
403 const PCI_IRQ_ADDR_LO: u32 = 0;
404 const PCI_IRQ_INTC: u32 = 1;
405 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
406 const GIC_SPI: u32 = 0;
407 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
408
Jiyong Park6a8789a2023-03-21 14:50:59 +0900409 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
410 let pci_irq_number = irq_map[3];
411 let _controller_phandle = irq_map[4]; // skipped.
412 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
413 // interrupt-cells is <3> for GIC
414 let gic_peripheral_interrupt_type = irq_map[7];
415 let gic_irq_number = irq_map[8];
416 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000417
Jiyong Park6a8789a2023-03-21 14:50:59 +0900418 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
419 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000420
Jiyong Park6a8789a2023-03-21 14:50:59 +0900421 if pci_addr != expected_pci_addr {
422 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
423 {:#x} {:#x} {:#x}",
424 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
425 return Err(RebootReason::InvalidFdt);
426 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000427
Jiyong Park6a8789a2023-03-21 14:50:59 +0900428 if pci_irq_number != PCI_IRQ_INTC {
429 error!(
430 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
431 pci_irq_number, PCI_IRQ_INTC
432 );
433 return Err(RebootReason::InvalidFdt);
434 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000435
Jiyong Park6a8789a2023-03-21 14:50:59 +0900436 if gic_addr != (0, 0) {
437 error!(
438 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
439 {:#x} {:#x}",
440 gic_addr.0, gic_addr.1, 0, 0
441 );
442 return Err(RebootReason::InvalidFdt);
443 }
444
445 if gic_peripheral_interrupt_type != GIC_SPI {
446 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
447 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
448 return Err(RebootReason::InvalidFdt);
449 }
450
451 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
452 if gic_irq_number != irq_nr {
453 error!(
454 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
455 gic_irq_number, irq_nr
456 );
457 return Err(RebootReason::InvalidFdt);
458 }
459
460 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
461 error!(
462 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
463 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
464 );
465 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000466 }
467 Ok(())
468}
469
Jiyong Park9c63cd12023-03-21 17:53:07 +0900470fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
471 let mut node = fdt
472 .root_mut()?
473 .next_compatible(cstr!("pci-host-cam-generic"))?
474 .ok_or(FdtError::NotFound)?;
475
476 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
477 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
478
479 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
480 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
481
482 node.setprop_inplace(
483 cstr!("ranges"),
484 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
485 )
486}
487
Jiyong Park00ceff32023-03-13 05:43:23 +0000488#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900489struct SerialInfo {
490 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000491}
492
493impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900494 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000495}
496
Jiyong Park6a8789a2023-03-21 14:50:59 +0900497fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000498 let mut addrs = ArrayVec::new();
499
500 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
501 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000502 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900503 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000504 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000505 if serial_nodes.next().is_some() {
506 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
507 }
508
Jiyong Park6a8789a2023-03-21 14:50:59 +0900509 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000510}
511
Jiyong Park9c63cd12023-03-21 17:53:07 +0900512/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
513fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
514 let name = cstr!("ns16550a");
515 let mut next = fdt.root_mut()?.next_compatible(name);
516 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000517 let reg =
518 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900519 next = if !serial_info.addrs.contains(&reg.addr) {
520 current.delete_and_next_compatible(name)
521 } else {
522 current.next_compatible(name)
523 }
524 }
525 Ok(())
526}
527
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700528fn validate_swiotlb_info(
529 swiotlb_info: &SwiotlbInfo,
530 memory: &Range<usize>,
531) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900532 let size = swiotlb_info.size;
533 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000534
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700535 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000536 error!("Invalid swiotlb size {:#x}", size);
537 return Err(RebootReason::InvalidFdt);
538 }
539
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000540 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000541 error!("Invalid swiotlb alignment {:#x}", align);
542 return Err(RebootReason::InvalidFdt);
543 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700544
Alice Wang9cfbfd62023-06-14 11:19:03 +0000545 if let Some(addr) = swiotlb_info.addr {
546 if addr.checked_add(size).is_none() {
547 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
548 return Err(RebootReason::InvalidFdt);
549 }
550 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700551 if let Some(range) = swiotlb_info.fixed_range() {
552 if !range.is_within(memory) {
553 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
554 return Err(RebootReason::InvalidFdt);
555 }
556 }
557
Jiyong Park6a8789a2023-03-21 14:50:59 +0900558 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000559}
560
Jiyong Park9c63cd12023-03-21 17:53:07 +0900561fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
562 let mut node =
563 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700564
565 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000566 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700567 cstr!("reg"),
568 range.start.try_into().unwrap(),
569 range.len().try_into().unwrap(),
570 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000571 node.nop_property(cstr!("size"))?;
572 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700573 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000574 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700575 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000576 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700577 }
578
Jiyong Park9c63cd12023-03-21 17:53:07 +0900579 Ok(())
580}
581
582fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
583 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
584 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
585 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
586 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
587
588 let addr = range0.addr;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000589 // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS.
590 const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some());
Alice Wangabc7d632023-06-14 09:10:14 +0000591 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900592
593 // range1 is just below range0
594 range1.addr = addr - size;
595 range1.size = Some(size);
596
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000597 let (addr0, size0) = range0.to_cells();
598 let (addr1, size1) = range1.to_cells();
599 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900600
601 let mut node =
602 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
603 node.setprop_inplace(cstr!("reg"), flatten(&value))
604}
605
606fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
607 const NUM_INTERRUPTS: usize = 4;
608 const CELLS_PER_INTERRUPT: usize = 3;
609 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
610 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
611 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
612 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
613
614 let num_cpus: u32 = num_cpus.try_into().unwrap();
615 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
616 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
617 *v |= cpu_mask;
618 }
619 for v in value.iter_mut() {
620 *v = v.to_be();
621 }
622
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000623 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900624
625 let mut node =
626 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000627 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900628}
629
Jiyong Park00ceff32023-03-13 05:43:23 +0000630#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900631pub struct DeviceTreeInfo {
632 pub kernel_range: Option<Range<usize>>,
633 pub initrd_range: Option<Range<usize>>,
634 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900635 bootargs: Option<CString>,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000636 cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000637 pci_info: PciInfo,
638 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700639 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900640 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900641 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000642}
643
644impl DeviceTreeInfo {
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000645 const MAX_CPUS: usize = 16;
646
647 const fn gic_patched_size(num_cpus: usize) -> Option<usize> {
Alice Wangabc7d632023-06-14 09:10:14 +0000648 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
649
650 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
651 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000652}
653
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900654pub fn sanitize_device_tree(
655 fdt: &mut [u8],
656 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900657 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900658) -> Result<DeviceTreeInfo, RebootReason> {
659 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
660 error!("Failed to load FDT: {e}");
661 RebootReason::InvalidFdt
662 })?;
663
664 let vm_dtbo = match vm_dtbo {
665 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
666 error!("Failed to load VM DTBO: {e}");
667 RebootReason::InvalidFdt
668 })?),
669 None => None,
670 };
671
672 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900673
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000674 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
675 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
676 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900677 error!("Failed to instantiate FDT from the template DT: {e}");
678 RebootReason::InvalidFdt
679 })?;
680
Jaewan Kim9220e852023-12-01 10:58:40 +0900681 fdt.unpack().map_err(|e| {
682 error!("Failed to unpack DT for patching: {e}");
683 RebootReason::InvalidFdt
684 })?;
685
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900686 if let Some(device_assignment_info) = &info.device_assignment {
687 let vm_dtbo = vm_dtbo.unwrap();
688 device_assignment_info.filter(vm_dtbo).map_err(|e| {
689 error!("Failed to filter VM DTBO: {e}");
690 RebootReason::InvalidFdt
691 })?;
692 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
693 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
694 // it can only be instantiated after validation.
695 unsafe {
696 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
697 error!("Failed to apply filtered VM DTBO: {e}");
698 RebootReason::InvalidFdt
699 })?;
700 }
701 }
702
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900703 if let Some(vm_ref_dt) = vm_ref_dt {
704 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
705 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900706 RebootReason::InvalidFdt
707 })?;
708
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900709 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
710 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900711 RebootReason::InvalidFdt
712 })?;
713 }
714
Jiyong Park9c63cd12023-03-21 17:53:07 +0900715 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900716
Jaewan Kim19b984f2023-12-04 15:16:50 +0900717 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
718
Jaewan Kim9220e852023-12-01 10:58:40 +0900719 fdt.pack().map_err(|e| {
720 error!("Failed to unpack DT after patching: {e}");
721 RebootReason::InvalidFdt
722 })?;
723
Jiyong Park6a8789a2023-03-21 14:50:59 +0900724 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900725}
726
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900727fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900728 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
729 error!("Failed to read kernel range from DT: {e}");
730 RebootReason::InvalidFdt
731 })?;
732
733 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
734 error!("Failed to read initrd range from DT: {e}");
735 RebootReason::InvalidFdt
736 })?;
737
Alice Wang0d527472023-06-13 14:55:38 +0000738 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900739
Jiyong Parke9d87e82023-03-21 19:28:40 +0900740 let bootargs = read_bootargs_from(fdt).map_err(|e| {
741 error!("Failed to read bootargs from DT: {e}");
742 RebootReason::InvalidFdt
743 })?;
744
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000745 let cpus = read_cpu_info_from(fdt).map_err(|e| {
746 error!("Failed to read CPU info from DT: {e}");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900747 RebootReason::InvalidFdt
748 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000749 validate_cpu_info(&cpus).map_err(|e| {
750 error!("Failed to validate CPU info from DT: {e}");
Alice Wangabc7d632023-06-14 09:10:14 +0000751 RebootReason::InvalidFdt
752 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753
754 let pci_info = read_pci_info_from(fdt).map_err(|e| {
755 error!("Failed to read pci info from DT: {e}");
756 RebootReason::InvalidFdt
757 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900758 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900759
760 let serial_info = read_serial_info_from(fdt).map_err(|e| {
761 error!("Failed to read serial info from DT: {e}");
762 RebootReason::InvalidFdt
763 })?;
764
Alice Wang9cfbfd62023-06-14 11:19:03 +0000765 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900766 error!("Failed to read swiotlb info from DT: {e}");
767 RebootReason::InvalidFdt
768 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700769 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900770
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900771 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900772 Some(vm_dtbo) => {
773 if let Some(hypervisor) = hyp::get_device_assigner() {
774 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
775 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
776 RebootReason::InvalidFdt
777 })?
778 } else {
779 warn!(
780 "Device assignment is ignored because device assigning hypervisor is missing"
781 );
782 None
783 }
784 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900785 None => None,
786 };
787
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900788 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900789 error!("Failed to read names of properties under /avf from DT: {e}");
790 RebootReason::InvalidFdt
791 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900792
Jiyong Park00ceff32023-03-13 05:43:23 +0000793 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900794 kernel_range,
795 initrd_range,
796 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900797 bootargs,
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000798 cpus,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900799 pci_info,
800 serial_info,
801 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900802 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900803 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000804 })
805}
806
Jiyong Park9c63cd12023-03-21 17:53:07 +0900807fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
808 if let Some(initrd_range) = &info.initrd_range {
809 patch_initrd_range(fdt, initrd_range).map_err(|e| {
810 error!("Failed to patch initrd range to DT: {e}");
811 RebootReason::InvalidFdt
812 })?;
813 }
814 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
815 error!("Failed to patch memory range to DT: {e}");
816 RebootReason::InvalidFdt
817 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900818 if let Some(bootargs) = &info.bootargs {
819 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
820 error!("Failed to patch bootargs to DT: {e}");
821 RebootReason::InvalidFdt
822 })?;
823 }
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000824 patch_cpus(fdt, &info.cpus).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900825 error!("Failed to patch cpus to DT: {e}");
826 RebootReason::InvalidFdt
827 })?;
828 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
829 error!("Failed to patch pci info to DT: {e}");
830 RebootReason::InvalidFdt
831 })?;
832 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
833 error!("Failed to patch serial info to DT: {e}");
834 RebootReason::InvalidFdt
835 })?;
836 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
837 error!("Failed to patch swiotlb info to DT: {e}");
838 RebootReason::InvalidFdt
839 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000840 patch_gic(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900841 error!("Failed to patch gic info to DT: {e}");
842 RebootReason::InvalidFdt
843 })?;
Pierre-Clément Tosi689e4732024-02-05 14:39:51 +0000844 patch_timer(fdt, info.cpus.len()).map_err(|e| {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900845 error!("Failed to patch timer info to DT: {e}");
846 RebootReason::InvalidFdt
847 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900848 if let Some(device_assignment) = &info.device_assignment {
849 // Note: We patch values after VM DTBO is overlaid because patch may require more space
850 // then VM DTBO's underlying slice is allocated.
851 device_assignment.patch(fdt).map_err(|e| {
852 error!("Failed to patch device assignment info to DT: {e}");
853 RebootReason::InvalidFdt
854 })?;
855 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900856
Jiyong Park9c63cd12023-03-21 17:53:07 +0900857 Ok(())
858}
859
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000860/// Modifies the input DT according to the fields of the configuration.
861pub fn modify_for_next_stage(
862 fdt: &mut Fdt,
863 bcc: &[u8],
864 new_instance: bool,
865 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000866 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900867 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000868 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000869) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000870 if let Some(debug_policy) = debug_policy {
871 let backup = Vec::from(fdt.as_slice());
872 fdt.unpack()?;
873 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
874 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
875 info!("Debug policy applied.");
876 } else {
877 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
878 fdt.unpack()?;
879 }
880 } else {
881 info!("No debug policy found.");
882 fdt.unpack()?;
883 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000884
Jiyong Parke9d87e82023-03-21 19:28:40 +0900885 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000886
Alice Wang56ec45b2023-06-15 08:30:32 +0000887 if let Some(mut chosen) = fdt.chosen_mut()? {
888 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
889 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000890 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000891 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900892 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900893 if let Some(bootargs) = read_bootargs_from(fdt)? {
894 filter_out_dangerous_bootargs(fdt, &bootargs)?;
895 }
896 }
897
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000898 fdt.pack()?;
899
900 Ok(())
901}
902
Jiyong Parke9d87e82023-03-21 19:28:40 +0900903/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
904fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000905 // We reject DTs with missing reserved-memory node as validation should have checked that the
906 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900907 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000908
Jiyong Parke9d87e82023-03-21 19:28:40 +0900909 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000910
Jiyong Parke9d87e82023-03-21 19:28:40 +0900911 let addr: u64 = addr.try_into().unwrap();
912 let size: u64 = size.try_into().unwrap();
913 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000914}
915
Alice Wang56ec45b2023-06-15 08:30:32 +0000916fn empty_or_delete_prop(
917 fdt_node: &mut FdtNodeMut,
918 prop_name: &CStr,
919 keep_prop: bool,
920) -> libfdt::Result<()> {
921 if keep_prop {
922 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000923 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000924 fdt_node
925 .delprop(prop_name)
926 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000927 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000928}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900929
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000930/// Apply the debug policy overlay to the guest DT.
931///
932/// 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 +0000933fn apply_debug_policy(
934 fdt: &mut Fdt,
935 backup_fdt: &Fdt,
936 debug_policy: &[u8],
937) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000938 let mut debug_policy = Vec::from(debug_policy);
939 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900940 Ok(overlay) => overlay,
941 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000942 warn!("Corrupted debug policy found: {e}. Not applying.");
943 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900944 }
945 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900946
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100947 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900948 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000949 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000950 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900951 // A successful restoration is considered success because an invalid debug policy
952 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000953 Ok(false)
954 } else {
955 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900956 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900957}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900958
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000959fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900960 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
961 if let Some(value) = node.getprop_u32(debug_feature_name)? {
962 return Ok(value == 1);
963 }
964 }
965 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
966}
967
968fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000969 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
970 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900971
972 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
973 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
974 ("crashkernel", Box::new(|_| has_crashkernel)),
975 ("console", Box::new(|_| has_console)),
976 ];
977
978 // parse and filter out unwanted
979 let mut filtered = Vec::new();
980 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
981 info!("Invalid bootarg: {e}");
982 FdtError::BadValue
983 })? {
984 match accepted.iter().find(|&t| t.0 == arg.name()) {
985 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
986 _ => debug!("Rejected bootarg {}", arg.as_ref()),
987 }
988 }
989
990 // flatten into a new C-string
991 let mut new_bootargs = Vec::new();
992 for (i, arg) in filtered.iter().enumerate() {
993 if i != 0 {
994 new_bootargs.push(b' '); // separator
995 }
996 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
997 }
998 new_bootargs.push(b'\0');
999
1000 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
1001 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
1002}