blob: d4c8385c6a6ab3618b93a94c6a78df375f1a0995 [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 Parkb87f3302023-03-21 10:03:11 +090018use crate::cstr;
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;
Jiyong Parke9d87e82023-03-21 19:28:40 +090022use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090023use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090024use core::cmp::max;
25use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000026use core::ffi::CStr;
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;
Jiyong Park83316122023-03-21 09:39:39 +090036use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000037use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090038use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000039use log::warn;
Jiyong Park00ceff32023-03-13 05:43:23 +000040use tinyvec::ArrayVec;
Alice Wang63f4c9e2023-06-12 09:36:43 +000041use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000042use vmbase::memory::SIZE_4KB;
43use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000044use vmbase::util::RangeExt as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000045
Jiyong Park6a8789a2023-03-21 14:50:59 +090046/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
47/// not an error.
48fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090049 let addr = cstr!("kernel-address");
50 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000051
Jiyong Parkb87f3302023-03-21 10:03:11 +090052 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000053 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
54 let addr = addr as usize;
55 let size = size as usize;
56
57 return Ok(Some(addr..(addr + size)));
58 }
59 }
60
61 Ok(None)
62}
63
Jiyong Park6a8789a2023-03-21 14:50:59 +090064/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
65/// error as there can be initrd-less VM.
66fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090067 let start = cstr!("linux,initrd-start");
68 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000069
70 if let Some(chosen) = fdt.chosen()? {
71 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
72 return Ok(Some((start as usize)..(end as usize)));
73 }
74 }
75
76 Ok(None)
77}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000078
Jiyong Park9c63cd12023-03-21 17:53:07 +090079fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
80 let start = u32::try_from(initrd_range.start).unwrap();
81 let end = u32::try_from(initrd_range.end).unwrap();
82
83 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
84 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
85 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
86 Ok(())
87}
88
Jiyong Parke9d87e82023-03-21 19:28:40 +090089fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
90 if let Some(chosen) = fdt.chosen()? {
91 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
92 // We need to copy the string to heap because the original fdt will be invalidated
93 // by the templated DT
94 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
95 return Ok(Some(copy));
96 }
97 }
98 Ok(None)
99}
100
101fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
102 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900103 // This function is called before the verification is done. So, we just copy the bootargs to
104 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
105 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900106 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
107}
108
Jiyong Park6a8789a2023-03-21 14:50:59 +0900109/// Check if memory range is ok
110fn validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason> {
111 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000112 if base != MEM_START {
113 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000114 return Err(RebootReason::InvalidFdt);
115 }
116
Jiyong Park6a8789a2023-03-21 14:50:59 +0900117 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000118 if size % GUEST_PAGE_SIZE != 0 {
119 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
120 return Err(RebootReason::InvalidFdt);
121 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000122
Jiyong Park6a8789a2023-03-21 14:50:59 +0900123 if size == 0 {
124 error!("Memory size is 0");
125 return Err(RebootReason::InvalidFdt);
126 }
127 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000128}
129
Jiyong Park9c63cd12023-03-21 17:53:07 +0900130fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
131 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900132 fdt.node_mut(cstr!("/memory"))?
133 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000134 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900135}
136
Jiyong Park6a8789a2023-03-21 14:50:59 +0900137/// Read the number of CPUs from DT
138fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
139 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
140}
141
142/// Validate number of CPUs
143fn validate_num_cpus(num_cpus: usize) -> Result<(), RebootReason> {
144 if num_cpus == 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000145 error!("Number of CPU can't be 0");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900146 return Err(RebootReason::InvalidFdt);
147 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900148 if DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).is_none() {
149 error!("Too many CPUs for gic: {}", num_cpus);
150 return Err(RebootReason::InvalidFdt);
151 }
152 Ok(())
153}
154
155/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
156fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
157 let cpu = cstr!("arm,arm-v8");
158 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
159 for _ in 0..num_cpus {
160 next = if let Some(current) = next {
161 current.next_compatible(cpu)?
162 } else {
163 return Err(FdtError::NoSpace);
164 };
165 }
166 while let Some(current) = next {
167 next = current.delete_and_next_compatible(cpu)?;
168 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900169 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000170}
171
172#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000173struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900174 ranges: [PciAddrRange; 2],
175 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
176 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000177}
178
Jiyong Park6a8789a2023-03-21 14:50:59 +0900179impl PciInfo {
180 const IRQ_MASK_CELLS: usize = 4;
181 const IRQ_MAP_CELLS: usize = 10;
182 const MAX_IRQS: usize = 8;
Jiyong Park00ceff32023-03-13 05:43:23 +0000183}
184
Jiyong Park6a8789a2023-03-21 14:50:59 +0900185type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
186type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
187type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000188
189/// Iterator that takes N cells as a chunk
190struct CellChunkIterator<'a, const N: usize> {
191 cells: CellIterator<'a>,
192}
193
194impl<'a, const N: usize> CellChunkIterator<'a, N> {
195 fn new(cells: CellIterator<'a>) -> Self {
196 Self { cells }
197 }
198}
199
200impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
201 type Item = [u32; N];
202 fn next(&mut self) -> Option<Self::Item> {
203 let mut ret: Self::Item = [0; N];
204 for i in ret.iter_mut() {
205 *i = self.cells.next()?;
206 }
207 Some(ret)
208 }
209}
210
Jiyong Park6a8789a2023-03-21 14:50:59 +0900211/// Read pci host controller ranges, irq maps, and irq map masks from DT
212fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
213 let node =
214 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
215
216 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
217 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
218 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
219
220 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
221 let irq_masks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
222 let irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]> =
223 irq_masks.take(PciInfo::MAX_IRQS).collect();
224
225 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
226 let irq_maps = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
227 let irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]> =
228 irq_maps.take(PciInfo::MAX_IRQS).collect();
229
230 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
231}
232
Jiyong Park0ee65392023-03-27 20:52:45 +0900233fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900234 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900235 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900236 }
237 for irq_mask in pci_info.irq_masks.iter() {
238 validate_pci_irq_mask(irq_mask)?;
239 }
240 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
241 validate_pci_irq_map(irq_map, idx)?;
242 }
243 Ok(())
244}
245
Jiyong Park0ee65392023-03-27 20:52:45 +0900246fn validate_pci_addr_range(
247 range: &PciAddrRange,
248 memory_range: &Range<usize>,
249) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900250 let mem_flags = PciMemoryFlags(range.addr.0);
251 let range_type = mem_flags.range_type();
252 let prefetchable = mem_flags.prefetchable();
253 let bus_addr = range.addr.1;
254 let cpu_addr = range.parent_addr;
255 let size = range.size;
256
257 if range_type != PciRangeType::Memory64 {
258 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
259 return Err(RebootReason::InvalidFdt);
260 }
261 if prefetchable {
262 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
263 return Err(RebootReason::InvalidFdt);
264 }
265 // Enforce ID bus-to-cpu mappings, as used by crosvm.
266 if bus_addr != cpu_addr {
267 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
268 return Err(RebootReason::InvalidFdt);
269 }
270
Jiyong Park0ee65392023-03-27 20:52:45 +0900271 let Some(bus_end) = bus_addr.checked_add(size) else {
272 error!("PCI address range size {:#x} overflows", size);
273 return Err(RebootReason::InvalidFdt);
274 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000275 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900276 error!("PCI address end {:#x} is outside of translatable range", bus_end);
277 return Err(RebootReason::InvalidFdt);
278 }
279
280 let memory_start = memory_range.start.try_into().unwrap();
281 let memory_end = memory_range.end.try_into().unwrap();
282
283 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
284 error!(
285 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
286 bus_addr, bus_end, memory_start, memory_end
287 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900288 return Err(RebootReason::InvalidFdt);
289 }
290
291 Ok(())
292}
293
294fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000295 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
296 const IRQ_MASK_ADDR_ME: u32 = 0x0;
297 const IRQ_MASK_ADDR_LO: u32 = 0x0;
298 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900299 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000300 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900301 if *irq_mask != EXPECTED {
302 error!("Invalid PCI irq mask {:#?}", irq_mask);
303 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000304 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900305 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000306}
307
Jiyong Park6a8789a2023-03-21 14:50:59 +0900308fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000309 const PCI_DEVICE_IDX: usize = 11;
310 const PCI_IRQ_ADDR_ME: u32 = 0;
311 const PCI_IRQ_ADDR_LO: u32 = 0;
312 const PCI_IRQ_INTC: u32 = 1;
313 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
314 const GIC_SPI: u32 = 0;
315 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
316
Jiyong Park6a8789a2023-03-21 14:50:59 +0900317 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
318 let pci_irq_number = irq_map[3];
319 let _controller_phandle = irq_map[4]; // skipped.
320 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
321 // interrupt-cells is <3> for GIC
322 let gic_peripheral_interrupt_type = irq_map[7];
323 let gic_irq_number = irq_map[8];
324 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000325
Jiyong Park6a8789a2023-03-21 14:50:59 +0900326 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
327 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000328
Jiyong Park6a8789a2023-03-21 14:50:59 +0900329 if pci_addr != expected_pci_addr {
330 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
331 {:#x} {:#x} {:#x}",
332 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
333 return Err(RebootReason::InvalidFdt);
334 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000335
Jiyong Park6a8789a2023-03-21 14:50:59 +0900336 if pci_irq_number != PCI_IRQ_INTC {
337 error!(
338 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
339 pci_irq_number, PCI_IRQ_INTC
340 );
341 return Err(RebootReason::InvalidFdt);
342 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000343
Jiyong Park6a8789a2023-03-21 14:50:59 +0900344 if gic_addr != (0, 0) {
345 error!(
346 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
347 {:#x} {:#x}",
348 gic_addr.0, gic_addr.1, 0, 0
349 );
350 return Err(RebootReason::InvalidFdt);
351 }
352
353 if gic_peripheral_interrupt_type != GIC_SPI {
354 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
355 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
356 return Err(RebootReason::InvalidFdt);
357 }
358
359 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
360 if gic_irq_number != irq_nr {
361 error!(
362 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
363 gic_irq_number, irq_nr
364 );
365 return Err(RebootReason::InvalidFdt);
366 }
367
368 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
369 error!(
370 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
371 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
372 );
373 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000374 }
375 Ok(())
376}
377
Jiyong Park9c63cd12023-03-21 17:53:07 +0900378fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
379 let mut node = fdt
380 .root_mut()?
381 .next_compatible(cstr!("pci-host-cam-generic"))?
382 .ok_or(FdtError::NotFound)?;
383
384 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
385 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
386
387 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
388 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
389
390 node.setprop_inplace(
391 cstr!("ranges"),
392 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
393 )
394}
395
Jiyong Park00ceff32023-03-13 05:43:23 +0000396#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900397struct SerialInfo {
398 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000399}
400
401impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900402 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000403}
404
Jiyong Park6a8789a2023-03-21 14:50:59 +0900405fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
406 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
407 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
408 let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
409 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000410 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900411 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000412}
413
Jiyong Park9c63cd12023-03-21 17:53:07 +0900414/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
415fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
416 let name = cstr!("ns16550a");
417 let mut next = fdt.root_mut()?.next_compatible(name);
418 while let Some(current) = next? {
419 let reg = FdtNode::from_mut(&current)
420 .reg()?
421 .ok_or(FdtError::NotFound)?
422 .next()
423 .ok_or(FdtError::NotFound)?;
424 next = if !serial_info.addrs.contains(&reg.addr) {
425 current.delete_and_next_compatible(name)
426 } else {
427 current.next_compatible(name)
428 }
429 }
430 Ok(())
431}
432
Jiyong Park00ceff32023-03-13 05:43:23 +0000433#[derive(Debug)]
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700434pub struct SwiotlbInfo {
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700435 addr: Option<usize>,
436 size: usize,
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000437 align: Option<usize>,
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700438}
439
440impl SwiotlbInfo {
Alice Wang9cfbfd62023-06-14 11:19:03 +0000441 /// Creates a `SwiotlbInfo` struct from the given device tree.
442 pub fn new_from_fdt(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo> {
443 let node =
444 fdt.compatible_nodes(cstr!("restricted-dma-pool"))?.next().ok_or(FdtError::NotFound)?;
445
446 let (addr, size, align) = if let Some(mut reg) = node.reg()? {
447 let reg = reg.next().ok_or(FdtError::NotFound)?;
448 let size = reg.size.ok_or(FdtError::NotFound)?;
449 (Some(reg.addr.try_into().unwrap()), size.try_into().unwrap(), None)
450 } else {
451 let size = node.getprop_u64(cstr!("size"))?.ok_or(FdtError::NotFound)?;
452 let align = node.getprop_u64(cstr!("alignment"))?.ok_or(FdtError::NotFound)?;
453 (None, size.try_into().unwrap(), Some(align.try_into().unwrap()))
454 };
455 Ok(Self { addr, size, align })
456 }
457
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700458 pub fn fixed_range(&self) -> Option<Range<usize>> {
459 self.addr.map(|addr| addr..addr + self.size)
460 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000461}
462
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700463fn validate_swiotlb_info(
464 swiotlb_info: &SwiotlbInfo,
465 memory: &Range<usize>,
466) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900467 let size = swiotlb_info.size;
468 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000469
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700470 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000471 error!("Invalid swiotlb size {:#x}", size);
472 return Err(RebootReason::InvalidFdt);
473 }
474
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000475 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000476 error!("Invalid swiotlb alignment {:#x}", align);
477 return Err(RebootReason::InvalidFdt);
478 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700479
Alice Wang9cfbfd62023-06-14 11:19:03 +0000480 if let Some(addr) = swiotlb_info.addr {
481 if addr.checked_add(size).is_none() {
482 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
483 return Err(RebootReason::InvalidFdt);
484 }
485 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700486 if let Some(range) = swiotlb_info.fixed_range() {
487 if !range.is_within(memory) {
488 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
489 return Err(RebootReason::InvalidFdt);
490 }
491 }
492
Jiyong Park6a8789a2023-03-21 14:50:59 +0900493 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000494}
495
Jiyong Park9c63cd12023-03-21 17:53:07 +0900496fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
497 let mut node =
498 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700499
500 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000501 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700502 cstr!("reg"),
503 range.start.try_into().unwrap(),
504 range.len().try_into().unwrap(),
505 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000506 node.nop_property(cstr!("size"))?;
507 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700508 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000509 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700510 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000511 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700512 }
513
Jiyong Park9c63cd12023-03-21 17:53:07 +0900514 Ok(())
515}
516
517fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
518 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
519 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
520 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
521 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
522
523 let addr = range0.addr;
524 // SAFETY - doesn't overflow. checked in validate_num_cpus
525 let size: u64 =
526 DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).unwrap();
527
528 // range1 is just below range0
529 range1.addr = addr - size;
530 range1.size = Some(size);
531
532 let range0 = range0.to_cells();
533 let range1 = range1.to_cells();
534 let value = [
535 range0.0, // addr
536 range0.1.unwrap(), //size
537 range1.0, // addr
538 range1.1.unwrap(), //size
539 ];
540
541 let mut node =
542 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
543 node.setprop_inplace(cstr!("reg"), flatten(&value))
544}
545
546fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
547 const NUM_INTERRUPTS: usize = 4;
548 const CELLS_PER_INTERRUPT: usize = 3;
549 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
550 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
551 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
552 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
553
554 let num_cpus: u32 = num_cpus.try_into().unwrap();
555 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
556 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
557 *v |= cpu_mask;
558 }
559 for v in value.iter_mut() {
560 *v = v.to_be();
561 }
562
563 // SAFETY - array size is the same
564 let value = unsafe {
565 core::mem::transmute::<
566 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
567 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
568 >(value.into_inner())
569 };
570
571 let mut node =
572 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
573 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
574}
575
Jiyong Park00ceff32023-03-13 05:43:23 +0000576#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900577pub struct DeviceTreeInfo {
578 pub kernel_range: Option<Range<usize>>,
579 pub initrd_range: Option<Range<usize>>,
580 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900581 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900582 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000583 pci_info: PciInfo,
584 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700585 pub swiotlb_info: SwiotlbInfo,
Jiyong Park00ceff32023-03-13 05:43:23 +0000586}
587
588impl DeviceTreeInfo {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900589 const GIC_REDIST_SIZE_PER_CPU: u64 = (32 * SIZE_4KB) as u64;
Jiyong Park00ceff32023-03-13 05:43:23 +0000590}
591
Jiyong Park9c63cd12023-03-21 17:53:07 +0900592pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park83316122023-03-21 09:39:39 +0900593 let info = parse_device_tree(fdt)?;
594 debug!("Device tree info: {:?}", info);
595
Jiyong Parke9d87e82023-03-21 19:28:40 +0900596 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
597 error!("Failed to instantiate FDT from the template DT: {e}");
598 RebootReason::InvalidFdt
599 })?;
600
Jiyong Park9c63cd12023-03-21 17:53:07 +0900601 patch_device_tree(fdt, &info)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900602 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900603}
604
605fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900606 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
607 error!("Failed to read kernel range from DT: {e}");
608 RebootReason::InvalidFdt
609 })?;
610
611 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
612 error!("Failed to read initrd range from DT: {e}");
613 RebootReason::InvalidFdt
614 })?;
615
Alice Wang2422bdc2023-06-12 08:37:55 +0000616 let memory_range = fdt.first_memory_range().map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900617 error!("Failed to read memory range from DT: {e}");
618 RebootReason::InvalidFdt
619 })?;
620 validate_memory_range(&memory_range)?;
621
Jiyong Parke9d87e82023-03-21 19:28:40 +0900622 let bootargs = read_bootargs_from(fdt).map_err(|e| {
623 error!("Failed to read bootargs from DT: {e}");
624 RebootReason::InvalidFdt
625 })?;
626
Jiyong Park6a8789a2023-03-21 14:50:59 +0900627 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
628 error!("Failed to read num cpus from DT: {e}");
629 RebootReason::InvalidFdt
630 })?;
631 validate_num_cpus(num_cpus)?;
632
633 let pci_info = read_pci_info_from(fdt).map_err(|e| {
634 error!("Failed to read pci info from DT: {e}");
635 RebootReason::InvalidFdt
636 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900637 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900638
639 let serial_info = read_serial_info_from(fdt).map_err(|e| {
640 error!("Failed to read serial info from DT: {e}");
641 RebootReason::InvalidFdt
642 })?;
643
Alice Wang9cfbfd62023-06-14 11:19:03 +0000644 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900645 error!("Failed to read swiotlb info from DT: {e}");
646 RebootReason::InvalidFdt
647 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700648 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900649
Jiyong Park00ceff32023-03-13 05:43:23 +0000650 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900651 kernel_range,
652 initrd_range,
653 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900654 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900655 num_cpus,
656 pci_info,
657 serial_info,
658 swiotlb_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000659 })
660}
661
Jiyong Park9c63cd12023-03-21 17:53:07 +0900662fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900663 fdt.unpack().map_err(|e| {
664 error!("Failed to unpack DT for patching: {e}");
665 RebootReason::InvalidFdt
666 })?;
667
Jiyong Park9c63cd12023-03-21 17:53:07 +0900668 if let Some(initrd_range) = &info.initrd_range {
669 patch_initrd_range(fdt, initrd_range).map_err(|e| {
670 error!("Failed to patch initrd range to DT: {e}");
671 RebootReason::InvalidFdt
672 })?;
673 }
674 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
675 error!("Failed to patch memory range to DT: {e}");
676 RebootReason::InvalidFdt
677 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900678 if let Some(bootargs) = &info.bootargs {
679 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
680 error!("Failed to patch bootargs to DT: {e}");
681 RebootReason::InvalidFdt
682 })?;
683 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900684 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
685 error!("Failed to patch cpus to DT: {e}");
686 RebootReason::InvalidFdt
687 })?;
688 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
689 error!("Failed to patch pci info to DT: {e}");
690 RebootReason::InvalidFdt
691 })?;
692 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
693 error!("Failed to patch serial info to DT: {e}");
694 RebootReason::InvalidFdt
695 })?;
696 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
697 error!("Failed to patch swiotlb info to DT: {e}");
698 RebootReason::InvalidFdt
699 })?;
700 patch_gic(fdt, info.num_cpus).map_err(|e| {
701 error!("Failed to patch gic info to DT: {e}");
702 RebootReason::InvalidFdt
703 })?;
704 patch_timer(fdt, info.num_cpus).map_err(|e| {
705 error!("Failed to patch timer info to DT: {e}");
706 RebootReason::InvalidFdt
707 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900708
709 fdt.pack().map_err(|e| {
710 error!("Failed to pack DT after patching: {e}");
711 RebootReason::InvalidFdt
712 })?;
713
Jiyong Park9c63cd12023-03-21 17:53:07 +0900714 Ok(())
715}
716
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000717/// Modifies the input DT according to the fields of the configuration.
718pub fn modify_for_next_stage(
719 fdt: &mut Fdt,
720 bcc: &[u8],
721 new_instance: bool,
722 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900723 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900724 debuggable: bool,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000725) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000726 if let Some(debug_policy) = debug_policy {
727 let backup = Vec::from(fdt.as_slice());
728 fdt.unpack()?;
729 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
730 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
731 info!("Debug policy applied.");
732 } else {
733 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
734 fdt.unpack()?;
735 }
736 } else {
737 info!("No debug policy found.");
738 fdt.unpack()?;
739 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000740
Jiyong Parke9d87e82023-03-21 19:28:40 +0900741 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000742
Jiyong Parkb87f3302023-03-21 10:03:11 +0900743 set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?;
744 set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000745
Jiyong Park32f37ef2023-05-17 16:15:58 +0900746 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900747 if let Some(bootargs) = read_bootargs_from(fdt)? {
748 filter_out_dangerous_bootargs(fdt, &bootargs)?;
749 }
750 }
751
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000752 fdt.pack()?;
753
754 Ok(())
755}
756
Jiyong Parke9d87e82023-03-21 19:28:40 +0900757/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
758fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000759 // We reject DTs with missing reserved-memory node as validation should have checked that the
760 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900761 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000762
Jiyong Parke9d87e82023-03-21 19:28:40 +0900763 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000764
Jiyong Parke9d87e82023-03-21 19:28:40 +0900765 let addr: u64 = addr.try_into().unwrap();
766 let size: u64 = size.try_into().unwrap();
767 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000768}
769
770fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> {
771 // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node.
772 let mut chosen = fdt.chosen_mut()?.unwrap();
773 if value {
774 chosen.setprop_empty(flag)?;
775 } else {
776 match chosen.delprop(flag) {
777 Ok(()) | Err(FdtError::NotFound) => (),
778 Err(e) => return Err(e),
779 }
780 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000781
782 Ok(())
783}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900784
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000785/// Apply the debug policy overlay to the guest DT.
786///
787/// 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 +0000788fn apply_debug_policy(
789 fdt: &mut Fdt,
790 backup_fdt: &Fdt,
791 debug_policy: &[u8],
792) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000793 let mut debug_policy = Vec::from(debug_policy);
794 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900795 Ok(overlay) => overlay,
796 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000797 warn!("Corrupted debug policy found: {e}. Not applying.");
798 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900799 }
800 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900801
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000802 // SAFETY - on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900803 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000804 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900805 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900806 // A successful restoration is considered success because an invalid debug policy
807 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000808 Ok(false)
809 } else {
810 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900811 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900812}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900813
814fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
815 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
816 if let Some(value) = node.getprop_u32(debug_feature_name)? {
817 return Ok(value == 1);
818 }
819 }
820 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
821}
822
823fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
824 let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?;
825 let has_console = read_common_debug_policy(fdt, cstr!("log"))?;
826
827 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
828 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
829 ("crashkernel", Box::new(|_| has_crashkernel)),
830 ("console", Box::new(|_| has_console)),
831 ];
832
833 // parse and filter out unwanted
834 let mut filtered = Vec::new();
835 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
836 info!("Invalid bootarg: {e}");
837 FdtError::BadValue
838 })? {
839 match accepted.iter().find(|&t| t.0 == arg.name()) {
840 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
841 _ => debug!("Rejected bootarg {}", arg.as_ref()),
842 }
843 }
844
845 // flatten into a new C-string
846 let mut new_bootargs = Vec::new();
847 for (i, arg) in filtered.iter().enumerate() {
848 if i != 0 {
849 new_bootargs.push(b' '); // separator
850 }
851 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
852 }
853 new_bootargs.push(b'\0');
854
855 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
856 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
857}