blob: 4fe2c34bf4ed31af18c5671a8b4309973920f3a2 [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 Kimc6e023b2023-10-12 15:11:05 +090018use crate::device_assignment::DeviceAssignmentInfo;
19use crate::device_assignment::VmDtbo;
Jiyong Park00ceff32023-03-13 05:43:23 +000020use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090021use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000022use crate::RebootReason;
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;
Jiyong Park9c63cd12023-03-21 17:53:07 +090038use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000039use libfdt::FdtNodeMut;
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;
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 Tosia0934c12022-11-25 20:54:11 +000050
Alice Wangabc7d632023-06-14 09:10:14 +000051/// An enumeration of errors that can occur during the FDT validation.
52#[derive(Clone, Debug)]
53pub enum FdtValidationError {
54 /// Invalid CPU count.
55 InvalidCpuCount(usize),
56}
57
58impl fmt::Display for FdtValidationError {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 match self {
61 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
62 }
63 }
64}
65
Jiyong Park6a8789a2023-03-21 14:50:59 +090066/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
67/// not an error.
68fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090069 let addr = cstr!("kernel-address");
70 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000071
Jiyong Parkb87f3302023-03-21 10:03:11 +090072 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000073 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
74 let addr = addr as usize;
75 let size = size as usize;
76
77 return Ok(Some(addr..(addr + size)));
78 }
79 }
80
81 Ok(None)
82}
83
Jiyong Park6a8789a2023-03-21 14:50:59 +090084/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
85/// error as there can be initrd-less VM.
86fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090087 let start = cstr!("linux,initrd-start");
88 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000089
90 if let Some(chosen) = fdt.chosen()? {
91 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
92 return Ok(Some((start as usize)..(end as usize)));
93 }
94 }
95
96 Ok(None)
97}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000098
Jiyong Park9c63cd12023-03-21 17:53:07 +090099fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
100 let start = u32::try_from(initrd_range.start).unwrap();
101 let end = u32::try_from(initrd_range.end).unwrap();
102
103 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
104 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
105 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
106 Ok(())
107}
108
Jiyong Parke9d87e82023-03-21 19:28:40 +0900109fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
110 if let Some(chosen) = fdt.chosen()? {
111 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
112 // We need to copy the string to heap because the original fdt will be invalidated
113 // by the templated DT
114 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
115 return Ok(Some(copy));
116 }
117 }
118 Ok(None)
119}
120
121fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
122 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900123 // This function is called before the verification is done. So, we just copy the bootargs to
124 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
125 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900126 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
127}
128
Alice Wang0d527472023-06-13 14:55:38 +0000129/// Reads and validates the memory range in the DT.
130///
131/// Only one memory range is expected with the crosvm setup for now.
132fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
133 let mut memory = fdt.memory().map_err(|e| {
134 error!("Failed to read memory range from DT: {e}");
135 RebootReason::InvalidFdt
136 })?;
137 let range = memory.next().ok_or_else(|| {
138 error!("The /memory node in the DT contains no range.");
139 RebootReason::InvalidFdt
140 })?;
141 if memory.next().is_some() {
142 warn!(
143 "The /memory node in the DT contains more than one memory range, \
144 while only one is expected."
145 );
146 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900147 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000148 if base != MEM_START {
149 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000150 return Err(RebootReason::InvalidFdt);
151 }
152
Jiyong Park6a8789a2023-03-21 14:50:59 +0900153 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000154 if size % GUEST_PAGE_SIZE != 0 {
155 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
156 return Err(RebootReason::InvalidFdt);
157 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000158
Jiyong Park6a8789a2023-03-21 14:50:59 +0900159 if size == 0 {
160 error!("Memory size is 0");
161 return Err(RebootReason::InvalidFdt);
162 }
Alice Wang0d527472023-06-13 14:55:38 +0000163 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000164}
165
Jiyong Park9c63cd12023-03-21 17:53:07 +0900166fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
167 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900168 fdt.node_mut(cstr!("/memory"))?
169 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000170 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900171}
172
Jiyong Park6a8789a2023-03-21 14:50:59 +0900173/// Read the number of CPUs from DT
174fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
175 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
176}
177
178/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000179fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
180 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
181 Err(FdtValidationError::InvalidCpuCount(num_cpus))
182 } else {
183 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900184 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900185}
186
187/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
188fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
189 let cpu = cstr!("arm,arm-v8");
190 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
191 for _ in 0..num_cpus {
192 next = if let Some(current) = next {
193 current.next_compatible(cpu)?
194 } else {
195 return Err(FdtError::NoSpace);
196 };
197 }
198 while let Some(current) = next {
199 next = current.delete_and_next_compatible(cpu)?;
200 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900201 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000202}
203
204#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000205struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900206 ranges: [PciAddrRange; 2],
207 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
208 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000209}
210
Jiyong Park6a8789a2023-03-21 14:50:59 +0900211impl PciInfo {
212 const IRQ_MASK_CELLS: usize = 4;
213 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100214 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000215}
216
Jiyong Park6a8789a2023-03-21 14:50:59 +0900217type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
218type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
219type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000220
221/// Iterator that takes N cells as a chunk
222struct CellChunkIterator<'a, const N: usize> {
223 cells: CellIterator<'a>,
224}
225
226impl<'a, const N: usize> CellChunkIterator<'a, N> {
227 fn new(cells: CellIterator<'a>) -> Self {
228 Self { cells }
229 }
230}
231
232impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
233 type Item = [u32; N];
234 fn next(&mut self) -> Option<Self::Item> {
235 let mut ret: Self::Item = [0; N];
236 for i in ret.iter_mut() {
237 *i = self.cells.next()?;
238 }
239 Some(ret)
240 }
241}
242
Jiyong Park6a8789a2023-03-21 14:50:59 +0900243/// Read pci host controller ranges, irq maps, and irq map masks from DT
244fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
245 let node =
246 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
247
248 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
249 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
250 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
251
252 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000253 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
254 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
255
256 if chunks.next().is_some() {
257 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
258 return Err(FdtError::NoSpace);
259 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900260
261 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000262 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
263 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
264
265 if chunks.next().is_some() {
266 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
267 return Err(FdtError::NoSpace);
268 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900269
270 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
271}
272
Jiyong Park0ee65392023-03-27 20:52:45 +0900273fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900274 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900275 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900276 }
277 for irq_mask in pci_info.irq_masks.iter() {
278 validate_pci_irq_mask(irq_mask)?;
279 }
280 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
281 validate_pci_irq_map(irq_map, idx)?;
282 }
283 Ok(())
284}
285
Jiyong Park0ee65392023-03-27 20:52:45 +0900286fn validate_pci_addr_range(
287 range: &PciAddrRange,
288 memory_range: &Range<usize>,
289) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900290 let mem_flags = PciMemoryFlags(range.addr.0);
291 let range_type = mem_flags.range_type();
292 let prefetchable = mem_flags.prefetchable();
293 let bus_addr = range.addr.1;
294 let cpu_addr = range.parent_addr;
295 let size = range.size;
296
297 if range_type != PciRangeType::Memory64 {
298 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
299 return Err(RebootReason::InvalidFdt);
300 }
301 if prefetchable {
302 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
303 return Err(RebootReason::InvalidFdt);
304 }
305 // Enforce ID bus-to-cpu mappings, as used by crosvm.
306 if bus_addr != cpu_addr {
307 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
308 return Err(RebootReason::InvalidFdt);
309 }
310
Jiyong Park0ee65392023-03-27 20:52:45 +0900311 let Some(bus_end) = bus_addr.checked_add(size) else {
312 error!("PCI address range size {:#x} overflows", size);
313 return Err(RebootReason::InvalidFdt);
314 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000315 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900316 error!("PCI address end {:#x} is outside of translatable range", bus_end);
317 return Err(RebootReason::InvalidFdt);
318 }
319
320 let memory_start = memory_range.start.try_into().unwrap();
321 let memory_end = memory_range.end.try_into().unwrap();
322
323 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
324 error!(
325 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
326 bus_addr, bus_end, memory_start, memory_end
327 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900328 return Err(RebootReason::InvalidFdt);
329 }
330
331 Ok(())
332}
333
334fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000335 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
336 const IRQ_MASK_ADDR_ME: u32 = 0x0;
337 const IRQ_MASK_ADDR_LO: u32 = 0x0;
338 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900339 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000340 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900341 if *irq_mask != EXPECTED {
342 error!("Invalid PCI irq mask {:#?}", irq_mask);
343 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000344 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900345 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000346}
347
Jiyong Park6a8789a2023-03-21 14:50:59 +0900348fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000349 const PCI_DEVICE_IDX: usize = 11;
350 const PCI_IRQ_ADDR_ME: u32 = 0;
351 const PCI_IRQ_ADDR_LO: u32 = 0;
352 const PCI_IRQ_INTC: u32 = 1;
353 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
354 const GIC_SPI: u32 = 0;
355 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
356
Jiyong Park6a8789a2023-03-21 14:50:59 +0900357 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
358 let pci_irq_number = irq_map[3];
359 let _controller_phandle = irq_map[4]; // skipped.
360 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
361 // interrupt-cells is <3> for GIC
362 let gic_peripheral_interrupt_type = irq_map[7];
363 let gic_irq_number = irq_map[8];
364 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000365
Jiyong Park6a8789a2023-03-21 14:50:59 +0900366 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
367 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000368
Jiyong Park6a8789a2023-03-21 14:50:59 +0900369 if pci_addr != expected_pci_addr {
370 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
371 {:#x} {:#x} {:#x}",
372 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
373 return Err(RebootReason::InvalidFdt);
374 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000375
Jiyong Park6a8789a2023-03-21 14:50:59 +0900376 if pci_irq_number != PCI_IRQ_INTC {
377 error!(
378 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
379 pci_irq_number, PCI_IRQ_INTC
380 );
381 return Err(RebootReason::InvalidFdt);
382 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000383
Jiyong Park6a8789a2023-03-21 14:50:59 +0900384 if gic_addr != (0, 0) {
385 error!(
386 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
387 {:#x} {:#x}",
388 gic_addr.0, gic_addr.1, 0, 0
389 );
390 return Err(RebootReason::InvalidFdt);
391 }
392
393 if gic_peripheral_interrupt_type != GIC_SPI {
394 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
395 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
396 return Err(RebootReason::InvalidFdt);
397 }
398
399 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
400 if gic_irq_number != irq_nr {
401 error!(
402 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
403 gic_irq_number, irq_nr
404 );
405 return Err(RebootReason::InvalidFdt);
406 }
407
408 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
409 error!(
410 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
411 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
412 );
413 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000414 }
415 Ok(())
416}
417
Jiyong Park9c63cd12023-03-21 17:53:07 +0900418fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
419 let mut node = fdt
420 .root_mut()?
421 .next_compatible(cstr!("pci-host-cam-generic"))?
422 .ok_or(FdtError::NotFound)?;
423
424 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
425 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
426
427 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
428 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
429
430 node.setprop_inplace(
431 cstr!("ranges"),
432 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
433 )
434}
435
Jiyong Park00ceff32023-03-13 05:43:23 +0000436#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900437struct SerialInfo {
438 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000439}
440
441impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900442 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000443}
444
Jiyong Park6a8789a2023-03-21 14:50:59 +0900445fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
446 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
447 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000448 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900449 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000450 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900451 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000452}
453
Jiyong Park9c63cd12023-03-21 17:53:07 +0900454/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
455fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
456 let name = cstr!("ns16550a");
457 let mut next = fdt.root_mut()?.next_compatible(name);
458 while let Some(current) = next? {
459 let reg = FdtNode::from_mut(&current)
460 .reg()?
461 .ok_or(FdtError::NotFound)?
462 .next()
463 .ok_or(FdtError::NotFound)?;
464 next = if !serial_info.addrs.contains(&reg.addr) {
465 current.delete_and_next_compatible(name)
466 } else {
467 current.next_compatible(name)
468 }
469 }
470 Ok(())
471}
472
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700473fn validate_swiotlb_info(
474 swiotlb_info: &SwiotlbInfo,
475 memory: &Range<usize>,
476) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900477 let size = swiotlb_info.size;
478 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000479
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700480 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000481 error!("Invalid swiotlb size {:#x}", size);
482 return Err(RebootReason::InvalidFdt);
483 }
484
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000485 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000486 error!("Invalid swiotlb alignment {:#x}", align);
487 return Err(RebootReason::InvalidFdt);
488 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700489
Alice Wang9cfbfd62023-06-14 11:19:03 +0000490 if let Some(addr) = swiotlb_info.addr {
491 if addr.checked_add(size).is_none() {
492 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
493 return Err(RebootReason::InvalidFdt);
494 }
495 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700496 if let Some(range) = swiotlb_info.fixed_range() {
497 if !range.is_within(memory) {
498 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
499 return Err(RebootReason::InvalidFdt);
500 }
501 }
502
Jiyong Park6a8789a2023-03-21 14:50:59 +0900503 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000504}
505
Jiyong Park9c63cd12023-03-21 17:53:07 +0900506fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
507 let mut node =
508 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700509
510 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000511 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700512 cstr!("reg"),
513 range.start.try_into().unwrap(),
514 range.len().try_into().unwrap(),
515 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000516 node.nop_property(cstr!("size"))?;
517 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700518 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000519 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700520 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000521 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700522 }
523
Jiyong Park9c63cd12023-03-21 17:53:07 +0900524 Ok(())
525}
526
527fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
528 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
529 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
530 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
531 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
532
533 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000534 // `validate_num_cpus()` checked that this wouldn't panic
535 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900536
537 // range1 is just below range0
538 range1.addr = addr - size;
539 range1.size = Some(size);
540
541 let range0 = range0.to_cells();
542 let range1 = range1.to_cells();
543 let value = [
544 range0.0, // addr
545 range0.1.unwrap(), //size
546 range1.0, // addr
547 range1.1.unwrap(), //size
548 ];
549
550 let mut node =
551 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
552 node.setprop_inplace(cstr!("reg"), flatten(&value))
553}
554
555fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
556 const NUM_INTERRUPTS: usize = 4;
557 const CELLS_PER_INTERRUPT: usize = 3;
558 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
559 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
560 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
561 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
562
563 let num_cpus: u32 = num_cpus.try_into().unwrap();
564 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
565 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
566 *v |= cpu_mask;
567 }
568 for v in value.iter_mut() {
569 *v = v.to_be();
570 }
571
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100572 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900573 let value = unsafe {
574 core::mem::transmute::<
575 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
576 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
577 >(value.into_inner())
578 };
579
580 let mut node =
581 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
582 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
583}
584
Jiyong Park00ceff32023-03-13 05:43:23 +0000585#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900586pub struct DeviceTreeInfo {
587 pub kernel_range: Option<Range<usize>>,
588 pub initrd_range: Option<Range<usize>>,
589 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900590 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900591 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000592 pci_info: PciInfo,
593 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700594 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900595 device_assignment: Option<DeviceAssignmentInfo>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000596}
597
598impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000599 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
600 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
601
602 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
603 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000604}
605
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900606pub fn sanitize_device_tree(
607 fdt: &mut [u8],
608 vm_dtbo: Option<&mut [u8]>,
609) -> Result<DeviceTreeInfo, RebootReason> {
610 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
611 error!("Failed to load FDT: {e}");
612 RebootReason::InvalidFdt
613 })?;
614
615 let vm_dtbo = match vm_dtbo {
616 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
617 error!("Failed to load VM DTBO: {e}");
618 RebootReason::InvalidFdt
619 })?),
620 None => None,
621 };
622
623 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900624
Jiyong Parke9d87e82023-03-21 19:28:40 +0900625 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
626 error!("Failed to instantiate FDT from the template DT: {e}");
627 RebootReason::InvalidFdt
628 })?;
629
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900630 if let Some(device_assignment_info) = &info.device_assignment {
631 let vm_dtbo = vm_dtbo.unwrap();
632 device_assignment_info.filter(vm_dtbo).map_err(|e| {
633 error!("Failed to filter VM DTBO: {e}");
634 RebootReason::InvalidFdt
635 })?;
636 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
637 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
638 // it can only be instantiated after validation.
639 unsafe {
640 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
641 error!("Failed to apply filtered VM DTBO: {e}");
642 RebootReason::InvalidFdt
643 })?;
644 }
645 }
646
Jiyong Park9c63cd12023-03-21 17:53:07 +0900647 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900648
Jiyong Park6a8789a2023-03-21 14:50:59 +0900649 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900650}
651
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900652fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900653 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
654 error!("Failed to read kernel range from DT: {e}");
655 RebootReason::InvalidFdt
656 })?;
657
658 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
659 error!("Failed to read initrd range from DT: {e}");
660 RebootReason::InvalidFdt
661 })?;
662
Alice Wang0d527472023-06-13 14:55:38 +0000663 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900664
Jiyong Parke9d87e82023-03-21 19:28:40 +0900665 let bootargs = read_bootargs_from(fdt).map_err(|e| {
666 error!("Failed to read bootargs from DT: {e}");
667 RebootReason::InvalidFdt
668 })?;
669
Jiyong Park6a8789a2023-03-21 14:50:59 +0900670 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
671 error!("Failed to read num cpus from DT: {e}");
672 RebootReason::InvalidFdt
673 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000674 validate_num_cpus(num_cpus).map_err(|e| {
675 error!("Failed to validate num cpus from DT: {e}");
676 RebootReason::InvalidFdt
677 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900678
679 let pci_info = read_pci_info_from(fdt).map_err(|e| {
680 error!("Failed to read pci info from DT: {e}");
681 RebootReason::InvalidFdt
682 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900683 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900684
685 let serial_info = read_serial_info_from(fdt).map_err(|e| {
686 error!("Failed to read serial info from DT: {e}");
687 RebootReason::InvalidFdt
688 })?;
689
Alice Wang9cfbfd62023-06-14 11:19:03 +0000690 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900691 error!("Failed to read swiotlb info from DT: {e}");
692 RebootReason::InvalidFdt
693 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700694 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900695
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900696 let device_assignment = match vm_dtbo {
697 Some(vm_dtbo) => DeviceAssignmentInfo::parse(fdt, vm_dtbo).map_err(|e| {
698 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
699 RebootReason::InvalidFdt
700 })?,
701 None => None,
702 };
703
Jiyong Park00ceff32023-03-13 05:43:23 +0000704 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900705 kernel_range,
706 initrd_range,
707 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900708 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900709 num_cpus,
710 pci_info,
711 serial_info,
712 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900713 device_assignment,
Jiyong Park00ceff32023-03-13 05:43:23 +0000714 })
715}
716
Jiyong Park9c63cd12023-03-21 17:53:07 +0900717fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900718 fdt.unpack().map_err(|e| {
719 error!("Failed to unpack DT for patching: {e}");
720 RebootReason::InvalidFdt
721 })?;
722
Jiyong Park9c63cd12023-03-21 17:53:07 +0900723 if let Some(initrd_range) = &info.initrd_range {
724 patch_initrd_range(fdt, initrd_range).map_err(|e| {
725 error!("Failed to patch initrd range to DT: {e}");
726 RebootReason::InvalidFdt
727 })?;
728 }
729 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
730 error!("Failed to patch memory range to DT: {e}");
731 RebootReason::InvalidFdt
732 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900733 if let Some(bootargs) = &info.bootargs {
734 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
735 error!("Failed to patch bootargs to DT: {e}");
736 RebootReason::InvalidFdt
737 })?;
738 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900739 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
740 error!("Failed to patch cpus to DT: {e}");
741 RebootReason::InvalidFdt
742 })?;
743 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
744 error!("Failed to patch pci info to DT: {e}");
745 RebootReason::InvalidFdt
746 })?;
747 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
748 error!("Failed to patch serial info to DT: {e}");
749 RebootReason::InvalidFdt
750 })?;
751 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
752 error!("Failed to patch swiotlb info to DT: {e}");
753 RebootReason::InvalidFdt
754 })?;
755 patch_gic(fdt, info.num_cpus).map_err(|e| {
756 error!("Failed to patch gic info to DT: {e}");
757 RebootReason::InvalidFdt
758 })?;
759 patch_timer(fdt, info.num_cpus).map_err(|e| {
760 error!("Failed to patch timer info to DT: {e}");
761 RebootReason::InvalidFdt
762 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900763 if let Some(device_assignment) = &info.device_assignment {
764 // Note: We patch values after VM DTBO is overlaid because patch may require more space
765 // then VM DTBO's underlying slice is allocated.
766 device_assignment.patch(fdt).map_err(|e| {
767 error!("Failed to patch device assignment info to DT: {e}");
768 RebootReason::InvalidFdt
769 })?;
770 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900771
772 fdt.pack().map_err(|e| {
773 error!("Failed to pack DT after patching: {e}");
774 RebootReason::InvalidFdt
775 })?;
776
Jiyong Park9c63cd12023-03-21 17:53:07 +0900777 Ok(())
778}
779
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000780/// Modifies the input DT according to the fields of the configuration.
781pub fn modify_for_next_stage(
782 fdt: &mut Fdt,
783 bcc: &[u8],
784 new_instance: bool,
785 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900786 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900787 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000788 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000789) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000790 if let Some(debug_policy) = debug_policy {
791 let backup = Vec::from(fdt.as_slice());
792 fdt.unpack()?;
793 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
794 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
795 info!("Debug policy applied.");
796 } else {
797 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
798 fdt.unpack()?;
799 }
800 } else {
801 info!("No debug policy found.");
802 fdt.unpack()?;
803 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000804
Jiyong Parke9d87e82023-03-21 19:28:40 +0900805 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000806
Alice Wang56ec45b2023-06-15 08:30:32 +0000807 if let Some(mut chosen) = fdt.chosen_mut()? {
808 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
809 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000810 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000811 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900812 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900813 if let Some(bootargs) = read_bootargs_from(fdt)? {
814 filter_out_dangerous_bootargs(fdt, &bootargs)?;
815 }
816 }
817
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000818 fdt.pack()?;
819
820 Ok(())
821}
822
Jiyong Parke9d87e82023-03-21 19:28:40 +0900823/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
824fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000825 // We reject DTs with missing reserved-memory node as validation should have checked that the
826 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900827 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000828
Jiyong Parke9d87e82023-03-21 19:28:40 +0900829 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000830
Jiyong Parke9d87e82023-03-21 19:28:40 +0900831 let addr: u64 = addr.try_into().unwrap();
832 let size: u64 = size.try_into().unwrap();
833 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000834}
835
Alice Wang56ec45b2023-06-15 08:30:32 +0000836fn empty_or_delete_prop(
837 fdt_node: &mut FdtNodeMut,
838 prop_name: &CStr,
839 keep_prop: bool,
840) -> libfdt::Result<()> {
841 if keep_prop {
842 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000843 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000844 fdt_node
845 .delprop(prop_name)
846 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000847 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000848}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900849
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000850/// Apply the debug policy overlay to the guest DT.
851///
852/// 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 +0000853fn apply_debug_policy(
854 fdt: &mut Fdt,
855 backup_fdt: &Fdt,
856 debug_policy: &[u8],
857) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000858 let mut debug_policy = Vec::from(debug_policy);
859 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900860 Ok(overlay) => overlay,
861 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000862 warn!("Corrupted debug policy found: {e}. Not applying.");
863 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900864 }
865 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900866
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100867 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900868 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000869 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900870 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900871 // A successful restoration is considered success because an invalid debug policy
872 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000873 Ok(false)
874 } else {
875 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900876 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900877}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900878
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000879fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900880 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
881 if let Some(value) = node.getprop_u32(debug_feature_name)? {
882 return Ok(value == 1);
883 }
884 }
885 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
886}
887
888fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000889 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
890 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900891
892 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
893 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
894 ("crashkernel", Box::new(|_| has_crashkernel)),
895 ("console", Box::new(|_| has_console)),
896 ];
897
898 // parse and filter out unwanted
899 let mut filtered = Vec::new();
900 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
901 info!("Invalid bootarg: {e}");
902 FdtError::BadValue
903 })? {
904 match accepted.iter().find(|&t| t.0 == arg.name()) {
905 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
906 _ => debug!("Rejected bootarg {}", arg.as_ref()),
907 }
908 }
909
910 // flatten into a new C-string
911 let mut new_bootargs = Vec::new();
912 for (i, arg) in filtered.iter().enumerate() {
913 if i != 0 {
914 new_bootargs.push(b' '); // separator
915 }
916 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
917 }
918 new_bootargs.push(b'\0');
919
920 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
921 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
922}