• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 
17 use crate::bootargs::BootArgsIterator;
18 use crate::cstr;
19 use crate::helpers::flatten;
20 use crate::helpers::RangeExt;
21 use crate::helpers::GUEST_PAGE_SIZE;
22 use crate::helpers::SIZE_4KB;
23 use crate::memory::BASE_ADDR;
24 use crate::memory::MAX_ADDR;
25 use crate::Box;
26 use crate::RebootReason;
27 use alloc::ffi::CString;
28 use alloc::vec::Vec;
29 use core::cmp::max;
30 use core::cmp::min;
31 use core::ffi::CStr;
32 use core::mem::size_of;
33 use core::ops::Range;
34 use fdtpci::PciMemoryFlags;
35 use fdtpci::PciRangeType;
36 use libfdt::AddressRange;
37 use libfdt::CellIterator;
38 use libfdt::Fdt;
39 use libfdt::FdtError;
40 use libfdt::FdtNode;
41 use log::debug;
42 use log::error;
43 use log::info;
44 use log::warn;
45 use tinyvec::ArrayVec;
46 
47 /// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
48 /// not an error.
read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>>49 fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
50     let addr = cstr!("kernel-address");
51     let size = cstr!("kernel-size");
52 
53     if let Some(config) = fdt.node(cstr!("/config"))? {
54         if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
55             let addr = addr as usize;
56             let size = size as usize;
57 
58             return Ok(Some(addr..(addr + size)));
59         }
60     }
61 
62     Ok(None)
63 }
64 
65 /// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
66 /// error as there can be initrd-less VM.
read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>>67 fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
68     let start = cstr!("linux,initrd-start");
69     let end = cstr!("linux,initrd-end");
70 
71     if let Some(chosen) = fdt.chosen()? {
72         if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
73             return Ok(Some((start as usize)..(end as usize)));
74         }
75     }
76 
77     Ok(None)
78 }
79 
patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()>80 fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
81     let start = u32::try_from(initrd_range.start).unwrap();
82     let end = u32::try_from(initrd_range.end).unwrap();
83 
84     let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
85     node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
86     node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
87     Ok(())
88 }
89 
read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>>90 fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
91     if let Some(chosen) = fdt.chosen()? {
92         if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
93             // We need to copy the string to heap because the original fdt will be invalidated
94             // by the templated DT
95             let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
96             return Ok(Some(copy));
97         }
98     }
99     Ok(None)
100 }
101 
patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()>102 fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
103     let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
104     // This function is called before the verification is done. So, we just copy the bootargs to
105     // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
106     // if the VM is not debuggable.
107     node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
108 }
109 
110 /// Read the first range in /memory node in DT
read_memory_range_from(fdt: &Fdt) -> libfdt::Result<Range<usize>>111 fn read_memory_range_from(fdt: &Fdt) -> libfdt::Result<Range<usize>> {
112     fdt.memory()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
113 }
114 
115 /// Check if memory range is ok
validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason>116 fn validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason> {
117     let base = range.start;
118     if base != BASE_ADDR {
119         error!("Memory base address {:#x} is not {:#x}", base, BASE_ADDR);
120         return Err(RebootReason::InvalidFdt);
121     }
122 
123     let size = range.len();
124     if size % GUEST_PAGE_SIZE != 0 {
125         error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
126         return Err(RebootReason::InvalidFdt);
127     }
128 
129     if size == 0 {
130         error!("Memory size is 0");
131         return Err(RebootReason::InvalidFdt);
132     }
133     Ok(())
134 }
135 
patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()>136 fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
137     let size = memory_range.len() as u64;
138     fdt.node_mut(cstr!("/memory"))?
139         .ok_or(FdtError::NotFound)?
140         .setprop_inplace(cstr!("reg"), flatten(&[BASE_ADDR.to_be_bytes(), size.to_be_bytes()]))
141 }
142 
143 /// Read the number of CPUs from DT
read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize>144 fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
145     Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
146 }
147 
148 /// Validate number of CPUs
validate_num_cpus(num_cpus: usize) -> Result<(), RebootReason>149 fn validate_num_cpus(num_cpus: usize) -> Result<(), RebootReason> {
150     if num_cpus == 0 {
151         error!("Number of CPU can't be 0");
152         return Err(RebootReason::InvalidFdt);
153     }
154     if DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).is_none() {
155         error!("Too many CPUs for gic: {}", num_cpus);
156         return Err(RebootReason::InvalidFdt);
157     }
158     Ok(())
159 }
160 
161 /// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()>162 fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
163     let cpu = cstr!("arm,arm-v8");
164     let mut next = fdt.root_mut()?.next_compatible(cpu)?;
165     for _ in 0..num_cpus {
166         next = if let Some(current) = next {
167             current.next_compatible(cpu)?
168         } else {
169             return Err(FdtError::NoSpace);
170         };
171     }
172     while let Some(current) = next {
173         next = current.delete_and_next_compatible(cpu)?;
174     }
175     Ok(())
176 }
177 
178 #[derive(Debug)]
179 struct PciInfo {
180     ranges: [PciAddrRange; 2],
181     irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
182     irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
183 }
184 
185 impl PciInfo {
186     const IRQ_MASK_CELLS: usize = 4;
187     const IRQ_MAP_CELLS: usize = 10;
188     const MAX_IRQS: usize = 8;
189 }
190 
191 type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
192 type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
193 type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
194 
195 /// Iterator that takes N cells as a chunk
196 struct CellChunkIterator<'a, const N: usize> {
197     cells: CellIterator<'a>,
198 }
199 
200 impl<'a, const N: usize> CellChunkIterator<'a, N> {
new(cells: CellIterator<'a>) -> Self201     fn new(cells: CellIterator<'a>) -> Self {
202         Self { cells }
203     }
204 }
205 
206 impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
207     type Item = [u32; N];
next(&mut self) -> Option<Self::Item>208     fn next(&mut self) -> Option<Self::Item> {
209         let mut ret: Self::Item = [0; N];
210         for i in ret.iter_mut() {
211             *i = self.cells.next()?;
212         }
213         Some(ret)
214     }
215 }
216 
217 /// Read pci host controller ranges, irq maps, and irq map masks from DT
read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo>218 fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
219     let node =
220         fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
221 
222     let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
223     let range0 = ranges.next().ok_or(FdtError::NotFound)?;
224     let range1 = ranges.next().ok_or(FdtError::NotFound)?;
225 
226     let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
227     let irq_masks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
228     let irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]> =
229         irq_masks.take(PciInfo::MAX_IRQS).collect();
230 
231     let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
232     let irq_maps = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
233     let irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]> =
234         irq_maps.take(PciInfo::MAX_IRQS).collect();
235 
236     Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
237 }
238 
validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason>239 fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
240     for range in pci_info.ranges.iter() {
241         validate_pci_addr_range(range, memory_range)?;
242     }
243     for irq_mask in pci_info.irq_masks.iter() {
244         validate_pci_irq_mask(irq_mask)?;
245     }
246     for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
247         validate_pci_irq_map(irq_map, idx)?;
248     }
249     Ok(())
250 }
251 
validate_pci_addr_range( range: &PciAddrRange, memory_range: &Range<usize>, ) -> Result<(), RebootReason>252 fn validate_pci_addr_range(
253     range: &PciAddrRange,
254     memory_range: &Range<usize>,
255 ) -> Result<(), RebootReason> {
256     let mem_flags = PciMemoryFlags(range.addr.0);
257     let range_type = mem_flags.range_type();
258     let prefetchable = mem_flags.prefetchable();
259     let bus_addr = range.addr.1;
260     let cpu_addr = range.parent_addr;
261     let size = range.size;
262 
263     if range_type != PciRangeType::Memory64 {
264         error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
265         return Err(RebootReason::InvalidFdt);
266     }
267     if prefetchable {
268         error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
269         return Err(RebootReason::InvalidFdt);
270     }
271     // Enforce ID bus-to-cpu mappings, as used by crosvm.
272     if bus_addr != cpu_addr {
273         error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
274         return Err(RebootReason::InvalidFdt);
275     }
276 
277     let Some(bus_end) = bus_addr.checked_add(size) else {
278         error!("PCI address range size {:#x} overflows", size);
279         return Err(RebootReason::InvalidFdt);
280     };
281     if bus_end > MAX_ADDR.try_into().unwrap() {
282         error!("PCI address end {:#x} is outside of translatable range", bus_end);
283         return Err(RebootReason::InvalidFdt);
284     }
285 
286     let memory_start = memory_range.start.try_into().unwrap();
287     let memory_end = memory_range.end.try_into().unwrap();
288 
289     if max(bus_addr, memory_start) < min(bus_end, memory_end) {
290         error!(
291             "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
292             bus_addr, bus_end, memory_start, memory_end
293         );
294         return Err(RebootReason::InvalidFdt);
295     }
296 
297     Ok(())
298 }
299 
validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason>300 fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
301     const IRQ_MASK_ADDR_HI: u32 = 0xf800;
302     const IRQ_MASK_ADDR_ME: u32 = 0x0;
303     const IRQ_MASK_ADDR_LO: u32 = 0x0;
304     const IRQ_MASK_ANY_IRQ: u32 = 0x7;
305     const EXPECTED: PciIrqMask =
306         [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
307     if *irq_mask != EXPECTED {
308         error!("Invalid PCI irq mask {:#?}", irq_mask);
309         return Err(RebootReason::InvalidFdt);
310     }
311     Ok(())
312 }
313 
validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason>314 fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
315     const PCI_DEVICE_IDX: usize = 11;
316     const PCI_IRQ_ADDR_ME: u32 = 0;
317     const PCI_IRQ_ADDR_LO: u32 = 0;
318     const PCI_IRQ_INTC: u32 = 1;
319     const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
320     const GIC_SPI: u32 = 0;
321     const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
322 
323     let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
324     let pci_irq_number = irq_map[3];
325     let _controller_phandle = irq_map[4]; // skipped.
326     let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
327                                              // interrupt-cells is <3> for GIC
328     let gic_peripheral_interrupt_type = irq_map[7];
329     let gic_irq_number = irq_map[8];
330     let gic_irq_type = irq_map[9];
331 
332     let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
333     let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
334 
335     if pci_addr != expected_pci_addr {
336         error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
337                {:#x} {:#x} {:#x}",
338                pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
339         return Err(RebootReason::InvalidFdt);
340     }
341 
342     if pci_irq_number != PCI_IRQ_INTC {
343         error!(
344             "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
345             pci_irq_number, PCI_IRQ_INTC
346         );
347         return Err(RebootReason::InvalidFdt);
348     }
349 
350     if gic_addr != (0, 0) {
351         error!(
352             "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
353                {:#x} {:#x}",
354             gic_addr.0, gic_addr.1, 0, 0
355         );
356         return Err(RebootReason::InvalidFdt);
357     }
358 
359     if gic_peripheral_interrupt_type != GIC_SPI {
360         error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
361                {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
362         return Err(RebootReason::InvalidFdt);
363     }
364 
365     let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
366     if gic_irq_number != irq_nr {
367         error!(
368             "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
369             gic_irq_number, irq_nr
370         );
371         return Err(RebootReason::InvalidFdt);
372     }
373 
374     if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
375         error!(
376             "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
377             gic_irq_type, IRQ_TYPE_LEVEL_HIGH
378         );
379         return Err(RebootReason::InvalidFdt);
380     }
381     Ok(())
382 }
383 
patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()>384 fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
385     let mut node = fdt
386         .root_mut()?
387         .next_compatible(cstr!("pci-host-cam-generic"))?
388         .ok_or(FdtError::NotFound)?;
389 
390     let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
391     node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
392 
393     let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
394     node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
395 
396     node.setprop_inplace(
397         cstr!("ranges"),
398         flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
399     )
400 }
401 
402 #[derive(Default, Debug)]
403 struct SerialInfo {
404     addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
405 }
406 
407 impl SerialInfo {
408     const MAX_SERIALS: usize = 4;
409 }
410 
read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo>411 fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
412     let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
413     for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
414         let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
415         addrs.push(reg.addr);
416     }
417     Ok(SerialInfo { addrs })
418 }
419 
420 /// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()>421 fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
422     let name = cstr!("ns16550a");
423     let mut next = fdt.root_mut()?.next_compatible(name);
424     while let Some(current) = next? {
425         let reg = FdtNode::from_mut(&current)
426             .reg()?
427             .ok_or(FdtError::NotFound)?
428             .next()
429             .ok_or(FdtError::NotFound)?;
430         next = if !serial_info.addrs.contains(&reg.addr) {
431             current.delete_and_next_compatible(name)
432         } else {
433             current.next_compatible(name)
434         }
435     }
436     Ok(())
437 }
438 
439 #[derive(Debug)]
440 pub struct SwiotlbInfo {
441     addr: Option<usize>,
442     size: usize,
443     align: usize,
444 }
445 
446 impl SwiotlbInfo {
fixed_range(&self) -> Option<Range<usize>>447     pub fn fixed_range(&self) -> Option<Range<usize>> {
448         self.addr.map(|addr| addr..addr + self.size)
449     }
450 }
451 
read_swiotlb_info_from(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo>452 fn read_swiotlb_info_from(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo> {
453     let node =
454         fdt.compatible_nodes(cstr!("restricted-dma-pool"))?.next().ok_or(FdtError::NotFound)?;
455     let align =
456         node.getprop_u64(cstr!("alignment"))?.ok_or(FdtError::NotFound)?.try_into().unwrap();
457 
458     let (addr, size) = if let Some(mut reg) = node.reg()? {
459         let reg = reg.next().ok_or(FdtError::NotFound)?;
460         let size = reg.size.ok_or(FdtError::NotFound)?;
461         reg.addr.checked_add(size).ok_or(FdtError::BadValue)?;
462         (Some(reg.addr.try_into().unwrap()), size.try_into().unwrap())
463     } else {
464         let size = node.getprop_u64(cstr!("size"))?.ok_or(FdtError::NotFound)?.try_into().unwrap();
465         (None, size)
466     };
467 
468     Ok(SwiotlbInfo { addr, size, align })
469 }
470 
validate_swiotlb_info( swiotlb_info: &SwiotlbInfo, memory: &Range<usize>, ) -> Result<(), RebootReason>471 fn validate_swiotlb_info(
472     swiotlb_info: &SwiotlbInfo,
473     memory: &Range<usize>,
474 ) -> Result<(), RebootReason> {
475     let size = swiotlb_info.size;
476     let align = swiotlb_info.align;
477 
478     if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
479         error!("Invalid swiotlb size {:#x}", size);
480         return Err(RebootReason::InvalidFdt);
481     }
482 
483     if (align % GUEST_PAGE_SIZE) != 0 {
484         error!("Invalid swiotlb alignment {:#x}", align);
485         return Err(RebootReason::InvalidFdt);
486     }
487 
488     if let Some(range) = swiotlb_info.fixed_range() {
489         if !range.is_within(memory) {
490             error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
491             return Err(RebootReason::InvalidFdt);
492         }
493     }
494 
495     Ok(())
496 }
497 
patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()>498 fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
499     let mut node =
500         fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
501     node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.to_be_bytes())?;
502 
503     if let Some(range) = swiotlb_info.fixed_range() {
504         node.appendprop_addrrange(
505             cstr!("reg"),
506             range.start.try_into().unwrap(),
507             range.len().try_into().unwrap(),
508         )?;
509     } else {
510         node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
511     }
512 
513     Ok(())
514 }
515 
patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()>516 fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
517     let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
518     let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
519     let range0 = ranges.next().ok_or(FdtError::NotFound)?;
520     let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
521 
522     let addr = range0.addr;
523     // SAFETY - doesn't overflow. checked in validate_num_cpus
524     let size: u64 =
525         DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).unwrap();
526 
527     // range1 is just below range0
528     range1.addr = addr - size;
529     range1.size = Some(size);
530 
531     let range0 = range0.to_cells();
532     let range1 = range1.to_cells();
533     let value = [
534         range0.0,          // addr
535         range0.1.unwrap(), //size
536         range1.0,          // addr
537         range1.1.unwrap(), //size
538     ];
539 
540     let mut node =
541         fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
542     node.setprop_inplace(cstr!("reg"), flatten(&value))
543 }
544 
patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()>545 fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
546     const NUM_INTERRUPTS: usize = 4;
547     const CELLS_PER_INTERRUPT: usize = 3;
548     let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
549     let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
550     let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
551         interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
552 
553     let num_cpus: u32 = num_cpus.try_into().unwrap();
554     let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
555     for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
556         *v |= cpu_mask;
557     }
558     for v in value.iter_mut() {
559         *v = v.to_be();
560     }
561 
562     // SAFETY - array size is the same
563     let value = unsafe {
564         core::mem::transmute::<
565             [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
566             [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
567         >(value.into_inner())
568     };
569 
570     let mut node =
571         fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
572     node.setprop_inplace(cstr!("interrupts"), value.as_slice())
573 }
574 
575 #[derive(Debug)]
576 pub struct DeviceTreeInfo {
577     pub kernel_range: Option<Range<usize>>,
578     pub initrd_range: Option<Range<usize>>,
579     pub memory_range: Range<usize>,
580     bootargs: Option<CString>,
581     num_cpus: usize,
582     pci_info: PciInfo,
583     serial_info: SerialInfo,
584     pub swiotlb_info: SwiotlbInfo,
585 }
586 
587 impl DeviceTreeInfo {
588     const GIC_REDIST_SIZE_PER_CPU: u64 = (32 * SIZE_4KB) as u64;
589 }
590 
sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason>591 pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> {
592     let info = parse_device_tree(fdt)?;
593     debug!("Device tree info: {:?}", info);
594 
595     fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
596         error!("Failed to instantiate FDT from the template DT: {e}");
597         RebootReason::InvalidFdt
598     })?;
599 
600     patch_device_tree(fdt, &info)?;
601     Ok(info)
602 }
603 
parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason>604 fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> {
605     let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
606         error!("Failed to read kernel range from DT: {e}");
607         RebootReason::InvalidFdt
608     })?;
609 
610     let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
611         error!("Failed to read initrd range from DT: {e}");
612         RebootReason::InvalidFdt
613     })?;
614 
615     let memory_range = read_memory_range_from(fdt).map_err(|e| {
616         error!("Failed to read memory range from DT: {e}");
617         RebootReason::InvalidFdt
618     })?;
619     validate_memory_range(&memory_range)?;
620 
621     let bootargs = read_bootargs_from(fdt).map_err(|e| {
622         error!("Failed to read bootargs from DT: {e}");
623         RebootReason::InvalidFdt
624     })?;
625 
626     let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
627         error!("Failed to read num cpus from DT: {e}");
628         RebootReason::InvalidFdt
629     })?;
630     validate_num_cpus(num_cpus)?;
631 
632     let pci_info = read_pci_info_from(fdt).map_err(|e| {
633         error!("Failed to read pci info from DT: {e}");
634         RebootReason::InvalidFdt
635     })?;
636     validate_pci_info(&pci_info, &memory_range)?;
637 
638     let serial_info = read_serial_info_from(fdt).map_err(|e| {
639         error!("Failed to read serial info from DT: {e}");
640         RebootReason::InvalidFdt
641     })?;
642 
643     let swiotlb_info = read_swiotlb_info_from(fdt).map_err(|e| {
644         error!("Failed to read swiotlb info from DT: {e}");
645         RebootReason::InvalidFdt
646     })?;
647     validate_swiotlb_info(&swiotlb_info, &memory_range)?;
648 
649     Ok(DeviceTreeInfo {
650         kernel_range,
651         initrd_range,
652         memory_range,
653         bootargs,
654         num_cpus,
655         pci_info,
656         serial_info,
657         swiotlb_info,
658     })
659 }
660 
patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason>661 fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
662     fdt.unpack().map_err(|e| {
663         error!("Failed to unpack DT for patching: {e}");
664         RebootReason::InvalidFdt
665     })?;
666 
667     if let Some(initrd_range) = &info.initrd_range {
668         patch_initrd_range(fdt, initrd_range).map_err(|e| {
669             error!("Failed to patch initrd range to DT: {e}");
670             RebootReason::InvalidFdt
671         })?;
672     }
673     patch_memory_range(fdt, &info.memory_range).map_err(|e| {
674         error!("Failed to patch memory range to DT: {e}");
675         RebootReason::InvalidFdt
676     })?;
677     if let Some(bootargs) = &info.bootargs {
678         patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
679             error!("Failed to patch bootargs to DT: {e}");
680             RebootReason::InvalidFdt
681         })?;
682     }
683     patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
684         error!("Failed to patch cpus to DT: {e}");
685         RebootReason::InvalidFdt
686     })?;
687     patch_pci_info(fdt, &info.pci_info).map_err(|e| {
688         error!("Failed to patch pci info to DT: {e}");
689         RebootReason::InvalidFdt
690     })?;
691     patch_serial_info(fdt, &info.serial_info).map_err(|e| {
692         error!("Failed to patch serial info to DT: {e}");
693         RebootReason::InvalidFdt
694     })?;
695     patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
696         error!("Failed to patch swiotlb info to DT: {e}");
697         RebootReason::InvalidFdt
698     })?;
699     patch_gic(fdt, info.num_cpus).map_err(|e| {
700         error!("Failed to patch gic info to DT: {e}");
701         RebootReason::InvalidFdt
702     })?;
703     patch_timer(fdt, info.num_cpus).map_err(|e| {
704         error!("Failed to patch timer info to DT: {e}");
705         RebootReason::InvalidFdt
706     })?;
707 
708     fdt.pack().map_err(|e| {
709         error!("Failed to pack DT after patching: {e}");
710         RebootReason::InvalidFdt
711     })?;
712 
713     Ok(())
714 }
715 
716 /// Modifies the input DT according to the fields of the configuration.
modify_for_next_stage( fdt: &mut Fdt, bcc: &[u8], new_instance: bool, strict_boot: bool, debug_policy: Option<&mut [u8]>, debuggable: bool, kaslr_seed: u64, ) -> libfdt::Result<()>717 pub fn modify_for_next_stage(
718     fdt: &mut Fdt,
719     bcc: &[u8],
720     new_instance: bool,
721     strict_boot: bool,
722     debug_policy: Option<&mut [u8]>,
723     debuggable: bool,
724     kaslr_seed: u64,
725 ) -> libfdt::Result<()> {
726     if let Some(debug_policy) = debug_policy {
727         let backup = Vec::from(fdt.as_slice());
728         fdt.unpack()?;
729         let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
730         if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
731             info!("Debug policy applied.");
732         } else {
733             // apply_debug_policy restored fdt to backup_fdt so unpack it again.
734             fdt.unpack()?;
735         }
736     } else {
737         info!("No debug policy found.");
738         fdt.unpack()?;
739     }
740 
741     patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
742 
743     set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?;
744     set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?;
745     fdt.chosen_mut()?.unwrap().setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
746 
747     if !debuggable {
748         if let Some(bootargs) = read_bootargs_from(fdt)? {
749             filter_out_dangerous_bootargs(fdt, &bootargs)?;
750         }
751     }
752 
753     fdt.pack()?;
754 
755     Ok(())
756 }
757 
758 /// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()>759 fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
760     // We reject DTs with missing reserved-memory node as validation should have checked that the
761     // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
762     let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
763 
764     let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
765 
766     let addr: u64 = addr.try_into().unwrap();
767     let size: u64 = size.try_into().unwrap();
768     node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
769 }
770 
set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()>771 fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> {
772     // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node.
773     let mut chosen = fdt.chosen_mut()?.unwrap();
774     if value {
775         chosen.setprop_empty(flag)?;
776     } else {
777         match chosen.delprop(flag) {
778             Ok(()) | Err(FdtError::NotFound) => (),
779             Err(e) => return Err(e),
780         }
781     }
782 
783     Ok(())
784 }
785 
786 /// Apply the debug policy overlay to the guest DT.
787 ///
788 /// Returns Ok(true) on success, Ok(false) on recovered failure and Err(_) on corruption of the DT.
apply_debug_policy( fdt: &mut Fdt, backup_fdt: &Fdt, debug_policy: &[u8], ) -> libfdt::Result<bool>789 fn apply_debug_policy(
790     fdt: &mut Fdt,
791     backup_fdt: &Fdt,
792     debug_policy: &[u8],
793 ) -> libfdt::Result<bool> {
794     let mut debug_policy = Vec::from(debug_policy);
795     let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
796         Ok(overlay) => overlay,
797         Err(e) => {
798             warn!("Corrupted debug policy found: {e}. Not applying.");
799             return Ok(false);
800         }
801     };
802 
803     // SAFETY - on failure, the corrupted DT is restored using the backup.
804     if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
805         warn!("Failed to apply debug policy: {e}. Recovering...");
806         fdt.copy_from_slice(backup_fdt.as_slice())?;
807         // A successful restoration is considered success because an invalid debug policy
808         // shouldn't DOS the pvmfw
809         Ok(false)
810     } else {
811         Ok(true)
812     }
813 }
814 
read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool>815 fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
816     if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
817         if let Some(value) = node.getprop_u32(debug_feature_name)? {
818             return Ok(value == 1);
819         }
820     }
821     Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
822 }
823 
filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()>824 fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
825     let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?;
826     let has_console = read_common_debug_policy(fdt, cstr!("log"))?;
827 
828     let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
829         ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
830         ("crashkernel", Box::new(|_| has_crashkernel)),
831         ("console", Box::new(|_| has_console)),
832     ];
833 
834     // parse and filter out unwanted
835     let mut filtered = Vec::new();
836     for arg in BootArgsIterator::new(bootargs).map_err(|e| {
837         info!("Invalid bootarg: {e}");
838         FdtError::BadValue
839     })? {
840         match accepted.iter().find(|&t| t.0 == arg.name()) {
841             Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
842             _ => debug!("Rejected bootarg {}", arg.as_ref()),
843         }
844     }
845 
846     // flatten into a new C-string
847     let mut new_bootargs = Vec::new();
848     for (i, arg) in filtered.iter().enumerate() {
849         if i != 0 {
850             new_bootargs.push(b' '); // separator
851         }
852         new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
853     }
854     new_bootargs.push(b'\0');
855 
856     let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
857     node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
858 }
859