blob: 770fdf0d0d9e990aa61cb9a9d7b206eeb304a767 [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;
Jaewan Kim52477ae2023-11-21 21:20:52 +090018use crate::device_assignment::{DeviceAssignmentInfo, VmDtbo};
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;
Seungjae Yoo013f4c42024-01-02 13:04:19 +090022use alloc::collections::BTreeMap;
Jiyong Parke9d87e82023-03-21 19:28:40 +090023use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090024use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090025use core::cmp::max;
26use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000027use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000028use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090029use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000031use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000032use fdtpci::PciMemoryFlags;
33use fdtpci::PciRangeType;
34use libfdt::AddressRange;
35use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000036use libfdt::Fdt;
37use libfdt::FdtError;
Jiyong Park9c63cd12023-03-21 17:53:07 +090038use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000039use libfdt::FdtNodeMut;
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;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000043use log::warn;
Jiyong Park00ceff32023-03-13 05:43:23 +000044use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000045use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000046use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000047use vmbase::memory::SIZE_4KB;
48use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000049use vmbase::util::RangeExt as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000050
Alice Wangabc7d632023-06-14 09:10:14 +000051/// An enumeration of errors that can occur during the FDT validation.
52#[derive(Clone, Debug)]
53pub enum FdtValidationError {
54 /// Invalid CPU count.
55 InvalidCpuCount(usize),
56}
57
58impl fmt::Display for FdtValidationError {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 match self {
61 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
62 }
63 }
64}
65
Jiyong Park6a8789a2023-03-21 14:50:59 +090066/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
67/// not an error.
68fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090069 let addr = cstr!("kernel-address");
70 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000071
Jiyong Parkb87f3302023-03-21 10:03:11 +090072 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000073 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
74 let addr = addr as usize;
75 let size = size as usize;
76
77 return Ok(Some(addr..(addr + size)));
78 }
79 }
80
81 Ok(None)
82}
83
Jiyong Park6a8789a2023-03-21 14:50:59 +090084/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
85/// error as there can be initrd-less VM.
86fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090087 let start = cstr!("linux,initrd-start");
88 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000089
90 if let Some(chosen) = fdt.chosen()? {
91 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
92 return Ok(Some((start as usize)..(end as usize)));
93 }
94 }
95
96 Ok(None)
97}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000098
Jiyong Park9c63cd12023-03-21 17:53:07 +090099fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
100 let start = u32::try_from(initrd_range.start).unwrap();
101 let end = u32::try_from(initrd_range.end).unwrap();
102
103 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
104 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
105 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
106 Ok(())
107}
108
Jiyong Parke9d87e82023-03-21 19:28:40 +0900109fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
110 if let Some(chosen) = fdt.chosen()? {
111 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
112 // We need to copy the string to heap because the original fdt will be invalidated
113 // by the templated DT
114 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
115 return Ok(Some(copy));
116 }
117 }
118 Ok(None)
119}
120
121fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
122 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900123 // This function is called before the verification is done. So, we just copy the bootargs to
124 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
125 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900126 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
127}
128
Alice Wang0d527472023-06-13 14:55:38 +0000129/// Reads and validates the memory range in the DT.
130///
131/// Only one memory range is expected with the crosvm setup for now.
132fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
133 let mut memory = fdt.memory().map_err(|e| {
134 error!("Failed to read memory range from DT: {e}");
135 RebootReason::InvalidFdt
136 })?;
137 let range = memory.next().ok_or_else(|| {
138 error!("The /memory node in the DT contains no range.");
139 RebootReason::InvalidFdt
140 })?;
141 if memory.next().is_some() {
142 warn!(
143 "The /memory node in the DT contains more than one memory range, \
144 while only one is expected."
145 );
146 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900147 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000148 if base != MEM_START {
149 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000150 return Err(RebootReason::InvalidFdt);
151 }
152
Jiyong Park6a8789a2023-03-21 14:50:59 +0900153 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000154 if size % GUEST_PAGE_SIZE != 0 {
155 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
156 return Err(RebootReason::InvalidFdt);
157 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000158
Jiyong Park6a8789a2023-03-21 14:50:59 +0900159 if size == 0 {
160 error!("Memory size is 0");
161 return Err(RebootReason::InvalidFdt);
162 }
Alice Wang0d527472023-06-13 14:55:38 +0000163 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000164}
165
Jiyong Park9c63cd12023-03-21 17:53:07 +0900166fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
167 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900168 fdt.node_mut(cstr!("/memory"))?
169 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000170 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900171}
172
Jiyong Park6a8789a2023-03-21 14:50:59 +0900173/// Read the number of CPUs from DT
174fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
175 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
176}
177
178/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000179fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
180 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
181 Err(FdtValidationError::InvalidCpuCount(num_cpus))
182 } else {
183 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900184 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900185}
186
187/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
188fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
189 let cpu = cstr!("arm,arm-v8");
190 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
191 for _ in 0..num_cpus {
192 next = if let Some(current) = next {
193 current.next_compatible(cpu)?
194 } else {
195 return Err(FdtError::NoSpace);
196 };
197 }
198 while let Some(current) = next {
199 next = current.delete_and_next_compatible(cpu)?;
200 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900201 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000202}
203
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900204/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900205fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900206 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900207 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900208 for property in avf_node.properties()? {
209 let name = property.name()?;
210 let value = property.value()?;
211 property_map.insert(
212 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
213 value.to_vec(),
214 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900215 }
216 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900217 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900218}
219
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900220/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
221/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
222fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900223 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900224 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900225 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900226) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900227 let mut root_vm_dt = vm_dt.root_mut()?;
228 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900229 // TODO(b/318431677): Validate nodes beyond /avf.
230 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900231 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900232 if let Some(ref_value) = avf_node.getprop(name)? {
233 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900234 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900235 "Property mismatches while applying overlay VM reference DT. \
236 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
237 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900238 );
239 return Err(FdtError::BadValue);
240 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900241 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900242 }
243 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900244 Ok(())
245}
246
Jiyong Park00ceff32023-03-13 05:43:23 +0000247#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000248struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900249 ranges: [PciAddrRange; 2],
250 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
251 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000252}
253
Jiyong Park6a8789a2023-03-21 14:50:59 +0900254impl PciInfo {
255 const IRQ_MASK_CELLS: usize = 4;
256 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100257 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000258}
259
Jiyong Park6a8789a2023-03-21 14:50:59 +0900260type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
261type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
262type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000263
264/// Iterator that takes N cells as a chunk
265struct CellChunkIterator<'a, const N: usize> {
266 cells: CellIterator<'a>,
267}
268
269impl<'a, const N: usize> CellChunkIterator<'a, N> {
270 fn new(cells: CellIterator<'a>) -> Self {
271 Self { cells }
272 }
273}
274
275impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
276 type Item = [u32; N];
277 fn next(&mut self) -> Option<Self::Item> {
278 let mut ret: Self::Item = [0; N];
279 for i in ret.iter_mut() {
280 *i = self.cells.next()?;
281 }
282 Some(ret)
283 }
284}
285
Jiyong Park6a8789a2023-03-21 14:50:59 +0900286/// Read pci host controller ranges, irq maps, and irq map masks from DT
287fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
288 let node =
289 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
290
291 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
292 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
293 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
294
295 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000296 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
297 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
298
299 if chunks.next().is_some() {
300 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
301 return Err(FdtError::NoSpace);
302 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900303
304 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000305 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
306 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
307
308 if chunks.next().is_some() {
309 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
310 return Err(FdtError::NoSpace);
311 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900312
313 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
314}
315
Jiyong Park0ee65392023-03-27 20:52:45 +0900316fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900317 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900318 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900319 }
320 for irq_mask in pci_info.irq_masks.iter() {
321 validate_pci_irq_mask(irq_mask)?;
322 }
323 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
324 validate_pci_irq_map(irq_map, idx)?;
325 }
326 Ok(())
327}
328
Jiyong Park0ee65392023-03-27 20:52:45 +0900329fn validate_pci_addr_range(
330 range: &PciAddrRange,
331 memory_range: &Range<usize>,
332) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900333 let mem_flags = PciMemoryFlags(range.addr.0);
334 let range_type = mem_flags.range_type();
335 let prefetchable = mem_flags.prefetchable();
336 let bus_addr = range.addr.1;
337 let cpu_addr = range.parent_addr;
338 let size = range.size;
339
340 if range_type != PciRangeType::Memory64 {
341 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
342 return Err(RebootReason::InvalidFdt);
343 }
344 if prefetchable {
345 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
346 return Err(RebootReason::InvalidFdt);
347 }
348 // Enforce ID bus-to-cpu mappings, as used by crosvm.
349 if bus_addr != cpu_addr {
350 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
351 return Err(RebootReason::InvalidFdt);
352 }
353
Jiyong Park0ee65392023-03-27 20:52:45 +0900354 let Some(bus_end) = bus_addr.checked_add(size) else {
355 error!("PCI address range size {:#x} overflows", size);
356 return Err(RebootReason::InvalidFdt);
357 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000358 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900359 error!("PCI address end {:#x} is outside of translatable range", bus_end);
360 return Err(RebootReason::InvalidFdt);
361 }
362
363 let memory_start = memory_range.start.try_into().unwrap();
364 let memory_end = memory_range.end.try_into().unwrap();
365
366 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
367 error!(
368 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
369 bus_addr, bus_end, memory_start, memory_end
370 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900371 return Err(RebootReason::InvalidFdt);
372 }
373
374 Ok(())
375}
376
377fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000378 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
379 const IRQ_MASK_ADDR_ME: u32 = 0x0;
380 const IRQ_MASK_ADDR_LO: u32 = 0x0;
381 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900382 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000383 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900384 if *irq_mask != EXPECTED {
385 error!("Invalid PCI irq mask {:#?}", irq_mask);
386 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000387 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900388 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000389}
390
Jiyong Park6a8789a2023-03-21 14:50:59 +0900391fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000392 const PCI_DEVICE_IDX: usize = 11;
393 const PCI_IRQ_ADDR_ME: u32 = 0;
394 const PCI_IRQ_ADDR_LO: u32 = 0;
395 const PCI_IRQ_INTC: u32 = 1;
396 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
397 const GIC_SPI: u32 = 0;
398 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
399
Jiyong Park6a8789a2023-03-21 14:50:59 +0900400 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
401 let pci_irq_number = irq_map[3];
402 let _controller_phandle = irq_map[4]; // skipped.
403 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
404 // interrupt-cells is <3> for GIC
405 let gic_peripheral_interrupt_type = irq_map[7];
406 let gic_irq_number = irq_map[8];
407 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000408
Jiyong Park6a8789a2023-03-21 14:50:59 +0900409 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
410 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000411
Jiyong Park6a8789a2023-03-21 14:50:59 +0900412 if pci_addr != expected_pci_addr {
413 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
414 {:#x} {:#x} {:#x}",
415 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
416 return Err(RebootReason::InvalidFdt);
417 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000418
Jiyong Park6a8789a2023-03-21 14:50:59 +0900419 if pci_irq_number != PCI_IRQ_INTC {
420 error!(
421 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
422 pci_irq_number, PCI_IRQ_INTC
423 );
424 return Err(RebootReason::InvalidFdt);
425 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000426
Jiyong Park6a8789a2023-03-21 14:50:59 +0900427 if gic_addr != (0, 0) {
428 error!(
429 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
430 {:#x} {:#x}",
431 gic_addr.0, gic_addr.1, 0, 0
432 );
433 return Err(RebootReason::InvalidFdt);
434 }
435
436 if gic_peripheral_interrupt_type != GIC_SPI {
437 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
438 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
439 return Err(RebootReason::InvalidFdt);
440 }
441
442 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
443 if gic_irq_number != irq_nr {
444 error!(
445 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
446 gic_irq_number, irq_nr
447 );
448 return Err(RebootReason::InvalidFdt);
449 }
450
451 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
452 error!(
453 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
454 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
455 );
456 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000457 }
458 Ok(())
459}
460
Jiyong Park9c63cd12023-03-21 17:53:07 +0900461fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
462 let mut node = fdt
463 .root_mut()?
464 .next_compatible(cstr!("pci-host-cam-generic"))?
465 .ok_or(FdtError::NotFound)?;
466
467 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
468 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
469
470 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
471 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
472
473 node.setprop_inplace(
474 cstr!("ranges"),
475 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
476 )
477}
478
Jiyong Park00ceff32023-03-13 05:43:23 +0000479#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900480struct SerialInfo {
481 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000482}
483
484impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900485 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000486}
487
Jiyong Park6a8789a2023-03-21 14:50:59 +0900488fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
489 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
490 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000491 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900492 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000493 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900494 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000495}
496
Jiyong Park9c63cd12023-03-21 17:53:07 +0900497/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
498fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
499 let name = cstr!("ns16550a");
500 let mut next = fdt.root_mut()?.next_compatible(name);
501 while let Some(current) = next? {
502 let reg = FdtNode::from_mut(&current)
503 .reg()?
504 .ok_or(FdtError::NotFound)?
505 .next()
506 .ok_or(FdtError::NotFound)?;
507 next = if !serial_info.addrs.contains(&reg.addr) {
508 current.delete_and_next_compatible(name)
509 } else {
510 current.next_compatible(name)
511 }
512 }
513 Ok(())
514}
515
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700516fn validate_swiotlb_info(
517 swiotlb_info: &SwiotlbInfo,
518 memory: &Range<usize>,
519) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900520 let size = swiotlb_info.size;
521 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000522
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700523 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000524 error!("Invalid swiotlb size {:#x}", size);
525 return Err(RebootReason::InvalidFdt);
526 }
527
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000528 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000529 error!("Invalid swiotlb alignment {:#x}", align);
530 return Err(RebootReason::InvalidFdt);
531 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700532
Alice Wang9cfbfd62023-06-14 11:19:03 +0000533 if let Some(addr) = swiotlb_info.addr {
534 if addr.checked_add(size).is_none() {
535 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
536 return Err(RebootReason::InvalidFdt);
537 }
538 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700539 if let Some(range) = swiotlb_info.fixed_range() {
540 if !range.is_within(memory) {
541 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
542 return Err(RebootReason::InvalidFdt);
543 }
544 }
545
Jiyong Park6a8789a2023-03-21 14:50:59 +0900546 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000547}
548
Jiyong Park9c63cd12023-03-21 17:53:07 +0900549fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
550 let mut node =
551 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700552
553 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000554 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700555 cstr!("reg"),
556 range.start.try_into().unwrap(),
557 range.len().try_into().unwrap(),
558 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000559 node.nop_property(cstr!("size"))?;
560 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700561 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000562 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700563 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000564 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700565 }
566
Jiyong Park9c63cd12023-03-21 17:53:07 +0900567 Ok(())
568}
569
570fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
571 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
572 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
573 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
574 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
575
576 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000577 // `validate_num_cpus()` checked that this wouldn't panic
578 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900579
580 // range1 is just below range0
581 range1.addr = addr - size;
582 range1.size = Some(size);
583
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000584 let (addr0, size0) = range0.to_cells();
585 let (addr1, size1) = range1.to_cells();
586 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900587
588 let mut node =
589 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
590 node.setprop_inplace(cstr!("reg"), flatten(&value))
591}
592
593fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
594 const NUM_INTERRUPTS: usize = 4;
595 const CELLS_PER_INTERRUPT: usize = 3;
596 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
597 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
598 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
599 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
600
601 let num_cpus: u32 = num_cpus.try_into().unwrap();
602 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
603 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
604 *v |= cpu_mask;
605 }
606 for v in value.iter_mut() {
607 *v = v.to_be();
608 }
609
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100610 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900611 let value = unsafe {
612 core::mem::transmute::<
613 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
614 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
615 >(value.into_inner())
616 };
617
618 let mut node =
619 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
620 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
621}
622
Jiyong Park00ceff32023-03-13 05:43:23 +0000623#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900624pub struct DeviceTreeInfo {
625 pub kernel_range: Option<Range<usize>>,
626 pub initrd_range: Option<Range<usize>>,
627 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900628 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900629 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000630 pci_info: PciInfo,
631 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700632 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900633 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900634 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000635}
636
637impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000638 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
639 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
640
641 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
642 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000643}
644
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900645pub fn sanitize_device_tree(
646 fdt: &mut [u8],
647 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900648 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900649) -> Result<DeviceTreeInfo, RebootReason> {
650 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
651 error!("Failed to load FDT: {e}");
652 RebootReason::InvalidFdt
653 })?;
654
655 let vm_dtbo = match vm_dtbo {
656 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
657 error!("Failed to load VM DTBO: {e}");
658 RebootReason::InvalidFdt
659 })?),
660 None => None,
661 };
662
663 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900664
Jiyong Parke9d87e82023-03-21 19:28:40 +0900665 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
666 error!("Failed to instantiate FDT from the template DT: {e}");
667 RebootReason::InvalidFdt
668 })?;
669
Jaewan Kim9220e852023-12-01 10:58:40 +0900670 fdt.unpack().map_err(|e| {
671 error!("Failed to unpack DT for patching: {e}");
672 RebootReason::InvalidFdt
673 })?;
674
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900675 if let Some(device_assignment_info) = &info.device_assignment {
676 let vm_dtbo = vm_dtbo.unwrap();
677 device_assignment_info.filter(vm_dtbo).map_err(|e| {
678 error!("Failed to filter VM DTBO: {e}");
679 RebootReason::InvalidFdt
680 })?;
681 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
682 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
683 // it can only be instantiated after validation.
684 unsafe {
685 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
686 error!("Failed to apply filtered VM DTBO: {e}");
687 RebootReason::InvalidFdt
688 })?;
689 }
690 }
691
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900692 if let Some(vm_ref_dt) = vm_ref_dt {
693 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
694 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900695 RebootReason::InvalidFdt
696 })?;
697
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900698 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
699 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900700 RebootReason::InvalidFdt
701 })?;
702 }
703
Jiyong Park9c63cd12023-03-21 17:53:07 +0900704 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900705
Jaewan Kim19b984f2023-12-04 15:16:50 +0900706 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
707
Jaewan Kim9220e852023-12-01 10:58:40 +0900708 fdt.pack().map_err(|e| {
709 error!("Failed to unpack DT after patching: {e}");
710 RebootReason::InvalidFdt
711 })?;
712
Jiyong Park6a8789a2023-03-21 14:50:59 +0900713 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900714}
715
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900716fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900717 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
718 error!("Failed to read kernel range from DT: {e}");
719 RebootReason::InvalidFdt
720 })?;
721
722 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
723 error!("Failed to read initrd range from DT: {e}");
724 RebootReason::InvalidFdt
725 })?;
726
Alice Wang0d527472023-06-13 14:55:38 +0000727 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900728
Jiyong Parke9d87e82023-03-21 19:28:40 +0900729 let bootargs = read_bootargs_from(fdt).map_err(|e| {
730 error!("Failed to read bootargs from DT: {e}");
731 RebootReason::InvalidFdt
732 })?;
733
Jiyong Park6a8789a2023-03-21 14:50:59 +0900734 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
735 error!("Failed to read num cpus from DT: {e}");
736 RebootReason::InvalidFdt
737 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000738 validate_num_cpus(num_cpus).map_err(|e| {
739 error!("Failed to validate num cpus from DT: {e}");
740 RebootReason::InvalidFdt
741 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900742
743 let pci_info = read_pci_info_from(fdt).map_err(|e| {
744 error!("Failed to read pci info from DT: {e}");
745 RebootReason::InvalidFdt
746 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900747 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900748
749 let serial_info = read_serial_info_from(fdt).map_err(|e| {
750 error!("Failed to read serial info from DT: {e}");
751 RebootReason::InvalidFdt
752 })?;
753
Alice Wang9cfbfd62023-06-14 11:19:03 +0000754 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900755 error!("Failed to read swiotlb info from DT: {e}");
756 RebootReason::InvalidFdt
757 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700758 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900759
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900760 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900761 Some(vm_dtbo) => {
762 if let Some(hypervisor) = hyp::get_device_assigner() {
763 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
764 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
765 RebootReason::InvalidFdt
766 })?
767 } else {
768 warn!(
769 "Device assignment is ignored because device assigning hypervisor is missing"
770 );
771 None
772 }
773 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900774 None => None,
775 };
776
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900777 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900778 error!("Failed to read names of properties under /avf from DT: {e}");
779 RebootReason::InvalidFdt
780 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900781
Jiyong Park00ceff32023-03-13 05:43:23 +0000782 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900783 kernel_range,
784 initrd_range,
785 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900786 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900787 num_cpus,
788 pci_info,
789 serial_info,
790 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900791 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900792 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000793 })
794}
795
Jiyong Park9c63cd12023-03-21 17:53:07 +0900796fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
797 if let Some(initrd_range) = &info.initrd_range {
798 patch_initrd_range(fdt, initrd_range).map_err(|e| {
799 error!("Failed to patch initrd range to DT: {e}");
800 RebootReason::InvalidFdt
801 })?;
802 }
803 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
804 error!("Failed to patch memory range to DT: {e}");
805 RebootReason::InvalidFdt
806 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900807 if let Some(bootargs) = &info.bootargs {
808 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
809 error!("Failed to patch bootargs to DT: {e}");
810 RebootReason::InvalidFdt
811 })?;
812 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900813 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
814 error!("Failed to patch cpus to DT: {e}");
815 RebootReason::InvalidFdt
816 })?;
817 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
818 error!("Failed to patch pci info to DT: {e}");
819 RebootReason::InvalidFdt
820 })?;
821 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
822 error!("Failed to patch serial info to DT: {e}");
823 RebootReason::InvalidFdt
824 })?;
825 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
826 error!("Failed to patch swiotlb info to DT: {e}");
827 RebootReason::InvalidFdt
828 })?;
829 patch_gic(fdt, info.num_cpus).map_err(|e| {
830 error!("Failed to patch gic info to DT: {e}");
831 RebootReason::InvalidFdt
832 })?;
833 patch_timer(fdt, info.num_cpus).map_err(|e| {
834 error!("Failed to patch timer info to DT: {e}");
835 RebootReason::InvalidFdt
836 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900837 if let Some(device_assignment) = &info.device_assignment {
838 // Note: We patch values after VM DTBO is overlaid because patch may require more space
839 // then VM DTBO's underlying slice is allocated.
840 device_assignment.patch(fdt).map_err(|e| {
841 error!("Failed to patch device assignment info to DT: {e}");
842 RebootReason::InvalidFdt
843 })?;
844 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900845
Jiyong Park9c63cd12023-03-21 17:53:07 +0900846 Ok(())
847}
848
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000849/// Modifies the input DT according to the fields of the configuration.
850pub fn modify_for_next_stage(
851 fdt: &mut Fdt,
852 bcc: &[u8],
853 new_instance: bool,
854 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000855 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900856 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000857 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000858) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000859 if let Some(debug_policy) = debug_policy {
860 let backup = Vec::from(fdt.as_slice());
861 fdt.unpack()?;
862 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
863 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
864 info!("Debug policy applied.");
865 } else {
866 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
867 fdt.unpack()?;
868 }
869 } else {
870 info!("No debug policy found.");
871 fdt.unpack()?;
872 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000873
Jiyong Parke9d87e82023-03-21 19:28:40 +0900874 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000875
Alice Wang56ec45b2023-06-15 08:30:32 +0000876 if let Some(mut chosen) = fdt.chosen_mut()? {
877 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
878 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000879 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000880 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900881 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900882 if let Some(bootargs) = read_bootargs_from(fdt)? {
883 filter_out_dangerous_bootargs(fdt, &bootargs)?;
884 }
885 }
886
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000887 fdt.pack()?;
888
889 Ok(())
890}
891
Jiyong Parke9d87e82023-03-21 19:28:40 +0900892/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
893fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000894 // We reject DTs with missing reserved-memory node as validation should have checked that the
895 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900896 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000897
Jiyong Parke9d87e82023-03-21 19:28:40 +0900898 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000899
Jiyong Parke9d87e82023-03-21 19:28:40 +0900900 let addr: u64 = addr.try_into().unwrap();
901 let size: u64 = size.try_into().unwrap();
902 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000903}
904
Alice Wang56ec45b2023-06-15 08:30:32 +0000905fn empty_or_delete_prop(
906 fdt_node: &mut FdtNodeMut,
907 prop_name: &CStr,
908 keep_prop: bool,
909) -> libfdt::Result<()> {
910 if keep_prop {
911 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000912 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000913 fdt_node
914 .delprop(prop_name)
915 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000916 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000917}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900918
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000919/// Apply the debug policy overlay to the guest DT.
920///
921/// 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 +0000922fn apply_debug_policy(
923 fdt: &mut Fdt,
924 backup_fdt: &Fdt,
925 debug_policy: &[u8],
926) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000927 let mut debug_policy = Vec::from(debug_policy);
928 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900929 Ok(overlay) => overlay,
930 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000931 warn!("Corrupted debug policy found: {e}. Not applying.");
932 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900933 }
934 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900935
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100936 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900937 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000938 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900939 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900940 // A successful restoration is considered success because an invalid debug policy
941 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000942 Ok(false)
943 } else {
944 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900945 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900946}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900947
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000948fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900949 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
950 if let Some(value) = node.getprop_u32(debug_feature_name)? {
951 return Ok(value == 1);
952 }
953 }
954 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
955}
956
957fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000958 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
959 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900960
961 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
962 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
963 ("crashkernel", Box::new(|_| has_crashkernel)),
964 ("console", Box::new(|_| has_console)),
965 ];
966
967 // parse and filter out unwanted
968 let mut filtered = Vec::new();
969 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
970 info!("Invalid bootarg: {e}");
971 FdtError::BadValue
972 })? {
973 match accepted.iter().find(|&t| t.0 == arg.name()) {
974 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
975 _ => debug!("Rejected bootarg {}", arg.as_ref()),
976 }
977 }
978
979 // flatten into a new C-string
980 let mut new_bootargs = Vec::new();
981 for (i, arg) in filtered.iter().enumerate() {
982 if i != 0 {
983 new_bootargs.push(b' '); // separator
984 }
985 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
986 }
987 new_bootargs.push(b'\0');
988
989 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
990 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
991}