blob: efb354cf44dfa19ba64b785ec2fc881b5df27771 [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
Jiyong Park6a8789a2023-03-21 14:50:59 +0900127/// Check if memory range is ok
128fn validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason> {
129 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000130 if base != MEM_START {
131 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000132 return Err(RebootReason::InvalidFdt);
133 }
134
Jiyong Park6a8789a2023-03-21 14:50:59 +0900135 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000136 if size % GUEST_PAGE_SIZE != 0 {
137 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
138 return Err(RebootReason::InvalidFdt);
139 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000140
Jiyong Park6a8789a2023-03-21 14:50:59 +0900141 if size == 0 {
142 error!("Memory size is 0");
143 return Err(RebootReason::InvalidFdt);
144 }
145 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000146}
147
Jiyong Park9c63cd12023-03-21 17:53:07 +0900148fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
149 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900150 fdt.node_mut(cstr!("/memory"))?
151 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000152 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900153}
154
Jiyong Park6a8789a2023-03-21 14:50:59 +0900155/// Read the number of CPUs from DT
156fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
157 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
158}
159
160/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000161fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
162 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
163 Err(FdtValidationError::InvalidCpuCount(num_cpus))
164 } else {
165 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900166 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900167}
168
169/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
170fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
171 let cpu = cstr!("arm,arm-v8");
172 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
173 for _ in 0..num_cpus {
174 next = if let Some(current) = next {
175 current.next_compatible(cpu)?
176 } else {
177 return Err(FdtError::NoSpace);
178 };
179 }
180 while let Some(current) = next {
181 next = current.delete_and_next_compatible(cpu)?;
182 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900183 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000184}
185
186#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000187struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900188 ranges: [PciAddrRange; 2],
189 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
190 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000191}
192
Jiyong Park6a8789a2023-03-21 14:50:59 +0900193impl PciInfo {
194 const IRQ_MASK_CELLS: usize = 4;
195 const IRQ_MAP_CELLS: usize = 10;
196 const MAX_IRQS: usize = 8;
Jiyong Park00ceff32023-03-13 05:43:23 +0000197}
198
Jiyong Park6a8789a2023-03-21 14:50:59 +0900199type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
200type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
201type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000202
203/// Iterator that takes N cells as a chunk
204struct CellChunkIterator<'a, const N: usize> {
205 cells: CellIterator<'a>,
206}
207
208impl<'a, const N: usize> CellChunkIterator<'a, N> {
209 fn new(cells: CellIterator<'a>) -> Self {
210 Self { cells }
211 }
212}
213
214impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
215 type Item = [u32; N];
216 fn next(&mut self) -> Option<Self::Item> {
217 let mut ret: Self::Item = [0; N];
218 for i in ret.iter_mut() {
219 *i = self.cells.next()?;
220 }
221 Some(ret)
222 }
223}
224
Jiyong Park6a8789a2023-03-21 14:50:59 +0900225/// Read pci host controller ranges, irq maps, and irq map masks from DT
226fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
227 let node =
228 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
229
230 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
231 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
232 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
233
234 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
235 let irq_masks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
236 let irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]> =
237 irq_masks.take(PciInfo::MAX_IRQS).collect();
238
239 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
240 let irq_maps = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
241 let irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]> =
242 irq_maps.take(PciInfo::MAX_IRQS).collect();
243
244 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
245}
246
Jiyong Park0ee65392023-03-27 20:52:45 +0900247fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900248 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900249 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900250 }
251 for irq_mask in pci_info.irq_masks.iter() {
252 validate_pci_irq_mask(irq_mask)?;
253 }
254 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
255 validate_pci_irq_map(irq_map, idx)?;
256 }
257 Ok(())
258}
259
Jiyong Park0ee65392023-03-27 20:52:45 +0900260fn validate_pci_addr_range(
261 range: &PciAddrRange,
262 memory_range: &Range<usize>,
263) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900264 let mem_flags = PciMemoryFlags(range.addr.0);
265 let range_type = mem_flags.range_type();
266 let prefetchable = mem_flags.prefetchable();
267 let bus_addr = range.addr.1;
268 let cpu_addr = range.parent_addr;
269 let size = range.size;
270
271 if range_type != PciRangeType::Memory64 {
272 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
273 return Err(RebootReason::InvalidFdt);
274 }
275 if prefetchable {
276 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
277 return Err(RebootReason::InvalidFdt);
278 }
279 // Enforce ID bus-to-cpu mappings, as used by crosvm.
280 if bus_addr != cpu_addr {
281 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
282 return Err(RebootReason::InvalidFdt);
283 }
284
Jiyong Park0ee65392023-03-27 20:52:45 +0900285 let Some(bus_end) = bus_addr.checked_add(size) else {
286 error!("PCI address range size {:#x} overflows", size);
287 return Err(RebootReason::InvalidFdt);
288 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000289 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900290 error!("PCI address end {:#x} is outside of translatable range", bus_end);
291 return Err(RebootReason::InvalidFdt);
292 }
293
294 let memory_start = memory_range.start.try_into().unwrap();
295 let memory_end = memory_range.end.try_into().unwrap();
296
297 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
298 error!(
299 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
300 bus_addr, bus_end, memory_start, memory_end
301 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900302 return Err(RebootReason::InvalidFdt);
303 }
304
305 Ok(())
306}
307
308fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000309 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
310 const IRQ_MASK_ADDR_ME: u32 = 0x0;
311 const IRQ_MASK_ADDR_LO: u32 = 0x0;
312 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900313 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000314 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900315 if *irq_mask != EXPECTED {
316 error!("Invalid PCI irq mask {:#?}", irq_mask);
317 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000318 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900319 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000320}
321
Jiyong Park6a8789a2023-03-21 14:50:59 +0900322fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000323 const PCI_DEVICE_IDX: usize = 11;
324 const PCI_IRQ_ADDR_ME: u32 = 0;
325 const PCI_IRQ_ADDR_LO: u32 = 0;
326 const PCI_IRQ_INTC: u32 = 1;
327 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
328 const GIC_SPI: u32 = 0;
329 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
330
Jiyong Park6a8789a2023-03-21 14:50:59 +0900331 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
332 let pci_irq_number = irq_map[3];
333 let _controller_phandle = irq_map[4]; // skipped.
334 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
335 // interrupt-cells is <3> for GIC
336 let gic_peripheral_interrupt_type = irq_map[7];
337 let gic_irq_number = irq_map[8];
338 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000339
Jiyong Park6a8789a2023-03-21 14:50:59 +0900340 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
341 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000342
Jiyong Park6a8789a2023-03-21 14:50:59 +0900343 if pci_addr != expected_pci_addr {
344 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
345 {:#x} {:#x} {:#x}",
346 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
347 return Err(RebootReason::InvalidFdt);
348 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000349
Jiyong Park6a8789a2023-03-21 14:50:59 +0900350 if pci_irq_number != PCI_IRQ_INTC {
351 error!(
352 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
353 pci_irq_number, PCI_IRQ_INTC
354 );
355 return Err(RebootReason::InvalidFdt);
356 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000357
Jiyong Park6a8789a2023-03-21 14:50:59 +0900358 if gic_addr != (0, 0) {
359 error!(
360 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
361 {:#x} {:#x}",
362 gic_addr.0, gic_addr.1, 0, 0
363 );
364 return Err(RebootReason::InvalidFdt);
365 }
366
367 if gic_peripheral_interrupt_type != GIC_SPI {
368 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
369 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
370 return Err(RebootReason::InvalidFdt);
371 }
372
373 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
374 if gic_irq_number != irq_nr {
375 error!(
376 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
377 gic_irq_number, irq_nr
378 );
379 return Err(RebootReason::InvalidFdt);
380 }
381
382 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
383 error!(
384 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
385 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
386 );
387 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000388 }
389 Ok(())
390}
391
Jiyong Park9c63cd12023-03-21 17:53:07 +0900392fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
393 let mut node = fdt
394 .root_mut()?
395 .next_compatible(cstr!("pci-host-cam-generic"))?
396 .ok_or(FdtError::NotFound)?;
397
398 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
399 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
400
401 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
402 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
403
404 node.setprop_inplace(
405 cstr!("ranges"),
406 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
407 )
408}
409
Jiyong Park00ceff32023-03-13 05:43:23 +0000410#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900411struct SerialInfo {
412 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000413}
414
415impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900416 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000417}
418
Jiyong Park6a8789a2023-03-21 14:50:59 +0900419fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
420 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
421 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
422 let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
423 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000424 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900425 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000426}
427
Jiyong Park9c63cd12023-03-21 17:53:07 +0900428/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
429fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
430 let name = cstr!("ns16550a");
431 let mut next = fdt.root_mut()?.next_compatible(name);
432 while let Some(current) = next? {
433 let reg = FdtNode::from_mut(&current)
434 .reg()?
435 .ok_or(FdtError::NotFound)?
436 .next()
437 .ok_or(FdtError::NotFound)?;
438 next = if !serial_info.addrs.contains(&reg.addr) {
439 current.delete_and_next_compatible(name)
440 } else {
441 current.next_compatible(name)
442 }
443 }
444 Ok(())
445}
446
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700447fn validate_swiotlb_info(
448 swiotlb_info: &SwiotlbInfo,
449 memory: &Range<usize>,
450) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900451 let size = swiotlb_info.size;
452 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000453
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700454 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000455 error!("Invalid swiotlb size {:#x}", size);
456 return Err(RebootReason::InvalidFdt);
457 }
458
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000459 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000460 error!("Invalid swiotlb alignment {:#x}", align);
461 return Err(RebootReason::InvalidFdt);
462 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700463
Alice Wang9cfbfd62023-06-14 11:19:03 +0000464 if let Some(addr) = swiotlb_info.addr {
465 if addr.checked_add(size).is_none() {
466 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
467 return Err(RebootReason::InvalidFdt);
468 }
469 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700470 if let Some(range) = swiotlb_info.fixed_range() {
471 if !range.is_within(memory) {
472 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
473 return Err(RebootReason::InvalidFdt);
474 }
475 }
476
Jiyong Park6a8789a2023-03-21 14:50:59 +0900477 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000478}
479
Jiyong Park9c63cd12023-03-21 17:53:07 +0900480fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
481 let mut node =
482 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700483
484 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000485 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700486 cstr!("reg"),
487 range.start.try_into().unwrap(),
488 range.len().try_into().unwrap(),
489 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000490 node.nop_property(cstr!("size"))?;
491 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700492 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000493 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700494 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000495 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700496 }
497
Jiyong Park9c63cd12023-03-21 17:53:07 +0900498 Ok(())
499}
500
501fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
502 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
503 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
504 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
505 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
506
507 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000508 // `validate_num_cpus()` checked that this wouldn't panic
509 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900510
511 // range1 is just below range0
512 range1.addr = addr - size;
513 range1.size = Some(size);
514
515 let range0 = range0.to_cells();
516 let range1 = range1.to_cells();
517 let value = [
518 range0.0, // addr
519 range0.1.unwrap(), //size
520 range1.0, // addr
521 range1.1.unwrap(), //size
522 ];
523
524 let mut node =
525 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
526 node.setprop_inplace(cstr!("reg"), flatten(&value))
527}
528
529fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
530 const NUM_INTERRUPTS: usize = 4;
531 const CELLS_PER_INTERRUPT: usize = 3;
532 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
533 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
534 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
535 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
536
537 let num_cpus: u32 = num_cpus.try_into().unwrap();
538 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
539 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
540 *v |= cpu_mask;
541 }
542 for v in value.iter_mut() {
543 *v = v.to_be();
544 }
545
546 // SAFETY - array size is the same
547 let value = unsafe {
548 core::mem::transmute::<
549 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
550 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
551 >(value.into_inner())
552 };
553
554 let mut node =
555 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
556 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
557}
558
Jiyong Park00ceff32023-03-13 05:43:23 +0000559#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900560pub struct DeviceTreeInfo {
561 pub kernel_range: Option<Range<usize>>,
562 pub initrd_range: Option<Range<usize>>,
563 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900564 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900565 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000566 pci_info: PciInfo,
567 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700568 pub swiotlb_info: SwiotlbInfo,
Jiyong Park00ceff32023-03-13 05:43:23 +0000569}
570
571impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000572 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
573 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
574
575 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
576 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000577}
578
Jiyong Park9c63cd12023-03-21 17:53:07 +0900579pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park83316122023-03-21 09:39:39 +0900580 let info = parse_device_tree(fdt)?;
581 debug!("Device tree info: {:?}", info);
582
Jiyong Parke9d87e82023-03-21 19:28:40 +0900583 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
584 error!("Failed to instantiate FDT from the template DT: {e}");
585 RebootReason::InvalidFdt
586 })?;
587
Jiyong Park9c63cd12023-03-21 17:53:07 +0900588 patch_device_tree(fdt, &info)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900589 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900590}
591
592fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900593 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
594 error!("Failed to read kernel range from DT: {e}");
595 RebootReason::InvalidFdt
596 })?;
597
598 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
599 error!("Failed to read initrd range from DT: {e}");
600 RebootReason::InvalidFdt
601 })?;
602
Alice Wang2422bdc2023-06-12 08:37:55 +0000603 let memory_range = fdt.first_memory_range().map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900604 error!("Failed to read memory range from DT: {e}");
605 RebootReason::InvalidFdt
606 })?;
607 validate_memory_range(&memory_range)?;
608
Jiyong Parke9d87e82023-03-21 19:28:40 +0900609 let bootargs = read_bootargs_from(fdt).map_err(|e| {
610 error!("Failed to read bootargs from DT: {e}");
611 RebootReason::InvalidFdt
612 })?;
613
Jiyong Park6a8789a2023-03-21 14:50:59 +0900614 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
615 error!("Failed to read num cpus from DT: {e}");
616 RebootReason::InvalidFdt
617 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000618 validate_num_cpus(num_cpus).map_err(|e| {
619 error!("Failed to validate num cpus from DT: {e}");
620 RebootReason::InvalidFdt
621 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900622
623 let pci_info = read_pci_info_from(fdt).map_err(|e| {
624 error!("Failed to read pci info from DT: {e}");
625 RebootReason::InvalidFdt
626 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900627 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900628
629 let serial_info = read_serial_info_from(fdt).map_err(|e| {
630 error!("Failed to read serial info from DT: {e}");
631 RebootReason::InvalidFdt
632 })?;
633
Alice Wang9cfbfd62023-06-14 11:19:03 +0000634 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900635 error!("Failed to read swiotlb info from DT: {e}");
636 RebootReason::InvalidFdt
637 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700638 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900639
Jiyong Park00ceff32023-03-13 05:43:23 +0000640 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900641 kernel_range,
642 initrd_range,
643 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900644 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900645 num_cpus,
646 pci_info,
647 serial_info,
648 swiotlb_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000649 })
650}
651
Jiyong Park9c63cd12023-03-21 17:53:07 +0900652fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900653 fdt.unpack().map_err(|e| {
654 error!("Failed to unpack DT for patching: {e}");
655 RebootReason::InvalidFdt
656 })?;
657
Jiyong Park9c63cd12023-03-21 17:53:07 +0900658 if let Some(initrd_range) = &info.initrd_range {
659 patch_initrd_range(fdt, initrd_range).map_err(|e| {
660 error!("Failed to patch initrd range to DT: {e}");
661 RebootReason::InvalidFdt
662 })?;
663 }
664 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
665 error!("Failed to patch memory range to DT: {e}");
666 RebootReason::InvalidFdt
667 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900668 if let Some(bootargs) = &info.bootargs {
669 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
670 error!("Failed to patch bootargs to DT: {e}");
671 RebootReason::InvalidFdt
672 })?;
673 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900674 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
675 error!("Failed to patch cpus to DT: {e}");
676 RebootReason::InvalidFdt
677 })?;
678 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
679 error!("Failed to patch pci info to DT: {e}");
680 RebootReason::InvalidFdt
681 })?;
682 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
683 error!("Failed to patch serial info to DT: {e}");
684 RebootReason::InvalidFdt
685 })?;
686 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
687 error!("Failed to patch swiotlb info to DT: {e}");
688 RebootReason::InvalidFdt
689 })?;
690 patch_gic(fdt, info.num_cpus).map_err(|e| {
691 error!("Failed to patch gic info to DT: {e}");
692 RebootReason::InvalidFdt
693 })?;
694 patch_timer(fdt, info.num_cpus).map_err(|e| {
695 error!("Failed to patch timer info to DT: {e}");
696 RebootReason::InvalidFdt
697 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900698
699 fdt.pack().map_err(|e| {
700 error!("Failed to pack DT after patching: {e}");
701 RebootReason::InvalidFdt
702 })?;
703
Jiyong Park9c63cd12023-03-21 17:53:07 +0900704 Ok(())
705}
706
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000707/// Modifies the input DT according to the fields of the configuration.
708pub fn modify_for_next_stage(
709 fdt: &mut Fdt,
710 bcc: &[u8],
711 new_instance: bool,
712 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900713 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900714 debuggable: bool,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000715) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000716 if let Some(debug_policy) = debug_policy {
717 let backup = Vec::from(fdt.as_slice());
718 fdt.unpack()?;
719 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
720 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
721 info!("Debug policy applied.");
722 } else {
723 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
724 fdt.unpack()?;
725 }
726 } else {
727 info!("No debug policy found.");
728 fdt.unpack()?;
729 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000730
Jiyong Parke9d87e82023-03-21 19:28:40 +0900731 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000732
Alice Wang56ec45b2023-06-15 08:30:32 +0000733 if let Some(mut chosen) = fdt.chosen_mut()? {
734 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
735 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
736 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900737 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900738 if let Some(bootargs) = read_bootargs_from(fdt)? {
739 filter_out_dangerous_bootargs(fdt, &bootargs)?;
740 }
741 }
742
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000743 fdt.pack()?;
744
745 Ok(())
746}
747
Jiyong Parke9d87e82023-03-21 19:28:40 +0900748/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
749fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000750 // We reject DTs with missing reserved-memory node as validation should have checked that the
751 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900752 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000753
Jiyong Parke9d87e82023-03-21 19:28:40 +0900754 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000755
Jiyong Parke9d87e82023-03-21 19:28:40 +0900756 let addr: u64 = addr.try_into().unwrap();
757 let size: u64 = size.try_into().unwrap();
758 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000759}
760
Alice Wang56ec45b2023-06-15 08:30:32 +0000761fn empty_or_delete_prop(
762 fdt_node: &mut FdtNodeMut,
763 prop_name: &CStr,
764 keep_prop: bool,
765) -> libfdt::Result<()> {
766 if keep_prop {
767 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000768 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000769 fdt_node
770 .delprop(prop_name)
771 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000772 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000773}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900774
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000775/// Apply the debug policy overlay to the guest DT.
776///
777/// 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 +0000778fn apply_debug_policy(
779 fdt: &mut Fdt,
780 backup_fdt: &Fdt,
781 debug_policy: &[u8],
782) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000783 let mut debug_policy = Vec::from(debug_policy);
784 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900785 Ok(overlay) => overlay,
786 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000787 warn!("Corrupted debug policy found: {e}. Not applying.");
788 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900789 }
790 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900791
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000792 // SAFETY - on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900793 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000794 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900795 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900796 // A successful restoration is considered success because an invalid debug policy
797 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000798 Ok(false)
799 } else {
800 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900801 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900802}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900803
804fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
805 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
806 if let Some(value) = node.getprop_u32(debug_feature_name)? {
807 return Ok(value == 1);
808 }
809 }
810 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
811}
812
813fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
814 let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?;
815 let has_console = read_common_debug_policy(fdt, cstr!("log"))?;
816
817 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
818 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
819 ("crashkernel", Box::new(|_| has_crashkernel)),
820 ("console", Box::new(|_| has_console)),
821 ];
822
823 // parse and filter out unwanted
824 let mut filtered = Vec::new();
825 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
826 info!("Invalid bootarg: {e}");
827 FdtError::BadValue
828 })? {
829 match accepted.iter().find(|&t| t.0 == arg.name()) {
830 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
831 _ => debug!("Rejected bootarg {}", arg.as_ref()),
832 }
833 }
834
835 // flatten into a new C-string
836 let mut new_bootargs = Vec::new();
837 for (i, arg) in filtered.iter().enumerate() {
838 if i != 0 {
839 new_bootargs.push(b' '); // separator
840 }
841 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
842 }
843 new_bootargs.push(b'\0');
844
845 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
846 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
847}