blob: 2ea4599a0ed02b483d2f307ed7be59df9eff57ee [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
584 let range0 = range0.to_cells();
585 let range1 = range1.to_cells();
586 let value = [
587 range0.0, // addr
588 range0.1.unwrap(), //size
589 range1.0, // addr
590 range1.1.unwrap(), //size
591 ];
592
593 let mut node =
594 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
595 node.setprop_inplace(cstr!("reg"), flatten(&value))
596}
597
598fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
599 const NUM_INTERRUPTS: usize = 4;
600 const CELLS_PER_INTERRUPT: usize = 3;
601 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
602 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
603 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
604 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
605
606 let num_cpus: u32 = num_cpus.try_into().unwrap();
607 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
608 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
609 *v |= cpu_mask;
610 }
611 for v in value.iter_mut() {
612 *v = v.to_be();
613 }
614
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100615 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900616 let value = unsafe {
617 core::mem::transmute::<
618 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
619 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
620 >(value.into_inner())
621 };
622
623 let mut node =
624 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
625 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
626}
627
Jiyong Park00ceff32023-03-13 05:43:23 +0000628#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900629pub struct DeviceTreeInfo {
630 pub kernel_range: Option<Range<usize>>,
631 pub initrd_range: Option<Range<usize>>,
632 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900633 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900634 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000635 pci_info: PciInfo,
636 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700637 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900638 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900639 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000640}
641
642impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000643 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
644 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
645
646 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
647 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000648}
649
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900650pub fn sanitize_device_tree(
651 fdt: &mut [u8],
652 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900653 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900654) -> Result<DeviceTreeInfo, RebootReason> {
655 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
656 error!("Failed to load FDT: {e}");
657 RebootReason::InvalidFdt
658 })?;
659
660 let vm_dtbo = match vm_dtbo {
661 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
662 error!("Failed to load VM DTBO: {e}");
663 RebootReason::InvalidFdt
664 })?),
665 None => None,
666 };
667
668 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900669
Jiyong Parke9d87e82023-03-21 19:28:40 +0900670 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
671 error!("Failed to instantiate FDT from the template DT: {e}");
672 RebootReason::InvalidFdt
673 })?;
674
Jaewan Kim9220e852023-12-01 10:58:40 +0900675 fdt.unpack().map_err(|e| {
676 error!("Failed to unpack DT for patching: {e}");
677 RebootReason::InvalidFdt
678 })?;
679
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900680 if let Some(device_assignment_info) = &info.device_assignment {
681 let vm_dtbo = vm_dtbo.unwrap();
682 device_assignment_info.filter(vm_dtbo).map_err(|e| {
683 error!("Failed to filter VM DTBO: {e}");
684 RebootReason::InvalidFdt
685 })?;
686 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
687 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
688 // it can only be instantiated after validation.
689 unsafe {
690 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
691 error!("Failed to apply filtered VM DTBO: {e}");
692 RebootReason::InvalidFdt
693 })?;
694 }
695 }
696
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900697 if let Some(vm_ref_dt) = vm_ref_dt {
698 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
699 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900700 RebootReason::InvalidFdt
701 })?;
702
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900703 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
704 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900705 RebootReason::InvalidFdt
706 })?;
707 }
708
Jiyong Park9c63cd12023-03-21 17:53:07 +0900709 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900710
Jaewan Kim19b984f2023-12-04 15:16:50 +0900711 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
712
Jaewan Kim9220e852023-12-01 10:58:40 +0900713 fdt.pack().map_err(|e| {
714 error!("Failed to unpack DT after patching: {e}");
715 RebootReason::InvalidFdt
716 })?;
717
Jiyong Park6a8789a2023-03-21 14:50:59 +0900718 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900719}
720
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900721fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900722 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
723 error!("Failed to read kernel range from DT: {e}");
724 RebootReason::InvalidFdt
725 })?;
726
727 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
728 error!("Failed to read initrd range from DT: {e}");
729 RebootReason::InvalidFdt
730 })?;
731
Alice Wang0d527472023-06-13 14:55:38 +0000732 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900733
Jiyong Parke9d87e82023-03-21 19:28:40 +0900734 let bootargs = read_bootargs_from(fdt).map_err(|e| {
735 error!("Failed to read bootargs from DT: {e}");
736 RebootReason::InvalidFdt
737 })?;
738
Jiyong Park6a8789a2023-03-21 14:50:59 +0900739 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
740 error!("Failed to read num cpus from DT: {e}");
741 RebootReason::InvalidFdt
742 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000743 validate_num_cpus(num_cpus).map_err(|e| {
744 error!("Failed to validate num cpus from DT: {e}");
745 RebootReason::InvalidFdt
746 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900747
748 let pci_info = read_pci_info_from(fdt).map_err(|e| {
749 error!("Failed to read pci info from DT: {e}");
750 RebootReason::InvalidFdt
751 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900752 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753
754 let serial_info = read_serial_info_from(fdt).map_err(|e| {
755 error!("Failed to read serial info from DT: {e}");
756 RebootReason::InvalidFdt
757 })?;
758
Alice Wang9cfbfd62023-06-14 11:19:03 +0000759 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900760 error!("Failed to read swiotlb info from DT: {e}");
761 RebootReason::InvalidFdt
762 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700763 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900764
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900765 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900766 Some(vm_dtbo) => {
767 if let Some(hypervisor) = hyp::get_device_assigner() {
768 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
769 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
770 RebootReason::InvalidFdt
771 })?
772 } else {
773 warn!(
774 "Device assignment is ignored because device assigning hypervisor is missing"
775 );
776 None
777 }
778 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900779 None => None,
780 };
781
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900782 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900783 error!("Failed to read names of properties under /avf from DT: {e}");
784 RebootReason::InvalidFdt
785 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900786
Jiyong Park00ceff32023-03-13 05:43:23 +0000787 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900788 kernel_range,
789 initrd_range,
790 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900791 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900792 num_cpus,
793 pci_info,
794 serial_info,
795 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900796 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900797 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000798 })
799}
800
Jiyong Park9c63cd12023-03-21 17:53:07 +0900801fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
802 if let Some(initrd_range) = &info.initrd_range {
803 patch_initrd_range(fdt, initrd_range).map_err(|e| {
804 error!("Failed to patch initrd range to DT: {e}");
805 RebootReason::InvalidFdt
806 })?;
807 }
808 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
809 error!("Failed to patch memory range to DT: {e}");
810 RebootReason::InvalidFdt
811 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900812 if let Some(bootargs) = &info.bootargs {
813 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
814 error!("Failed to patch bootargs to DT: {e}");
815 RebootReason::InvalidFdt
816 })?;
817 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900818 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
819 error!("Failed to patch cpus to DT: {e}");
820 RebootReason::InvalidFdt
821 })?;
822 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
823 error!("Failed to patch pci info to DT: {e}");
824 RebootReason::InvalidFdt
825 })?;
826 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
827 error!("Failed to patch serial info to DT: {e}");
828 RebootReason::InvalidFdt
829 })?;
830 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
831 error!("Failed to patch swiotlb info to DT: {e}");
832 RebootReason::InvalidFdt
833 })?;
834 patch_gic(fdt, info.num_cpus).map_err(|e| {
835 error!("Failed to patch gic info to DT: {e}");
836 RebootReason::InvalidFdt
837 })?;
838 patch_timer(fdt, info.num_cpus).map_err(|e| {
839 error!("Failed to patch timer info to DT: {e}");
840 RebootReason::InvalidFdt
841 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900842 if let Some(device_assignment) = &info.device_assignment {
843 // Note: We patch values after VM DTBO is overlaid because patch may require more space
844 // then VM DTBO's underlying slice is allocated.
845 device_assignment.patch(fdt).map_err(|e| {
846 error!("Failed to patch device assignment info to DT: {e}");
847 RebootReason::InvalidFdt
848 })?;
849 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900850
Jiyong Park9c63cd12023-03-21 17:53:07 +0900851 Ok(())
852}
853
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000854/// Modifies the input DT according to the fields of the configuration.
855pub fn modify_for_next_stage(
856 fdt: &mut Fdt,
857 bcc: &[u8],
858 new_instance: bool,
859 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000860 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900861 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000862 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000863) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000864 if let Some(debug_policy) = debug_policy {
865 let backup = Vec::from(fdt.as_slice());
866 fdt.unpack()?;
867 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
868 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
869 info!("Debug policy applied.");
870 } else {
871 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
872 fdt.unpack()?;
873 }
874 } else {
875 info!("No debug policy found.");
876 fdt.unpack()?;
877 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000878
Jiyong Parke9d87e82023-03-21 19:28:40 +0900879 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000880
Alice Wang56ec45b2023-06-15 08:30:32 +0000881 if let Some(mut chosen) = fdt.chosen_mut()? {
882 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
883 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000884 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000885 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900886 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900887 if let Some(bootargs) = read_bootargs_from(fdt)? {
888 filter_out_dangerous_bootargs(fdt, &bootargs)?;
889 }
890 }
891
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000892 fdt.pack()?;
893
894 Ok(())
895}
896
Jiyong Parke9d87e82023-03-21 19:28:40 +0900897/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
898fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000899 // We reject DTs with missing reserved-memory node as validation should have checked that the
900 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900901 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000902
Jiyong Parke9d87e82023-03-21 19:28:40 +0900903 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000904
Jiyong Parke9d87e82023-03-21 19:28:40 +0900905 let addr: u64 = addr.try_into().unwrap();
906 let size: u64 = size.try_into().unwrap();
907 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000908}
909
Alice Wang56ec45b2023-06-15 08:30:32 +0000910fn empty_or_delete_prop(
911 fdt_node: &mut FdtNodeMut,
912 prop_name: &CStr,
913 keep_prop: bool,
914) -> libfdt::Result<()> {
915 if keep_prop {
916 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000917 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000918 fdt_node
919 .delprop(prop_name)
920 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000921 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000922}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900923
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000924/// Apply the debug policy overlay to the guest DT.
925///
926/// 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 +0000927fn apply_debug_policy(
928 fdt: &mut Fdt,
929 backup_fdt: &Fdt,
930 debug_policy: &[u8],
931) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000932 let mut debug_policy = Vec::from(debug_policy);
933 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900934 Ok(overlay) => overlay,
935 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000936 warn!("Corrupted debug policy found: {e}. Not applying.");
937 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900938 }
939 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900940
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100941 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900942 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000943 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900944 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900945 // A successful restoration is considered success because an invalid debug policy
946 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000947 Ok(false)
948 } else {
949 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900950 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900951}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900952
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000953fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900954 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
955 if let Some(value) = node.getprop_u32(debug_feature_name)? {
956 return Ok(value == 1);
957 }
958 }
959 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
960}
961
962fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000963 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
964 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900965
966 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
967 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
968 ("crashkernel", Box::new(|_| has_crashkernel)),
969 ("console", Box::new(|_| has_console)),
970 ];
971
972 // parse and filter out unwanted
973 let mut filtered = Vec::new();
974 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
975 info!("Invalid bootarg: {e}");
976 FdtError::BadValue
977 })? {
978 match accepted.iter().find(|&t| t.0 == arg.name()) {
979 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
980 _ => debug!("Rejected bootarg {}", arg.as_ref()),
981 }
982 }
983
984 // flatten into a new C-string
985 let mut new_bootargs = Vec::new();
986 for (i, arg) in filtered.iter().enumerate() {
987 if i != 0 {
988 new_bootargs.push(b' '); // separator
989 }
990 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
991 }
992 new_bootargs.push(b'\0');
993
994 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
995 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
996}