blob: 244b192f6fa8a91eb821df1d69487dbaea773052 [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;
Jiyong Park00ceff32023-03-13 05:43:23 +000018use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090019use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000020use crate::RebootReason;
Jiyong Parke9d87e82023-03-21 19:28:40 +090021use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090022use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090023use core::cmp::max;
24use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000025use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000026use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090027use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::ops::Range;
Jiyong Park00ceff32023-03-13 05:43:23 +000029use fdtpci::PciMemoryFlags;
30use fdtpci::PciRangeType;
31use libfdt::AddressRange;
32use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000033use libfdt::Fdt;
34use libfdt::FdtError;
Jiyong Park9c63cd12023-03-21 17:53:07 +090035use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000036use libfdt::FdtNodeMut;
Jiyong Park83316122023-03-21 09:39:39 +090037use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000038use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090039use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000040use log::warn;
Jiyong Park00ceff32023-03-13 05:43:23 +000041use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000042use vmbase::cstr;
43use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000044use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000045use vmbase::memory::SIZE_4KB;
46use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000047use vmbase::util::RangeExt as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000048
Alice Wangabc7d632023-06-14 09:10:14 +000049/// An enumeration of errors that can occur during the FDT validation.
50#[derive(Clone, Debug)]
51pub enum FdtValidationError {
52 /// Invalid CPU count.
53 InvalidCpuCount(usize),
54}
55
56impl fmt::Display for FdtValidationError {
57 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58 match self {
59 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
60 }
61 }
62}
63
Jiyong Park6a8789a2023-03-21 14:50:59 +090064/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
65/// not an error.
66fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090067 let addr = cstr!("kernel-address");
68 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000069
Jiyong Parkb87f3302023-03-21 10:03:11 +090070 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000071 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
72 let addr = addr as usize;
73 let size = size as usize;
74
75 return Ok(Some(addr..(addr + size)));
76 }
77 }
78
79 Ok(None)
80}
81
Jiyong Park6a8789a2023-03-21 14:50:59 +090082/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
83/// error as there can be initrd-less VM.
84fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090085 let start = cstr!("linux,initrd-start");
86 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000087
88 if let Some(chosen) = fdt.chosen()? {
89 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
90 return Ok(Some((start as usize)..(end as usize)));
91 }
92 }
93
94 Ok(None)
95}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000096
Jiyong Park9c63cd12023-03-21 17:53:07 +090097fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
98 let start = u32::try_from(initrd_range.start).unwrap();
99 let end = u32::try_from(initrd_range.end).unwrap();
100
101 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
102 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
103 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
104 Ok(())
105}
106
Jiyong Parke9d87e82023-03-21 19:28:40 +0900107fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
108 if let Some(chosen) = fdt.chosen()? {
109 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
110 // We need to copy the string to heap because the original fdt will be invalidated
111 // by the templated DT
112 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
113 return Ok(Some(copy));
114 }
115 }
116 Ok(None)
117}
118
119fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
120 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900121 // This function is called before the verification is done. So, we just copy the bootargs to
122 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
123 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900124 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
125}
126
Alice Wang0d527472023-06-13 14:55:38 +0000127/// Reads and validates the memory range in the DT.
128///
129/// Only one memory range is expected with the crosvm setup for now.
130fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
131 let mut memory = fdt.memory().map_err(|e| {
132 error!("Failed to read memory range from DT: {e}");
133 RebootReason::InvalidFdt
134 })?;
135 let range = memory.next().ok_or_else(|| {
136 error!("The /memory node in the DT contains no range.");
137 RebootReason::InvalidFdt
138 })?;
139 if memory.next().is_some() {
140 warn!(
141 "The /memory node in the DT contains more than one memory range, \
142 while only one is expected."
143 );
144 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900145 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000146 if base != MEM_START {
147 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000148 return Err(RebootReason::InvalidFdt);
149 }
150
Jiyong Park6a8789a2023-03-21 14:50:59 +0900151 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000152 if size % GUEST_PAGE_SIZE != 0 {
153 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
154 return Err(RebootReason::InvalidFdt);
155 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000156
Jiyong Park6a8789a2023-03-21 14:50:59 +0900157 if size == 0 {
158 error!("Memory size is 0");
159 return Err(RebootReason::InvalidFdt);
160 }
Alice Wang0d527472023-06-13 14:55:38 +0000161 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000162}
163
Jiyong Park9c63cd12023-03-21 17:53:07 +0900164fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
165 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900166 fdt.node_mut(cstr!("/memory"))?
167 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000168 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900169}
170
Jiyong Park6a8789a2023-03-21 14:50:59 +0900171/// Read the number of CPUs from DT
172fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
173 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
174}
175
176/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000177fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
178 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
179 Err(FdtValidationError::InvalidCpuCount(num_cpus))
180 } else {
181 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900182 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900183}
184
185/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
186fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
187 let cpu = cstr!("arm,arm-v8");
188 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
189 for _ in 0..num_cpus {
190 next = if let Some(current) = next {
191 current.next_compatible(cpu)?
192 } else {
193 return Err(FdtError::NoSpace);
194 };
195 }
196 while let Some(current) = next {
197 next = current.delete_and_next_compatible(cpu)?;
198 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900199 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000200}
201
202#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000203struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900204 ranges: [PciAddrRange; 2],
205 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
206 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000207}
208
Jiyong Park6a8789a2023-03-21 14:50:59 +0900209impl PciInfo {
210 const IRQ_MASK_CELLS: usize = 4;
211 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100212 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000213}
214
Jiyong Park6a8789a2023-03-21 14:50:59 +0900215type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
216type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
217type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000218
219/// Iterator that takes N cells as a chunk
220struct CellChunkIterator<'a, const N: usize> {
221 cells: CellIterator<'a>,
222}
223
224impl<'a, const N: usize> CellChunkIterator<'a, N> {
225 fn new(cells: CellIterator<'a>) -> Self {
226 Self { cells }
227 }
228}
229
230impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
231 type Item = [u32; N];
232 fn next(&mut self) -> Option<Self::Item> {
233 let mut ret: Self::Item = [0; N];
234 for i in ret.iter_mut() {
235 *i = self.cells.next()?;
236 }
237 Some(ret)
238 }
239}
240
Jiyong Park6a8789a2023-03-21 14:50:59 +0900241/// Read pci host controller ranges, irq maps, and irq map masks from DT
242fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
243 let node =
244 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
245
246 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
247 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
248 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
249
250 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000251 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
252 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
253
254 if chunks.next().is_some() {
255 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
256 return Err(FdtError::NoSpace);
257 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900258
259 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000260 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
261 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
262
263 if chunks.next().is_some() {
264 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
265 return Err(FdtError::NoSpace);
266 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900267
268 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
269}
270
Jiyong Park0ee65392023-03-27 20:52:45 +0900271fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900272 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900273 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900274 }
275 for irq_mask in pci_info.irq_masks.iter() {
276 validate_pci_irq_mask(irq_mask)?;
277 }
278 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
279 validate_pci_irq_map(irq_map, idx)?;
280 }
281 Ok(())
282}
283
Jiyong Park0ee65392023-03-27 20:52:45 +0900284fn validate_pci_addr_range(
285 range: &PciAddrRange,
286 memory_range: &Range<usize>,
287) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900288 let mem_flags = PciMemoryFlags(range.addr.0);
289 let range_type = mem_flags.range_type();
290 let prefetchable = mem_flags.prefetchable();
291 let bus_addr = range.addr.1;
292 let cpu_addr = range.parent_addr;
293 let size = range.size;
294
295 if range_type != PciRangeType::Memory64 {
296 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
297 return Err(RebootReason::InvalidFdt);
298 }
299 if prefetchable {
300 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
301 return Err(RebootReason::InvalidFdt);
302 }
303 // Enforce ID bus-to-cpu mappings, as used by crosvm.
304 if bus_addr != cpu_addr {
305 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
306 return Err(RebootReason::InvalidFdt);
307 }
308
Jiyong Park0ee65392023-03-27 20:52:45 +0900309 let Some(bus_end) = bus_addr.checked_add(size) else {
310 error!("PCI address range size {:#x} overflows", size);
311 return Err(RebootReason::InvalidFdt);
312 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000313 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900314 error!("PCI address end {:#x} is outside of translatable range", bus_end);
315 return Err(RebootReason::InvalidFdt);
316 }
317
318 let memory_start = memory_range.start.try_into().unwrap();
319 let memory_end = memory_range.end.try_into().unwrap();
320
321 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
322 error!(
323 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
324 bus_addr, bus_end, memory_start, memory_end
325 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900326 return Err(RebootReason::InvalidFdt);
327 }
328
329 Ok(())
330}
331
332fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000333 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
334 const IRQ_MASK_ADDR_ME: u32 = 0x0;
335 const IRQ_MASK_ADDR_LO: u32 = 0x0;
336 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900337 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000338 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900339 if *irq_mask != EXPECTED {
340 error!("Invalid PCI irq mask {:#?}", irq_mask);
341 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000342 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900343 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000344}
345
Jiyong Park6a8789a2023-03-21 14:50:59 +0900346fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000347 const PCI_DEVICE_IDX: usize = 11;
348 const PCI_IRQ_ADDR_ME: u32 = 0;
349 const PCI_IRQ_ADDR_LO: u32 = 0;
350 const PCI_IRQ_INTC: u32 = 1;
351 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
352 const GIC_SPI: u32 = 0;
353 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
354
Jiyong Park6a8789a2023-03-21 14:50:59 +0900355 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
356 let pci_irq_number = irq_map[3];
357 let _controller_phandle = irq_map[4]; // skipped.
358 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
359 // interrupt-cells is <3> for GIC
360 let gic_peripheral_interrupt_type = irq_map[7];
361 let gic_irq_number = irq_map[8];
362 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000363
Jiyong Park6a8789a2023-03-21 14:50:59 +0900364 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
365 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000366
Jiyong Park6a8789a2023-03-21 14:50:59 +0900367 if pci_addr != expected_pci_addr {
368 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
369 {:#x} {:#x} {:#x}",
370 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
371 return Err(RebootReason::InvalidFdt);
372 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000373
Jiyong Park6a8789a2023-03-21 14:50:59 +0900374 if pci_irq_number != PCI_IRQ_INTC {
375 error!(
376 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
377 pci_irq_number, PCI_IRQ_INTC
378 );
379 return Err(RebootReason::InvalidFdt);
380 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000381
Jiyong Park6a8789a2023-03-21 14:50:59 +0900382 if gic_addr != (0, 0) {
383 error!(
384 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
385 {:#x} {:#x}",
386 gic_addr.0, gic_addr.1, 0, 0
387 );
388 return Err(RebootReason::InvalidFdt);
389 }
390
391 if gic_peripheral_interrupt_type != GIC_SPI {
392 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
393 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
394 return Err(RebootReason::InvalidFdt);
395 }
396
397 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
398 if gic_irq_number != irq_nr {
399 error!(
400 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
401 gic_irq_number, irq_nr
402 );
403 return Err(RebootReason::InvalidFdt);
404 }
405
406 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
407 error!(
408 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
409 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
410 );
411 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000412 }
413 Ok(())
414}
415
Jiyong Park9c63cd12023-03-21 17:53:07 +0900416fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
417 let mut node = fdt
418 .root_mut()?
419 .next_compatible(cstr!("pci-host-cam-generic"))?
420 .ok_or(FdtError::NotFound)?;
421
422 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
423 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
424
425 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
426 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
427
428 node.setprop_inplace(
429 cstr!("ranges"),
430 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
431 )
432}
433
Jiyong Park00ceff32023-03-13 05:43:23 +0000434#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900435struct SerialInfo {
436 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000437}
438
439impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900440 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000441}
442
Jiyong Park6a8789a2023-03-21 14:50:59 +0900443fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
444 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
445 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
446 let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
447 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000448 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900449 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000450}
451
Jiyong Park9c63cd12023-03-21 17:53:07 +0900452/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
453fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
454 let name = cstr!("ns16550a");
455 let mut next = fdt.root_mut()?.next_compatible(name);
456 while let Some(current) = next? {
457 let reg = FdtNode::from_mut(&current)
458 .reg()?
459 .ok_or(FdtError::NotFound)?
460 .next()
461 .ok_or(FdtError::NotFound)?;
462 next = if !serial_info.addrs.contains(&reg.addr) {
463 current.delete_and_next_compatible(name)
464 } else {
465 current.next_compatible(name)
466 }
467 }
468 Ok(())
469}
470
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700471fn validate_swiotlb_info(
472 swiotlb_info: &SwiotlbInfo,
473 memory: &Range<usize>,
474) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900475 let size = swiotlb_info.size;
476 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000477
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700478 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000479 error!("Invalid swiotlb size {:#x}", size);
480 return Err(RebootReason::InvalidFdt);
481 }
482
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000483 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000484 error!("Invalid swiotlb alignment {:#x}", align);
485 return Err(RebootReason::InvalidFdt);
486 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700487
Alice Wang9cfbfd62023-06-14 11:19:03 +0000488 if let Some(addr) = swiotlb_info.addr {
489 if addr.checked_add(size).is_none() {
490 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
491 return Err(RebootReason::InvalidFdt);
492 }
493 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700494 if let Some(range) = swiotlb_info.fixed_range() {
495 if !range.is_within(memory) {
496 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
497 return Err(RebootReason::InvalidFdt);
498 }
499 }
500
Jiyong Park6a8789a2023-03-21 14:50:59 +0900501 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000502}
503
Jiyong Park9c63cd12023-03-21 17:53:07 +0900504fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
505 let mut node =
506 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700507
508 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000509 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700510 cstr!("reg"),
511 range.start.try_into().unwrap(),
512 range.len().try_into().unwrap(),
513 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000514 node.nop_property(cstr!("size"))?;
515 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700516 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000517 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700518 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000519 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700520 }
521
Jiyong Park9c63cd12023-03-21 17:53:07 +0900522 Ok(())
523}
524
525fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
526 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
527 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
528 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
529 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
530
531 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000532 // `validate_num_cpus()` checked that this wouldn't panic
533 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900534
535 // range1 is just below range0
536 range1.addr = addr - size;
537 range1.size = Some(size);
538
539 let range0 = range0.to_cells();
540 let range1 = range1.to_cells();
541 let value = [
542 range0.0, // addr
543 range0.1.unwrap(), //size
544 range1.0, // addr
545 range1.1.unwrap(), //size
546 ];
547
548 let mut node =
549 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
550 node.setprop_inplace(cstr!("reg"), flatten(&value))
551}
552
553fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
554 const NUM_INTERRUPTS: usize = 4;
555 const CELLS_PER_INTERRUPT: usize = 3;
556 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
557 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
558 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
559 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
560
561 let num_cpus: u32 = num_cpus.try_into().unwrap();
562 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
563 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
564 *v |= cpu_mask;
565 }
566 for v in value.iter_mut() {
567 *v = v.to_be();
568 }
569
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100570 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900571 let value = unsafe {
572 core::mem::transmute::<
573 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
574 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
575 >(value.into_inner())
576 };
577
578 let mut node =
579 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
580 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
581}
582
Jiyong Park00ceff32023-03-13 05:43:23 +0000583#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900584pub struct DeviceTreeInfo {
585 pub kernel_range: Option<Range<usize>>,
586 pub initrd_range: Option<Range<usize>>,
587 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900588 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900589 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000590 pci_info: PciInfo,
591 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700592 pub swiotlb_info: SwiotlbInfo,
Jiyong Park00ceff32023-03-13 05:43:23 +0000593}
594
595impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000596 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
597 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
598
599 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
600 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000601}
602
Jiyong Park9c63cd12023-03-21 17:53:07 +0900603pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park83316122023-03-21 09:39:39 +0900604 let info = parse_device_tree(fdt)?;
605 debug!("Device tree info: {:?}", info);
606
Jiyong Parke9d87e82023-03-21 19:28:40 +0900607 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
608 error!("Failed to instantiate FDT from the template DT: {e}");
609 RebootReason::InvalidFdt
610 })?;
611
Jiyong Park9c63cd12023-03-21 17:53:07 +0900612 patch_device_tree(fdt, &info)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900613 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900614}
615
616fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900617 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
618 error!("Failed to read kernel range from DT: {e}");
619 RebootReason::InvalidFdt
620 })?;
621
622 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
623 error!("Failed to read initrd range from DT: {e}");
624 RebootReason::InvalidFdt
625 })?;
626
Alice Wang0d527472023-06-13 14:55:38 +0000627 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900628
Jiyong Parke9d87e82023-03-21 19:28:40 +0900629 let bootargs = read_bootargs_from(fdt).map_err(|e| {
630 error!("Failed to read bootargs from DT: {e}");
631 RebootReason::InvalidFdt
632 })?;
633
Jiyong Park6a8789a2023-03-21 14:50:59 +0900634 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
635 error!("Failed to read num cpus from DT: {e}");
636 RebootReason::InvalidFdt
637 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000638 validate_num_cpus(num_cpus).map_err(|e| {
639 error!("Failed to validate num cpus from DT: {e}");
640 RebootReason::InvalidFdt
641 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900642
643 let pci_info = read_pci_info_from(fdt).map_err(|e| {
644 error!("Failed to read pci info from DT: {e}");
645 RebootReason::InvalidFdt
646 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900647 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900648
649 let serial_info = read_serial_info_from(fdt).map_err(|e| {
650 error!("Failed to read serial info from DT: {e}");
651 RebootReason::InvalidFdt
652 })?;
653
Alice Wang9cfbfd62023-06-14 11:19:03 +0000654 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900655 error!("Failed to read swiotlb info from DT: {e}");
656 RebootReason::InvalidFdt
657 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700658 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900659
Jiyong Park00ceff32023-03-13 05:43:23 +0000660 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900661 kernel_range,
662 initrd_range,
663 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900664 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900665 num_cpus,
666 pci_info,
667 serial_info,
668 swiotlb_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000669 })
670}
671
Jiyong Park9c63cd12023-03-21 17:53:07 +0900672fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900673 fdt.unpack().map_err(|e| {
674 error!("Failed to unpack DT for patching: {e}");
675 RebootReason::InvalidFdt
676 })?;
677
Jiyong Park9c63cd12023-03-21 17:53:07 +0900678 if let Some(initrd_range) = &info.initrd_range {
679 patch_initrd_range(fdt, initrd_range).map_err(|e| {
680 error!("Failed to patch initrd range to DT: {e}");
681 RebootReason::InvalidFdt
682 })?;
683 }
684 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
685 error!("Failed to patch memory range to DT: {e}");
686 RebootReason::InvalidFdt
687 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900688 if let Some(bootargs) = &info.bootargs {
689 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
690 error!("Failed to patch bootargs to DT: {e}");
691 RebootReason::InvalidFdt
692 })?;
693 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900694 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
695 error!("Failed to patch cpus to DT: {e}");
696 RebootReason::InvalidFdt
697 })?;
698 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
699 error!("Failed to patch pci info to DT: {e}");
700 RebootReason::InvalidFdt
701 })?;
702 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
703 error!("Failed to patch serial info to DT: {e}");
704 RebootReason::InvalidFdt
705 })?;
706 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
707 error!("Failed to patch swiotlb info to DT: {e}");
708 RebootReason::InvalidFdt
709 })?;
710 patch_gic(fdt, info.num_cpus).map_err(|e| {
711 error!("Failed to patch gic info to DT: {e}");
712 RebootReason::InvalidFdt
713 })?;
714 patch_timer(fdt, info.num_cpus).map_err(|e| {
715 error!("Failed to patch timer info to DT: {e}");
716 RebootReason::InvalidFdt
717 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900718
719 fdt.pack().map_err(|e| {
720 error!("Failed to pack DT after patching: {e}");
721 RebootReason::InvalidFdt
722 })?;
723
Jiyong Park9c63cd12023-03-21 17:53:07 +0900724 Ok(())
725}
726
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000727/// Modifies the input DT according to the fields of the configuration.
728pub fn modify_for_next_stage(
729 fdt: &mut Fdt,
730 bcc: &[u8],
731 new_instance: bool,
732 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900733 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900734 debuggable: bool,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000735) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000736 if let Some(debug_policy) = debug_policy {
737 let backup = Vec::from(fdt.as_slice());
738 fdt.unpack()?;
739 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
740 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
741 info!("Debug policy applied.");
742 } else {
743 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
744 fdt.unpack()?;
745 }
746 } else {
747 info!("No debug policy found.");
748 fdt.unpack()?;
749 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000750
Jiyong Parke9d87e82023-03-21 19:28:40 +0900751 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000752
Alice Wang56ec45b2023-06-15 08:30:32 +0000753 if let Some(mut chosen) = fdt.chosen_mut()? {
754 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
755 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
756 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900757 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900758 if let Some(bootargs) = read_bootargs_from(fdt)? {
759 filter_out_dangerous_bootargs(fdt, &bootargs)?;
760 }
761 }
762
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000763 fdt.pack()?;
764
765 Ok(())
766}
767
Jiyong Parke9d87e82023-03-21 19:28:40 +0900768/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
769fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000770 // We reject DTs with missing reserved-memory node as validation should have checked that the
771 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900772 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000773
Jiyong Parke9d87e82023-03-21 19:28:40 +0900774 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000775
Jiyong Parke9d87e82023-03-21 19:28:40 +0900776 let addr: u64 = addr.try_into().unwrap();
777 let size: u64 = size.try_into().unwrap();
778 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000779}
780
Alice Wang56ec45b2023-06-15 08:30:32 +0000781fn empty_or_delete_prop(
782 fdt_node: &mut FdtNodeMut,
783 prop_name: &CStr,
784 keep_prop: bool,
785) -> libfdt::Result<()> {
786 if keep_prop {
787 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000788 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000789 fdt_node
790 .delprop(prop_name)
791 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000792 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000793}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900794
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000795/// Apply the debug policy overlay to the guest DT.
796///
797/// 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 +0000798fn apply_debug_policy(
799 fdt: &mut Fdt,
800 backup_fdt: &Fdt,
801 debug_policy: &[u8],
802) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000803 let mut debug_policy = Vec::from(debug_policy);
804 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900805 Ok(overlay) => overlay,
806 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000807 warn!("Corrupted debug policy found: {e}. Not applying.");
808 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900809 }
810 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900811
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100812 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900813 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000814 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900815 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900816 // A successful restoration is considered success because an invalid debug policy
817 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000818 Ok(false)
819 } else {
820 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900821 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900822}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900823
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000824fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900825 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
826 if let Some(value) = node.getprop_u32(debug_feature_name)? {
827 return Ok(value == 1);
828 }
829 }
830 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
831}
832
833fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000834 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
835 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900836
837 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
838 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
839 ("crashkernel", Box::new(|_| has_crashkernel)),
840 ("console", Box::new(|_| has_console)),
841 ];
842
843 // parse and filter out unwanted
844 let mut filtered = Vec::new();
845 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
846 info!("Invalid bootarg: {e}");
847 FdtError::BadValue
848 })? {
849 match accepted.iter().find(|&t| t.0 == arg.name()) {
850 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
851 _ => debug!("Rejected bootarg {}", arg.as_ref()),
852 }
853 }
854
855 // flatten into a new C-string
856 let mut new_bootargs = Vec::new();
857 for (i, arg) in filtered.iter().enumerate() {
858 if i != 0 {
859 new_bootargs.push(b' '); // separator
860 }
861 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
862 }
863 new_bootargs.push(b'\0');
864
865 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
866 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
867}