blob: ab851a16235fb4151f263b32941b06240bb1b4aa [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 {
441 pub fn fixed_range(&self) -> Option<Range<usize>> {
442 self.addr.map(|addr| addr..addr + self.size)
443 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000444}
445
Jiyong Park6a8789a2023-03-21 14:50:59 +0900446fn read_swiotlb_info_from(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo> {
447 let node =
448 fdt.compatible_nodes(cstr!("restricted-dma-pool"))?.next().ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700449
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000450 let (addr, size, align) = if let Some(mut reg) = node.reg()? {
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700451 let reg = reg.next().ok_or(FdtError::NotFound)?;
452 let size = reg.size.ok_or(FdtError::NotFound)?;
453 reg.addr.checked_add(size).ok_or(FdtError::BadValue)?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000454 (Some(reg.addr.try_into().unwrap()), size.try_into().unwrap(), None)
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700455 } else {
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000456 let size = node.getprop_u64(cstr!("size"))?.ok_or(FdtError::NotFound)?;
457 let align = node.getprop_u64(cstr!("alignment"))?.ok_or(FdtError::NotFound)?;
458 (None, size.try_into().unwrap(), Some(align.try_into().unwrap()))
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700459 };
460
461 Ok(SwiotlbInfo { addr, size, align })
Jiyong Park6a8789a2023-03-21 14:50:59 +0900462}
Jiyong Park00ceff32023-03-13 05:43:23 +0000463
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700464fn validate_swiotlb_info(
465 swiotlb_info: &SwiotlbInfo,
466 memory: &Range<usize>,
467) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900468 let size = swiotlb_info.size;
469 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000470
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700471 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000472 error!("Invalid swiotlb size {:#x}", size);
473 return Err(RebootReason::InvalidFdt);
474 }
475
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000476 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000477 error!("Invalid swiotlb alignment {:#x}", align);
478 return Err(RebootReason::InvalidFdt);
479 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700480
481 if let Some(range) = swiotlb_info.fixed_range() {
482 if !range.is_within(memory) {
483 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
484 return Err(RebootReason::InvalidFdt);
485 }
486 }
487
Jiyong Park6a8789a2023-03-21 14:50:59 +0900488 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000489}
490
Jiyong Park9c63cd12023-03-21 17:53:07 +0900491fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
492 let mut node =
493 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700494
495 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000496 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700497 cstr!("reg"),
498 range.start.try_into().unwrap(),
499 range.len().try_into().unwrap(),
500 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000501 node.nop_property(cstr!("size"))?;
502 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700503 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000504 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700505 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000506 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700507 }
508
Jiyong Park9c63cd12023-03-21 17:53:07 +0900509 Ok(())
510}
511
512fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
513 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
514 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
515 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
516 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
517
518 let addr = range0.addr;
519 // SAFETY - doesn't overflow. checked in validate_num_cpus
520 let size: u64 =
521 DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).unwrap();
522
523 // range1 is just below range0
524 range1.addr = addr - size;
525 range1.size = Some(size);
526
527 let range0 = range0.to_cells();
528 let range1 = range1.to_cells();
529 let value = [
530 range0.0, // addr
531 range0.1.unwrap(), //size
532 range1.0, // addr
533 range1.1.unwrap(), //size
534 ];
535
536 let mut node =
537 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
538 node.setprop_inplace(cstr!("reg"), flatten(&value))
539}
540
541fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
542 const NUM_INTERRUPTS: usize = 4;
543 const CELLS_PER_INTERRUPT: usize = 3;
544 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
545 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
546 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
547 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
548
549 let num_cpus: u32 = num_cpus.try_into().unwrap();
550 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
551 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
552 *v |= cpu_mask;
553 }
554 for v in value.iter_mut() {
555 *v = v.to_be();
556 }
557
558 // SAFETY - array size is the same
559 let value = unsafe {
560 core::mem::transmute::<
561 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
562 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
563 >(value.into_inner())
564 };
565
566 let mut node =
567 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
568 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
569}
570
Jiyong Park00ceff32023-03-13 05:43:23 +0000571#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900572pub struct DeviceTreeInfo {
573 pub kernel_range: Option<Range<usize>>,
574 pub initrd_range: Option<Range<usize>>,
575 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900576 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900577 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000578 pci_info: PciInfo,
579 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700580 pub swiotlb_info: SwiotlbInfo,
Jiyong Park00ceff32023-03-13 05:43:23 +0000581}
582
583impl DeviceTreeInfo {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900584 const GIC_REDIST_SIZE_PER_CPU: u64 = (32 * SIZE_4KB) as u64;
Jiyong Park00ceff32023-03-13 05:43:23 +0000585}
586
Jiyong Park9c63cd12023-03-21 17:53:07 +0900587pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park83316122023-03-21 09:39:39 +0900588 let info = parse_device_tree(fdt)?;
589 debug!("Device tree info: {:?}", info);
590
Jiyong Parke9d87e82023-03-21 19:28:40 +0900591 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
592 error!("Failed to instantiate FDT from the template DT: {e}");
593 RebootReason::InvalidFdt
594 })?;
595
Jiyong Park9c63cd12023-03-21 17:53:07 +0900596 patch_device_tree(fdt, &info)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900597 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900598}
599
600fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900601 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
602 error!("Failed to read kernel range from DT: {e}");
603 RebootReason::InvalidFdt
604 })?;
605
606 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
607 error!("Failed to read initrd range from DT: {e}");
608 RebootReason::InvalidFdt
609 })?;
610
Alice Wang2422bdc2023-06-12 08:37:55 +0000611 let memory_range = fdt.first_memory_range().map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900612 error!("Failed to read memory range from DT: {e}");
613 RebootReason::InvalidFdt
614 })?;
615 validate_memory_range(&memory_range)?;
616
Jiyong Parke9d87e82023-03-21 19:28:40 +0900617 let bootargs = read_bootargs_from(fdt).map_err(|e| {
618 error!("Failed to read bootargs from DT: {e}");
619 RebootReason::InvalidFdt
620 })?;
621
Jiyong Park6a8789a2023-03-21 14:50:59 +0900622 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
623 error!("Failed to read num cpus from DT: {e}");
624 RebootReason::InvalidFdt
625 })?;
626 validate_num_cpus(num_cpus)?;
627
628 let pci_info = read_pci_info_from(fdt).map_err(|e| {
629 error!("Failed to read pci info from DT: {e}");
630 RebootReason::InvalidFdt
631 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900632 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900633
634 let serial_info = read_serial_info_from(fdt).map_err(|e| {
635 error!("Failed to read serial info from DT: {e}");
636 RebootReason::InvalidFdt
637 })?;
638
639 let swiotlb_info = read_swiotlb_info_from(fdt).map_err(|e| {
640 error!("Failed to read swiotlb info from DT: {e}");
641 RebootReason::InvalidFdt
642 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700643 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900644
Jiyong Park00ceff32023-03-13 05:43:23 +0000645 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900646 kernel_range,
647 initrd_range,
648 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900649 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900650 num_cpus,
651 pci_info,
652 serial_info,
653 swiotlb_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000654 })
655}
656
Jiyong Park9c63cd12023-03-21 17:53:07 +0900657fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900658 fdt.unpack().map_err(|e| {
659 error!("Failed to unpack DT for patching: {e}");
660 RebootReason::InvalidFdt
661 })?;
662
Jiyong Park9c63cd12023-03-21 17:53:07 +0900663 if let Some(initrd_range) = &info.initrd_range {
664 patch_initrd_range(fdt, initrd_range).map_err(|e| {
665 error!("Failed to patch initrd range to DT: {e}");
666 RebootReason::InvalidFdt
667 })?;
668 }
669 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
670 error!("Failed to patch memory range to DT: {e}");
671 RebootReason::InvalidFdt
672 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900673 if let Some(bootargs) = &info.bootargs {
674 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
675 error!("Failed to patch bootargs to DT: {e}");
676 RebootReason::InvalidFdt
677 })?;
678 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900679 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
680 error!("Failed to patch cpus to DT: {e}");
681 RebootReason::InvalidFdt
682 })?;
683 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
684 error!("Failed to patch pci info to DT: {e}");
685 RebootReason::InvalidFdt
686 })?;
687 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
688 error!("Failed to patch serial info to DT: {e}");
689 RebootReason::InvalidFdt
690 })?;
691 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
692 error!("Failed to patch swiotlb info to DT: {e}");
693 RebootReason::InvalidFdt
694 })?;
695 patch_gic(fdt, info.num_cpus).map_err(|e| {
696 error!("Failed to patch gic info to DT: {e}");
697 RebootReason::InvalidFdt
698 })?;
699 patch_timer(fdt, info.num_cpus).map_err(|e| {
700 error!("Failed to patch timer info to DT: {e}");
701 RebootReason::InvalidFdt
702 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900703
704 fdt.pack().map_err(|e| {
705 error!("Failed to pack DT after patching: {e}");
706 RebootReason::InvalidFdt
707 })?;
708
Jiyong Park9c63cd12023-03-21 17:53:07 +0900709 Ok(())
710}
711
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000712/// Modifies the input DT according to the fields of the configuration.
713pub fn modify_for_next_stage(
714 fdt: &mut Fdt,
715 bcc: &[u8],
716 new_instance: bool,
717 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900718 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900719 debuggable: bool,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000720) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000721 if let Some(debug_policy) = debug_policy {
722 let backup = Vec::from(fdt.as_slice());
723 fdt.unpack()?;
724 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
725 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
726 info!("Debug policy applied.");
727 } else {
728 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
729 fdt.unpack()?;
730 }
731 } else {
732 info!("No debug policy found.");
733 fdt.unpack()?;
734 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000735
Jiyong Parke9d87e82023-03-21 19:28:40 +0900736 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000737
Jiyong Parkb87f3302023-03-21 10:03:11 +0900738 set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?;
739 set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000740
Jiyong Park32f37ef2023-05-17 16:15:58 +0900741 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900742 if let Some(bootargs) = read_bootargs_from(fdt)? {
743 filter_out_dangerous_bootargs(fdt, &bootargs)?;
744 }
745 }
746
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000747 fdt.pack()?;
748
749 Ok(())
750}
751
Jiyong Parke9d87e82023-03-21 19:28:40 +0900752/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
753fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000754 // We reject DTs with missing reserved-memory node as validation should have checked that the
755 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900756 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000757
Jiyong Parke9d87e82023-03-21 19:28:40 +0900758 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000759
Jiyong Parke9d87e82023-03-21 19:28:40 +0900760 let addr: u64 = addr.try_into().unwrap();
761 let size: u64 = size.try_into().unwrap();
762 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000763}
764
765fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> {
766 // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node.
767 let mut chosen = fdt.chosen_mut()?.unwrap();
768 if value {
769 chosen.setprop_empty(flag)?;
770 } else {
771 match chosen.delprop(flag) {
772 Ok(()) | Err(FdtError::NotFound) => (),
773 Err(e) => return Err(e),
774 }
775 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000776
777 Ok(())
778}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900779
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000780/// Apply the debug policy overlay to the guest DT.
781///
782/// 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 +0000783fn apply_debug_policy(
784 fdt: &mut Fdt,
785 backup_fdt: &Fdt,
786 debug_policy: &[u8],
787) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000788 let mut debug_policy = Vec::from(debug_policy);
789 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900790 Ok(overlay) => overlay,
791 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000792 warn!("Corrupted debug policy found: {e}. Not applying.");
793 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900794 }
795 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900796
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000797 // SAFETY - on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900798 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000799 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900800 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900801 // A successful restoration is considered success because an invalid debug policy
802 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000803 Ok(false)
804 } else {
805 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900806 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900807}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900808
809fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
810 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
811 if let Some(value) = node.getprop_u32(debug_feature_name)? {
812 return Ok(value == 1);
813 }
814 }
815 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
816}
817
818fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
819 let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?;
820 let has_console = read_common_debug_policy(fdt, cstr!("log"))?;
821
822 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
823 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
824 ("crashkernel", Box::new(|_| has_crashkernel)),
825 ("console", Box::new(|_| has_console)),
826 ];
827
828 // parse and filter out unwanted
829 let mut filtered = Vec::new();
830 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
831 info!("Invalid bootarg: {e}");
832 FdtError::BadValue
833 })? {
834 match accepted.iter().find(|&t| t.0 == arg.name()) {
835 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
836 _ => debug!("Rejected bootarg {}", arg.as_ref()),
837 }
838 }
839
840 // flatten into a new C-string
841 let mut new_bootargs = Vec::new();
842 for (i, arg) in filtered.iter().enumerate() {
843 if i != 0 {
844 new_bootargs.push(b' '); // separator
845 }
846 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
847 }
848 new_bootargs.push(b'\0');
849
850 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
851 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
852}