blob: c68fc6ddba5ccfe2cfa12cbce6d4496228e12b92 [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 Park9c63cd12023-03-21 17:53:07 +090019use crate::helpers::flatten;
Jiyong Park00ceff32023-03-13 05:43:23 +000020use crate::helpers::GUEST_PAGE_SIZE;
Jiyong Park9c63cd12023-03-21 17:53:07 +090021use crate::helpers::SIZE_4KB;
Jiyong Park0ee65392023-03-27 20:52:45 +090022use crate::memory::BASE_ADDR;
23use crate::memory::MAX_ADDR;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +090024use crate::Box;
Jiyong Park00ceff32023-03-13 05:43:23 +000025use crate::RebootReason;
Jiyong Parke9d87e82023-03-21 19:28:40 +090026use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090027use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090028use core::cmp::max;
29use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::ffi::CStr;
Jiyong Park9c63cd12023-03-21 17:53:07 +090031use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000032use core::ops::Range;
Jiyong Park00ceff32023-03-13 05:43:23 +000033use fdtpci::PciMemoryFlags;
34use fdtpci::PciRangeType;
35use libfdt::AddressRange;
36use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000037use libfdt::Fdt;
38use libfdt::FdtError;
Jiyong Park9c63cd12023-03-21 17:53:07 +090039use libfdt::FdtNode;
Jiyong Park83316122023-03-21 09:39:39 +090040use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000041use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090042use log::info;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000044
Jiyong Park6a8789a2023-03-21 14:50:59 +090045/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
46/// not an error.
47fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090048 let addr = cstr!("kernel-address");
49 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000050
Jiyong Parkb87f3302023-03-21 10:03:11 +090051 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000052 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
53 let addr = addr as usize;
54 let size = size as usize;
55
56 return Ok(Some(addr..(addr + size)));
57 }
58 }
59
60 Ok(None)
61}
62
Jiyong Park6a8789a2023-03-21 14:50:59 +090063/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
64/// error as there can be initrd-less VM.
65fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090066 let start = cstr!("linux,initrd-start");
67 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000068
69 if let Some(chosen) = fdt.chosen()? {
70 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
71 return Ok(Some((start as usize)..(end as usize)));
72 }
73 }
74
75 Ok(None)
76}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000077
Jiyong Park9c63cd12023-03-21 17:53:07 +090078fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
79 let start = u32::try_from(initrd_range.start).unwrap();
80 let end = u32::try_from(initrd_range.end).unwrap();
81
82 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
83 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
84 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
85 Ok(())
86}
87
Jiyong Parke9d87e82023-03-21 19:28:40 +090088fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
89 if let Some(chosen) = fdt.chosen()? {
90 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
91 // We need to copy the string to heap because the original fdt will be invalidated
92 // by the templated DT
93 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
94 return Ok(Some(copy));
95 }
96 }
97 Ok(None)
98}
99
100fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
101 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900102 // This function is called before the verification is done. So, we just copy the bootargs to
103 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
104 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900105 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
106}
107
Jiyong Park6a8789a2023-03-21 14:50:59 +0900108/// Read the first range in /memory node in DT
109fn read_memory_range_from(fdt: &Fdt) -> libfdt::Result<Range<usize>> {
110 fdt.memory()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
111}
Jiyong Park00ceff32023-03-13 05:43:23 +0000112
Jiyong Park6a8789a2023-03-21 14:50:59 +0900113/// Check if memory range is ok
114fn validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason> {
115 let base = range.start;
Jiyong Park0ee65392023-03-27 20:52:45 +0900116 if base != BASE_ADDR {
117 error!("Memory base address {:#x} is not {:#x}", base, BASE_ADDR);
Jiyong Park00ceff32023-03-13 05:43:23 +0000118 return Err(RebootReason::InvalidFdt);
119 }
120
Jiyong Park6a8789a2023-03-21 14:50:59 +0900121 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000122 if size % GUEST_PAGE_SIZE != 0 {
123 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
124 return Err(RebootReason::InvalidFdt);
125 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000126
Jiyong Park6a8789a2023-03-21 14:50:59 +0900127 if size == 0 {
128 error!("Memory size is 0");
129 return Err(RebootReason::InvalidFdt);
130 }
131 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000132}
133
Jiyong Park9c63cd12023-03-21 17:53:07 +0900134fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
135 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900136 fdt.node_mut(cstr!("/memory"))?
137 .ok_or(FdtError::NotFound)?
138 .setprop_inplace(cstr!("reg"), flatten(&[BASE_ADDR.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900139}
140
Jiyong Park6a8789a2023-03-21 14:50:59 +0900141/// Read the number of CPUs from DT
142fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
143 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
144}
145
146/// Validate number of CPUs
147fn validate_num_cpus(num_cpus: usize) -> Result<(), RebootReason> {
148 if num_cpus == 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000149 error!("Number of CPU can't be 0");
Jiyong Park6a8789a2023-03-21 14:50:59 +0900150 return Err(RebootReason::InvalidFdt);
151 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900152 if DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).is_none() {
153 error!("Too many CPUs for gic: {}", num_cpus);
154 return Err(RebootReason::InvalidFdt);
155 }
156 Ok(())
157}
158
159/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
160fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
161 let cpu = cstr!("arm,arm-v8");
162 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
163 for _ in 0..num_cpus {
164 next = if let Some(current) = next {
165 current.next_compatible(cpu)?
166 } else {
167 return Err(FdtError::NoSpace);
168 };
169 }
170 while let Some(current) = next {
171 next = current.delete_and_next_compatible(cpu)?;
172 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900173 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000174}
175
176#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000177struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900178 ranges: [PciAddrRange; 2],
179 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
180 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000181}
182
Jiyong Park6a8789a2023-03-21 14:50:59 +0900183impl PciInfo {
184 const IRQ_MASK_CELLS: usize = 4;
185 const IRQ_MAP_CELLS: usize = 10;
186 const MAX_IRQS: usize = 8;
Jiyong Park00ceff32023-03-13 05:43:23 +0000187}
188
Jiyong Park6a8789a2023-03-21 14:50:59 +0900189type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
190type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
191type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000192
193/// Iterator that takes N cells as a chunk
194struct CellChunkIterator<'a, const N: usize> {
195 cells: CellIterator<'a>,
196}
197
198impl<'a, const N: usize> CellChunkIterator<'a, N> {
199 fn new(cells: CellIterator<'a>) -> Self {
200 Self { cells }
201 }
202}
203
204impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
205 type Item = [u32; N];
206 fn next(&mut self) -> Option<Self::Item> {
207 let mut ret: Self::Item = [0; N];
208 for i in ret.iter_mut() {
209 *i = self.cells.next()?;
210 }
211 Some(ret)
212 }
213}
214
Jiyong Park6a8789a2023-03-21 14:50:59 +0900215/// Read pci host controller ranges, irq maps, and irq map masks from DT
216fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
217 let node =
218 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
219
220 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
221 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
222 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
223
224 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
225 let irq_masks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
226 let irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]> =
227 irq_masks.take(PciInfo::MAX_IRQS).collect();
228
229 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
230 let irq_maps = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
231 let irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]> =
232 irq_maps.take(PciInfo::MAX_IRQS).collect();
233
234 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
235}
236
Jiyong Park0ee65392023-03-27 20:52:45 +0900237fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900238 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900239 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900240 }
241 for irq_mask in pci_info.irq_masks.iter() {
242 validate_pci_irq_mask(irq_mask)?;
243 }
244 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
245 validate_pci_irq_map(irq_map, idx)?;
246 }
247 Ok(())
248}
249
Jiyong Park0ee65392023-03-27 20:52:45 +0900250fn validate_pci_addr_range(
251 range: &PciAddrRange,
252 memory_range: &Range<usize>,
253) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900254 let mem_flags = PciMemoryFlags(range.addr.0);
255 let range_type = mem_flags.range_type();
256 let prefetchable = mem_flags.prefetchable();
257 let bus_addr = range.addr.1;
258 let cpu_addr = range.parent_addr;
259 let size = range.size;
260
261 if range_type != PciRangeType::Memory64 {
262 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
263 return Err(RebootReason::InvalidFdt);
264 }
265 if prefetchable {
266 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
267 return Err(RebootReason::InvalidFdt);
268 }
269 // Enforce ID bus-to-cpu mappings, as used by crosvm.
270 if bus_addr != cpu_addr {
271 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
272 return Err(RebootReason::InvalidFdt);
273 }
274
Jiyong Park0ee65392023-03-27 20:52:45 +0900275 let Some(bus_end) = bus_addr.checked_add(size) else {
276 error!("PCI address range size {:#x} overflows", size);
277 return Err(RebootReason::InvalidFdt);
278 };
279 if bus_end > MAX_ADDR.try_into().unwrap() {
280 error!("PCI address end {:#x} is outside of translatable range", bus_end);
281 return Err(RebootReason::InvalidFdt);
282 }
283
284 let memory_start = memory_range.start.try_into().unwrap();
285 let memory_end = memory_range.end.try_into().unwrap();
286
287 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
288 error!(
289 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
290 bus_addr, bus_end, memory_start, memory_end
291 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900292 return Err(RebootReason::InvalidFdt);
293 }
294
295 Ok(())
296}
297
298fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000299 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
300 const IRQ_MASK_ADDR_ME: u32 = 0x0;
301 const IRQ_MASK_ADDR_LO: u32 = 0x0;
302 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900303 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000304 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900305 if *irq_mask != EXPECTED {
306 error!("Invalid PCI irq mask {:#?}", irq_mask);
307 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000308 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900309 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000310}
311
Jiyong Park6a8789a2023-03-21 14:50:59 +0900312fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000313 const PCI_DEVICE_IDX: usize = 11;
314 const PCI_IRQ_ADDR_ME: u32 = 0;
315 const PCI_IRQ_ADDR_LO: u32 = 0;
316 const PCI_IRQ_INTC: u32 = 1;
317 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
318 const GIC_SPI: u32 = 0;
319 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
320
Jiyong Park6a8789a2023-03-21 14:50:59 +0900321 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
322 let pci_irq_number = irq_map[3];
323 let _controller_phandle = irq_map[4]; // skipped.
324 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
325 // interrupt-cells is <3> for GIC
326 let gic_peripheral_interrupt_type = irq_map[7];
327 let gic_irq_number = irq_map[8];
328 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000329
Jiyong Park6a8789a2023-03-21 14:50:59 +0900330 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
331 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000332
Jiyong Park6a8789a2023-03-21 14:50:59 +0900333 if pci_addr != expected_pci_addr {
334 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
335 {:#x} {:#x} {:#x}",
336 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
337 return Err(RebootReason::InvalidFdt);
338 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000339
Jiyong Park6a8789a2023-03-21 14:50:59 +0900340 if pci_irq_number != PCI_IRQ_INTC {
341 error!(
342 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
343 pci_irq_number, PCI_IRQ_INTC
344 );
345 return Err(RebootReason::InvalidFdt);
346 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000347
Jiyong Park6a8789a2023-03-21 14:50:59 +0900348 if gic_addr != (0, 0) {
349 error!(
350 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
351 {:#x} {:#x}",
352 gic_addr.0, gic_addr.1, 0, 0
353 );
354 return Err(RebootReason::InvalidFdt);
355 }
356
357 if gic_peripheral_interrupt_type != GIC_SPI {
358 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
359 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
360 return Err(RebootReason::InvalidFdt);
361 }
362
363 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
364 if gic_irq_number != irq_nr {
365 error!(
366 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
367 gic_irq_number, irq_nr
368 );
369 return Err(RebootReason::InvalidFdt);
370 }
371
372 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
373 error!(
374 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
375 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
376 );
377 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000378 }
379 Ok(())
380}
381
Jiyong Park9c63cd12023-03-21 17:53:07 +0900382fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
383 let mut node = fdt
384 .root_mut()?
385 .next_compatible(cstr!("pci-host-cam-generic"))?
386 .ok_or(FdtError::NotFound)?;
387
388 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
389 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
390
391 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
392 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
393
394 node.setprop_inplace(
395 cstr!("ranges"),
396 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
397 )
398}
399
Jiyong Park00ceff32023-03-13 05:43:23 +0000400#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900401struct SerialInfo {
402 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000403}
404
405impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900406 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000407}
408
Jiyong Park6a8789a2023-03-21 14:50:59 +0900409fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
410 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
411 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
412 let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
413 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000414 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900415 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000416}
417
Jiyong Park9c63cd12023-03-21 17:53:07 +0900418/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
419fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
420 let name = cstr!("ns16550a");
421 let mut next = fdt.root_mut()?.next_compatible(name);
422 while let Some(current) = next? {
423 let reg = FdtNode::from_mut(&current)
424 .reg()?
425 .ok_or(FdtError::NotFound)?
426 .next()
427 .ok_or(FdtError::NotFound)?;
428 next = if !serial_info.addrs.contains(&reg.addr) {
429 current.delete_and_next_compatible(name)
430 } else {
431 current.next_compatible(name)
432 }
433 }
434 Ok(())
435}
436
Jiyong Park00ceff32023-03-13 05:43:23 +0000437#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900438struct SwiotlbInfo {
Jiyong Park00ceff32023-03-13 05:43:23 +0000439 size: u64,
440 align: u64,
441}
442
Jiyong Park6a8789a2023-03-21 14:50:59 +0900443fn read_swiotlb_info_from(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo> {
444 let node =
445 fdt.compatible_nodes(cstr!("restricted-dma-pool"))?.next().ok_or(FdtError::NotFound)?;
446 let size = node.getprop_u64(cstr!("size"))?.ok_or(FdtError::NotFound)?;
447 let align = node.getprop_u64(cstr!("alignment"))?.ok_or(FdtError::NotFound)?;
448 Ok(SwiotlbInfo { size, align })
449}
Jiyong Park00ceff32023-03-13 05:43:23 +0000450
Jiyong Park6a8789a2023-03-21 14:50:59 +0900451fn validate_swiotlb_info(swiotlb_info: &SwiotlbInfo) -> Result<(), RebootReason> {
452 let size = swiotlb_info.size;
453 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000454
455 if size == 0 || (size % GUEST_PAGE_SIZE as u64) != 0 {
456 error!("Invalid swiotlb size {:#x}", size);
457 return Err(RebootReason::InvalidFdt);
458 }
459
460 if (align % GUEST_PAGE_SIZE as u64) != 0 {
461 error!("Invalid swiotlb alignment {:#x}", align);
462 return Err(RebootReason::InvalidFdt);
463 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900464 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000465}
466
Jiyong Park9c63cd12023-03-21 17:53:07 +0900467fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
468 let mut node =
469 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
470 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
471 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.to_be_bytes())?;
472 Ok(())
473}
474
475fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
476 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
477 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
478 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
479 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
480
481 let addr = range0.addr;
482 // SAFETY - doesn't overflow. checked in validate_num_cpus
483 let size: u64 =
484 DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).unwrap();
485
486 // range1 is just below range0
487 range1.addr = addr - size;
488 range1.size = Some(size);
489
490 let range0 = range0.to_cells();
491 let range1 = range1.to_cells();
492 let value = [
493 range0.0, // addr
494 range0.1.unwrap(), //size
495 range1.0, // addr
496 range1.1.unwrap(), //size
497 ];
498
499 let mut node =
500 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
501 node.setprop_inplace(cstr!("reg"), flatten(&value))
502}
503
504fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
505 const NUM_INTERRUPTS: usize = 4;
506 const CELLS_PER_INTERRUPT: usize = 3;
507 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
508 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
509 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
510 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
511
512 let num_cpus: u32 = num_cpus.try_into().unwrap();
513 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
514 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
515 *v |= cpu_mask;
516 }
517 for v in value.iter_mut() {
518 *v = v.to_be();
519 }
520
521 // SAFETY - array size is the same
522 let value = unsafe {
523 core::mem::transmute::<
524 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
525 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
526 >(value.into_inner())
527 };
528
529 let mut node =
530 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
531 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
532}
533
Jiyong Park00ceff32023-03-13 05:43:23 +0000534#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900535pub struct DeviceTreeInfo {
536 pub kernel_range: Option<Range<usize>>,
537 pub initrd_range: Option<Range<usize>>,
538 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900539 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900540 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000541 pci_info: PciInfo,
542 serial_info: SerialInfo,
543 swiotlb_info: SwiotlbInfo,
544}
545
546impl DeviceTreeInfo {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900547 const GIC_REDIST_SIZE_PER_CPU: u64 = (32 * SIZE_4KB) as u64;
Jiyong Park00ceff32023-03-13 05:43:23 +0000548}
549
Jiyong Park9c63cd12023-03-21 17:53:07 +0900550pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park83316122023-03-21 09:39:39 +0900551 let info = parse_device_tree(fdt)?;
552 debug!("Device tree info: {:?}", info);
553
Jiyong Parke9d87e82023-03-21 19:28:40 +0900554 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
555 error!("Failed to instantiate FDT from the template DT: {e}");
556 RebootReason::InvalidFdt
557 })?;
558
Jiyong Park9c63cd12023-03-21 17:53:07 +0900559 patch_device_tree(fdt, &info)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900560 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900561}
562
563fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900564 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
565 error!("Failed to read kernel range from DT: {e}");
566 RebootReason::InvalidFdt
567 })?;
568
569 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
570 error!("Failed to read initrd range from DT: {e}");
571 RebootReason::InvalidFdt
572 })?;
573
574 let memory_range = read_memory_range_from(fdt).map_err(|e| {
575 error!("Failed to read memory range from DT: {e}");
576 RebootReason::InvalidFdt
577 })?;
578 validate_memory_range(&memory_range)?;
579
Jiyong Parke9d87e82023-03-21 19:28:40 +0900580 let bootargs = read_bootargs_from(fdt).map_err(|e| {
581 error!("Failed to read bootargs from DT: {e}");
582 RebootReason::InvalidFdt
583 })?;
584
Jiyong Park6a8789a2023-03-21 14:50:59 +0900585 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
586 error!("Failed to read num cpus from DT: {e}");
587 RebootReason::InvalidFdt
588 })?;
589 validate_num_cpus(num_cpus)?;
590
591 let pci_info = read_pci_info_from(fdt).map_err(|e| {
592 error!("Failed to read pci info from DT: {e}");
593 RebootReason::InvalidFdt
594 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900595 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900596
597 let serial_info = read_serial_info_from(fdt).map_err(|e| {
598 error!("Failed to read serial info from DT: {e}");
599 RebootReason::InvalidFdt
600 })?;
601
602 let swiotlb_info = read_swiotlb_info_from(fdt).map_err(|e| {
603 error!("Failed to read swiotlb info from DT: {e}");
604 RebootReason::InvalidFdt
605 })?;
606 validate_swiotlb_info(&swiotlb_info)?;
607
Jiyong Park00ceff32023-03-13 05:43:23 +0000608 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900609 kernel_range,
610 initrd_range,
611 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900612 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900613 num_cpus,
614 pci_info,
615 serial_info,
616 swiotlb_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000617 })
618}
619
Jiyong Park9c63cd12023-03-21 17:53:07 +0900620fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900621 fdt.unpack().map_err(|e| {
622 error!("Failed to unpack DT for patching: {e}");
623 RebootReason::InvalidFdt
624 })?;
625
Jiyong Park9c63cd12023-03-21 17:53:07 +0900626 if let Some(initrd_range) = &info.initrd_range {
627 patch_initrd_range(fdt, initrd_range).map_err(|e| {
628 error!("Failed to patch initrd range to DT: {e}");
629 RebootReason::InvalidFdt
630 })?;
631 }
632 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
633 error!("Failed to patch memory range to DT: {e}");
634 RebootReason::InvalidFdt
635 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900636 if let Some(bootargs) = &info.bootargs {
637 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
638 error!("Failed to patch bootargs to DT: {e}");
639 RebootReason::InvalidFdt
640 })?;
641 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900642 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
643 error!("Failed to patch cpus to DT: {e}");
644 RebootReason::InvalidFdt
645 })?;
646 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
647 error!("Failed to patch pci info to DT: {e}");
648 RebootReason::InvalidFdt
649 })?;
650 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
651 error!("Failed to patch serial info to DT: {e}");
652 RebootReason::InvalidFdt
653 })?;
654 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
655 error!("Failed to patch swiotlb info to DT: {e}");
656 RebootReason::InvalidFdt
657 })?;
658 patch_gic(fdt, info.num_cpus).map_err(|e| {
659 error!("Failed to patch gic info to DT: {e}");
660 RebootReason::InvalidFdt
661 })?;
662 patch_timer(fdt, info.num_cpus).map_err(|e| {
663 error!("Failed to patch timer info to DT: {e}");
664 RebootReason::InvalidFdt
665 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900666
667 fdt.pack().map_err(|e| {
668 error!("Failed to pack DT after patching: {e}");
669 RebootReason::InvalidFdt
670 })?;
671
Jiyong Park9c63cd12023-03-21 17:53:07 +0900672 Ok(())
673}
674
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000675/// Modifies the input DT according to the fields of the configuration.
676pub fn modify_for_next_stage(
677 fdt: &mut Fdt,
678 bcc: &[u8],
679 new_instance: bool,
680 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900681 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900682 debuggable: bool,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000683) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000684 fdt.unpack()?;
685
Jiyong Parke9d87e82023-03-21 19:28:40 +0900686 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000687
Jiyong Parkb87f3302023-03-21 10:03:11 +0900688 set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?;
689 set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000690
Jiyong Parkc23426b2023-04-10 17:32:27 +0900691 if let Some(debug_policy) = debug_policy {
692 apply_debug_policy(fdt, debug_policy)?;
693 info!("Debug policy applied.");
694 } else {
695 info!("No debug policy found.");
696 }
697
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900698 if debuggable {
699 if let Some(bootargs) = read_bootargs_from(fdt)? {
700 filter_out_dangerous_bootargs(fdt, &bootargs)?;
701 }
702 }
703
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000704 fdt.pack()?;
705
706 Ok(())
707}
708
Jiyong Parke9d87e82023-03-21 19:28:40 +0900709/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
710fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000711 // We reject DTs with missing reserved-memory node as validation should have checked that the
712 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900713 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000714
Jiyong Parke9d87e82023-03-21 19:28:40 +0900715 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000716
Jiyong Parke9d87e82023-03-21 19:28:40 +0900717 let addr: u64 = addr.try_into().unwrap();
718 let size: u64 = size.try_into().unwrap();
719 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000720}
721
722fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> {
723 // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node.
724 let mut chosen = fdt.chosen_mut()?.unwrap();
725 if value {
726 chosen.setprop_empty(flag)?;
727 } else {
728 match chosen.delprop(flag) {
729 Ok(()) | Err(FdtError::NotFound) => (),
730 Err(e) => return Err(e),
731 }
732 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000733
734 Ok(())
735}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900736
737fn apply_debug_policy(fdt: &mut Fdt, debug_policy: &mut [u8]) -> libfdt::Result<()> {
738 let backup_fdt = Vec::from(fdt.as_slice());
739
740 let overlay = match Fdt::from_mut_slice(debug_policy) {
741 Ok(overlay) => overlay,
742 Err(e) => {
743 info!("Corrupted debug policy found: {e}. Not applying.");
744 return Ok(());
745 }
746 };
747 let backup_overlay = Vec::from(overlay.as_slice());
748
749 // SAFETY - on failure, the corrupted fdts are discarded and are restored using the backups.
750 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
751 error!("Failed to apply debug policy: {e}. Recovering...");
752 fdt.copy_from_slice(backup_fdt.as_slice())?;
753 overlay.copy_from_slice(backup_overlay.as_slice())?;
754 // A successful restoration is considered success because an invalid debug policy
755 // shouldn't DOS the pvmfw
756 }
757 Ok(())
758}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900759
760fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
761 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
762 if let Some(value) = node.getprop_u32(debug_feature_name)? {
763 return Ok(value == 1);
764 }
765 }
766 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
767}
768
769fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
770 let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?;
771 let has_console = read_common_debug_policy(fdt, cstr!("log"))?;
772
773 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
774 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
775 ("crashkernel", Box::new(|_| has_crashkernel)),
776 ("console", Box::new(|_| has_console)),
777 ];
778
779 // parse and filter out unwanted
780 let mut filtered = Vec::new();
781 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
782 info!("Invalid bootarg: {e}");
783 FdtError::BadValue
784 })? {
785 match accepted.iter().find(|&t| t.0 == arg.name()) {
786 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
787 _ => debug!("Rejected bootarg {}", arg.as_ref()),
788 }
789 }
790
791 // flatten into a new C-string
792 let mut new_bootargs = Vec::new();
793 for (i, arg) in filtered.iter().enumerate() {
794 if i != 0 {
795 new_bootargs.push(b' '); // separator
796 }
797 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
798 }
799 new_bootargs.push(b'\0');
800
801 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
802 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
803}