blob: 1e3757286107dad9e67698f557090670d97f2899 [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;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Jiyong Park83316122023-03-21 09:39:39 +090039use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000040use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090041use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000042use log::warn;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000044use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000045use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000046use vmbase::memory::SIZE_4KB;
47use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000048use vmbase::util::RangeExt as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000049
Alice Wangabc7d632023-06-14 09:10:14 +000050/// An enumeration of errors that can occur during the FDT validation.
51#[derive(Clone, Debug)]
52pub enum FdtValidationError {
53 /// Invalid CPU count.
54 InvalidCpuCount(usize),
55}
56
57impl fmt::Display for FdtValidationError {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 match self {
60 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
61 }
62 }
63}
64
Jiyong Park6a8789a2023-03-21 14:50:59 +090065/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
66/// not an error.
67fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090068 let addr = cstr!("kernel-address");
69 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000070
Jiyong Parkb87f3302023-03-21 10:03:11 +090071 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000072 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
73 let addr = addr as usize;
74 let size = size as usize;
75
76 return Ok(Some(addr..(addr + size)));
77 }
78 }
79
80 Ok(None)
81}
82
Jiyong Park6a8789a2023-03-21 14:50:59 +090083/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
84/// error as there can be initrd-less VM.
85fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090086 let start = cstr!("linux,initrd-start");
87 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000088
89 if let Some(chosen) = fdt.chosen()? {
90 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
91 return Ok(Some((start as usize)..(end as usize)));
92 }
93 }
94
95 Ok(None)
96}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000097
Jiyong Park9c63cd12023-03-21 17:53:07 +090098fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
99 let start = u32::try_from(initrd_range.start).unwrap();
100 let end = u32::try_from(initrd_range.end).unwrap();
101
102 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
103 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
104 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
105 Ok(())
106}
107
Jiyong Parke9d87e82023-03-21 19:28:40 +0900108fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
109 if let Some(chosen) = fdt.chosen()? {
110 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
111 // We need to copy the string to heap because the original fdt will be invalidated
112 // by the templated DT
113 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
114 return Ok(Some(copy));
115 }
116 }
117 Ok(None)
118}
119
120fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
121 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900122 // This function is called before the verification is done. So, we just copy the bootargs to
123 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
124 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900125 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
126}
127
Alice Wang0d527472023-06-13 14:55:38 +0000128/// Reads and validates the memory range in the DT.
129///
130/// Only one memory range is expected with the crosvm setup for now.
131fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
132 let mut memory = fdt.memory().map_err(|e| {
133 error!("Failed to read memory range from DT: {e}");
134 RebootReason::InvalidFdt
135 })?;
136 let range = memory.next().ok_or_else(|| {
137 error!("The /memory node in the DT contains no range.");
138 RebootReason::InvalidFdt
139 })?;
140 if memory.next().is_some() {
141 warn!(
142 "The /memory node in the DT contains more than one memory range, \
143 while only one is expected."
144 );
145 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900146 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000147 if base != MEM_START {
148 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000149 return Err(RebootReason::InvalidFdt);
150 }
151
Jiyong Park6a8789a2023-03-21 14:50:59 +0900152 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000153 if size % GUEST_PAGE_SIZE != 0 {
154 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
155 return Err(RebootReason::InvalidFdt);
156 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000157
Jiyong Park6a8789a2023-03-21 14:50:59 +0900158 if size == 0 {
159 error!("Memory size is 0");
160 return Err(RebootReason::InvalidFdt);
161 }
Alice Wang0d527472023-06-13 14:55:38 +0000162 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000163}
164
Jiyong Park9c63cd12023-03-21 17:53:07 +0900165fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
166 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900167 fdt.node_mut(cstr!("/memory"))?
168 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000169 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900170}
171
Jiyong Park6a8789a2023-03-21 14:50:59 +0900172/// Read the number of CPUs from DT
173fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
174 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
175}
176
177/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000178fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
179 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
180 Err(FdtValidationError::InvalidCpuCount(num_cpus))
181 } else {
182 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900183 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900184}
185
186/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
187fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
188 let cpu = cstr!("arm,arm-v8");
189 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
190 for _ in 0..num_cpus {
191 next = if let Some(current) = next {
192 current.next_compatible(cpu)?
193 } else {
194 return Err(FdtError::NoSpace);
195 };
196 }
197 while let Some(current) = next {
198 next = current.delete_and_next_compatible(cpu)?;
199 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900200 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000201}
202
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900203/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900204fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900205 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900206 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900207 for property in avf_node.properties()? {
208 let name = property.name()?;
209 let value = property.value()?;
210 property_map.insert(
211 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
212 value.to_vec(),
213 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900214 }
215 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900216 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900217}
218
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900219/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
220/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
221fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900222 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900223 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900224 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900225) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900226 let mut root_vm_dt = vm_dt.root_mut()?;
227 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900228 // TODO(b/318431677): Validate nodes beyond /avf.
229 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900230 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900231 if let Some(ref_value) = avf_node.getprop(name)? {
232 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900233 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900234 "Property mismatches while applying overlay VM reference DT. \
235 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
236 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900237 );
238 return Err(FdtError::BadValue);
239 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900240 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900241 }
242 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900243 Ok(())
244}
245
Jiyong Park00ceff32023-03-13 05:43:23 +0000246#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000247struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900248 ranges: [PciAddrRange; 2],
249 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
250 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000251}
252
Jiyong Park6a8789a2023-03-21 14:50:59 +0900253impl PciInfo {
254 const IRQ_MASK_CELLS: usize = 4;
255 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100256 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000257}
258
Jiyong Park6a8789a2023-03-21 14:50:59 +0900259type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
260type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
261type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000262
263/// Iterator that takes N cells as a chunk
264struct CellChunkIterator<'a, const N: usize> {
265 cells: CellIterator<'a>,
266}
267
268impl<'a, const N: usize> CellChunkIterator<'a, N> {
269 fn new(cells: CellIterator<'a>) -> Self {
270 Self { cells }
271 }
272}
273
274impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
275 type Item = [u32; N];
276 fn next(&mut self) -> Option<Self::Item> {
277 let mut ret: Self::Item = [0; N];
278 for i in ret.iter_mut() {
279 *i = self.cells.next()?;
280 }
281 Some(ret)
282 }
283}
284
Jiyong Park6a8789a2023-03-21 14:50:59 +0900285/// Read pci host controller ranges, irq maps, and irq map masks from DT
286fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
287 let node =
288 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
289
290 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
291 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
292 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
293
294 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000295 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
296 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
297
298 if chunks.next().is_some() {
299 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
300 return Err(FdtError::NoSpace);
301 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900302
303 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000304 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
305 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
306
307 if chunks.next().is_some() {
308 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
309 return Err(FdtError::NoSpace);
310 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900311
312 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
313}
314
Jiyong Park0ee65392023-03-27 20:52:45 +0900315fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900316 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900317 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900318 }
319 for irq_mask in pci_info.irq_masks.iter() {
320 validate_pci_irq_mask(irq_mask)?;
321 }
322 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
323 validate_pci_irq_map(irq_map, idx)?;
324 }
325 Ok(())
326}
327
Jiyong Park0ee65392023-03-27 20:52:45 +0900328fn validate_pci_addr_range(
329 range: &PciAddrRange,
330 memory_range: &Range<usize>,
331) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900332 let mem_flags = PciMemoryFlags(range.addr.0);
333 let range_type = mem_flags.range_type();
334 let prefetchable = mem_flags.prefetchable();
335 let bus_addr = range.addr.1;
336 let cpu_addr = range.parent_addr;
337 let size = range.size;
338
339 if range_type != PciRangeType::Memory64 {
340 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
341 return Err(RebootReason::InvalidFdt);
342 }
343 if prefetchable {
344 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
345 return Err(RebootReason::InvalidFdt);
346 }
347 // Enforce ID bus-to-cpu mappings, as used by crosvm.
348 if bus_addr != cpu_addr {
349 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
350 return Err(RebootReason::InvalidFdt);
351 }
352
Jiyong Park0ee65392023-03-27 20:52:45 +0900353 let Some(bus_end) = bus_addr.checked_add(size) else {
354 error!("PCI address range size {:#x} overflows", size);
355 return Err(RebootReason::InvalidFdt);
356 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000357 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900358 error!("PCI address end {:#x} is outside of translatable range", bus_end);
359 return Err(RebootReason::InvalidFdt);
360 }
361
362 let memory_start = memory_range.start.try_into().unwrap();
363 let memory_end = memory_range.end.try_into().unwrap();
364
365 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
366 error!(
367 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
368 bus_addr, bus_end, memory_start, memory_end
369 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900370 return Err(RebootReason::InvalidFdt);
371 }
372
373 Ok(())
374}
375
376fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000377 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
378 const IRQ_MASK_ADDR_ME: u32 = 0x0;
379 const IRQ_MASK_ADDR_LO: u32 = 0x0;
380 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900381 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000382 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900383 if *irq_mask != EXPECTED {
384 error!("Invalid PCI irq mask {:#?}", irq_mask);
385 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000386 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900387 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000388}
389
Jiyong Park6a8789a2023-03-21 14:50:59 +0900390fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000391 const PCI_DEVICE_IDX: usize = 11;
392 const PCI_IRQ_ADDR_ME: u32 = 0;
393 const PCI_IRQ_ADDR_LO: u32 = 0;
394 const PCI_IRQ_INTC: u32 = 1;
395 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
396 const GIC_SPI: u32 = 0;
397 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
398
Jiyong Park6a8789a2023-03-21 14:50:59 +0900399 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
400 let pci_irq_number = irq_map[3];
401 let _controller_phandle = irq_map[4]; // skipped.
402 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
403 // interrupt-cells is <3> for GIC
404 let gic_peripheral_interrupt_type = irq_map[7];
405 let gic_irq_number = irq_map[8];
406 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000407
Jiyong Park6a8789a2023-03-21 14:50:59 +0900408 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
409 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000410
Jiyong Park6a8789a2023-03-21 14:50:59 +0900411 if pci_addr != expected_pci_addr {
412 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
413 {:#x} {:#x} {:#x}",
414 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
415 return Err(RebootReason::InvalidFdt);
416 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000417
Jiyong Park6a8789a2023-03-21 14:50:59 +0900418 if pci_irq_number != PCI_IRQ_INTC {
419 error!(
420 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
421 pci_irq_number, PCI_IRQ_INTC
422 );
423 return Err(RebootReason::InvalidFdt);
424 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000425
Jiyong Park6a8789a2023-03-21 14:50:59 +0900426 if gic_addr != (0, 0) {
427 error!(
428 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
429 {:#x} {:#x}",
430 gic_addr.0, gic_addr.1, 0, 0
431 );
432 return Err(RebootReason::InvalidFdt);
433 }
434
435 if gic_peripheral_interrupt_type != GIC_SPI {
436 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
437 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
438 return Err(RebootReason::InvalidFdt);
439 }
440
441 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
442 if gic_irq_number != irq_nr {
443 error!(
444 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
445 gic_irq_number, irq_nr
446 );
447 return Err(RebootReason::InvalidFdt);
448 }
449
450 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
451 error!(
452 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
453 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
454 );
455 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000456 }
457 Ok(())
458}
459
Jiyong Park9c63cd12023-03-21 17:53:07 +0900460fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
461 let mut node = fdt
462 .root_mut()?
463 .next_compatible(cstr!("pci-host-cam-generic"))?
464 .ok_or(FdtError::NotFound)?;
465
466 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
467 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
468
469 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
470 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
471
472 node.setprop_inplace(
473 cstr!("ranges"),
474 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
475 )
476}
477
Jiyong Park00ceff32023-03-13 05:43:23 +0000478#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900479struct SerialInfo {
480 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000481}
482
483impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900484 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000485}
486
Jiyong Park6a8789a2023-03-21 14:50:59 +0900487fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
488 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
489 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000490 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900491 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000492 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900493 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000494}
495
Jiyong Park9c63cd12023-03-21 17:53:07 +0900496/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
497fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
498 let name = cstr!("ns16550a");
499 let mut next = fdt.root_mut()?.next_compatible(name);
500 while let Some(current) = next? {
Pierre-Clément Tosic01fd0d2024-01-25 22:26:22 +0000501 let reg =
502 current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900503 next = if !serial_info.addrs.contains(&reg.addr) {
504 current.delete_and_next_compatible(name)
505 } else {
506 current.next_compatible(name)
507 }
508 }
509 Ok(())
510}
511
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700512fn validate_swiotlb_info(
513 swiotlb_info: &SwiotlbInfo,
514 memory: &Range<usize>,
515) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900516 let size = swiotlb_info.size;
517 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000518
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700519 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000520 error!("Invalid swiotlb size {:#x}", size);
521 return Err(RebootReason::InvalidFdt);
522 }
523
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000524 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000525 error!("Invalid swiotlb alignment {:#x}", align);
526 return Err(RebootReason::InvalidFdt);
527 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700528
Alice Wang9cfbfd62023-06-14 11:19:03 +0000529 if let Some(addr) = swiotlb_info.addr {
530 if addr.checked_add(size).is_none() {
531 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
532 return Err(RebootReason::InvalidFdt);
533 }
534 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700535 if let Some(range) = swiotlb_info.fixed_range() {
536 if !range.is_within(memory) {
537 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
538 return Err(RebootReason::InvalidFdt);
539 }
540 }
541
Jiyong Park6a8789a2023-03-21 14:50:59 +0900542 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000543}
544
Jiyong Park9c63cd12023-03-21 17:53:07 +0900545fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
546 let mut node =
547 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700548
549 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000550 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700551 cstr!("reg"),
552 range.start.try_into().unwrap(),
553 range.len().try_into().unwrap(),
554 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000555 node.nop_property(cstr!("size"))?;
556 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700557 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000558 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700559 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000560 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700561 }
562
Jiyong Park9c63cd12023-03-21 17:53:07 +0900563 Ok(())
564}
565
566fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
567 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
568 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
569 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
570 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
571
572 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000573 // `validate_num_cpus()` checked that this wouldn't panic
574 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900575
576 // range1 is just below range0
577 range1.addr = addr - size;
578 range1.size = Some(size);
579
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000580 let (addr0, size0) = range0.to_cells();
581 let (addr1, size1) = range1.to_cells();
582 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900583
584 let mut node =
585 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
586 node.setprop_inplace(cstr!("reg"), flatten(&value))
587}
588
589fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
590 const NUM_INTERRUPTS: usize = 4;
591 const CELLS_PER_INTERRUPT: usize = 3;
592 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
593 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
594 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
595 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
596
597 let num_cpus: u32 = num_cpus.try_into().unwrap();
598 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
599 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
600 *v |= cpu_mask;
601 }
602 for v in value.iter_mut() {
603 *v = v.to_be();
604 }
605
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100606 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900607 let value = unsafe {
608 core::mem::transmute::<
609 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
610 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
611 >(value.into_inner())
612 };
613
614 let mut node =
615 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
616 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
617}
618
Jiyong Park00ceff32023-03-13 05:43:23 +0000619#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900620pub struct DeviceTreeInfo {
621 pub kernel_range: Option<Range<usize>>,
622 pub initrd_range: Option<Range<usize>>,
623 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900624 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900625 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000626 pci_info: PciInfo,
627 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700628 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900629 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900630 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000631}
632
633impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000634 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
635 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
636
637 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
638 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000639}
640
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900641pub fn sanitize_device_tree(
642 fdt: &mut [u8],
643 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900644 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900645) -> Result<DeviceTreeInfo, RebootReason> {
646 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
647 error!("Failed to load FDT: {e}");
648 RebootReason::InvalidFdt
649 })?;
650
651 let vm_dtbo = match vm_dtbo {
652 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
653 error!("Failed to load VM DTBO: {e}");
654 RebootReason::InvalidFdt
655 })?),
656 None => None,
657 };
658
659 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900660
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000661 // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT.
662 let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) };
663 fdt.clone_from(fdt_template).map_err(|e| {
Jiyong Parke9d87e82023-03-21 19:28:40 +0900664 error!("Failed to instantiate FDT from the template DT: {e}");
665 RebootReason::InvalidFdt
666 })?;
667
Jaewan Kim9220e852023-12-01 10:58:40 +0900668 fdt.unpack().map_err(|e| {
669 error!("Failed to unpack DT for patching: {e}");
670 RebootReason::InvalidFdt
671 })?;
672
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900673 if let Some(device_assignment_info) = &info.device_assignment {
674 let vm_dtbo = vm_dtbo.unwrap();
675 device_assignment_info.filter(vm_dtbo).map_err(|e| {
676 error!("Failed to filter VM DTBO: {e}");
677 RebootReason::InvalidFdt
678 })?;
679 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
680 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
681 // it can only be instantiated after validation.
682 unsafe {
683 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
684 error!("Failed to apply filtered VM DTBO: {e}");
685 RebootReason::InvalidFdt
686 })?;
687 }
688 }
689
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900690 if let Some(vm_ref_dt) = vm_ref_dt {
691 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
692 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900693 RebootReason::InvalidFdt
694 })?;
695
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900696 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
697 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900698 RebootReason::InvalidFdt
699 })?;
700 }
701
Jiyong Park9c63cd12023-03-21 17:53:07 +0900702 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900703
Jaewan Kim19b984f2023-12-04 15:16:50 +0900704 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
705
Jaewan Kim9220e852023-12-01 10:58:40 +0900706 fdt.pack().map_err(|e| {
707 error!("Failed to unpack DT after patching: {e}");
708 RebootReason::InvalidFdt
709 })?;
710
Jiyong Park6a8789a2023-03-21 14:50:59 +0900711 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900712}
713
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900714fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900715 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
716 error!("Failed to read kernel range from DT: {e}");
717 RebootReason::InvalidFdt
718 })?;
719
720 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
721 error!("Failed to read initrd range from DT: {e}");
722 RebootReason::InvalidFdt
723 })?;
724
Alice Wang0d527472023-06-13 14:55:38 +0000725 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900726
Jiyong Parke9d87e82023-03-21 19:28:40 +0900727 let bootargs = read_bootargs_from(fdt).map_err(|e| {
728 error!("Failed to read bootargs from DT: {e}");
729 RebootReason::InvalidFdt
730 })?;
731
Jiyong Park6a8789a2023-03-21 14:50:59 +0900732 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
733 error!("Failed to read num cpus from DT: {e}");
734 RebootReason::InvalidFdt
735 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000736 validate_num_cpus(num_cpus).map_err(|e| {
737 error!("Failed to validate num cpus from DT: {e}");
738 RebootReason::InvalidFdt
739 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900740
741 let pci_info = read_pci_info_from(fdt).map_err(|e| {
742 error!("Failed to read pci info from DT: {e}");
743 RebootReason::InvalidFdt
744 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900745 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900746
747 let serial_info = read_serial_info_from(fdt).map_err(|e| {
748 error!("Failed to read serial info from DT: {e}");
749 RebootReason::InvalidFdt
750 })?;
751
Alice Wang9cfbfd62023-06-14 11:19:03 +0000752 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900753 error!("Failed to read swiotlb info from DT: {e}");
754 RebootReason::InvalidFdt
755 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700756 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900757
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900758 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900759 Some(vm_dtbo) => {
760 if let Some(hypervisor) = hyp::get_device_assigner() {
761 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
762 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
763 RebootReason::InvalidFdt
764 })?
765 } else {
766 warn!(
767 "Device assignment is ignored because device assigning hypervisor is missing"
768 );
769 None
770 }
771 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900772 None => None,
773 };
774
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900775 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900776 error!("Failed to read names of properties under /avf from DT: {e}");
777 RebootReason::InvalidFdt
778 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900779
Jiyong Park00ceff32023-03-13 05:43:23 +0000780 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900781 kernel_range,
782 initrd_range,
783 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900784 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900785 num_cpus,
786 pci_info,
787 serial_info,
788 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900789 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900790 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000791 })
792}
793
Jiyong Park9c63cd12023-03-21 17:53:07 +0900794fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
795 if let Some(initrd_range) = &info.initrd_range {
796 patch_initrd_range(fdt, initrd_range).map_err(|e| {
797 error!("Failed to patch initrd range to DT: {e}");
798 RebootReason::InvalidFdt
799 })?;
800 }
801 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
802 error!("Failed to patch memory range to DT: {e}");
803 RebootReason::InvalidFdt
804 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900805 if let Some(bootargs) = &info.bootargs {
806 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
807 error!("Failed to patch bootargs to DT: {e}");
808 RebootReason::InvalidFdt
809 })?;
810 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900811 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
812 error!("Failed to patch cpus to DT: {e}");
813 RebootReason::InvalidFdt
814 })?;
815 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
816 error!("Failed to patch pci info to DT: {e}");
817 RebootReason::InvalidFdt
818 })?;
819 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
820 error!("Failed to patch serial info to DT: {e}");
821 RebootReason::InvalidFdt
822 })?;
823 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
824 error!("Failed to patch swiotlb info to DT: {e}");
825 RebootReason::InvalidFdt
826 })?;
827 patch_gic(fdt, info.num_cpus).map_err(|e| {
828 error!("Failed to patch gic info to DT: {e}");
829 RebootReason::InvalidFdt
830 })?;
831 patch_timer(fdt, info.num_cpus).map_err(|e| {
832 error!("Failed to patch timer info to DT: {e}");
833 RebootReason::InvalidFdt
834 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900835 if let Some(device_assignment) = &info.device_assignment {
836 // Note: We patch values after VM DTBO is overlaid because patch may require more space
837 // then VM DTBO's underlying slice is allocated.
838 device_assignment.patch(fdt).map_err(|e| {
839 error!("Failed to patch device assignment info to DT: {e}");
840 RebootReason::InvalidFdt
841 })?;
842 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900843
Jiyong Park9c63cd12023-03-21 17:53:07 +0900844 Ok(())
845}
846
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000847/// Modifies the input DT according to the fields of the configuration.
848pub fn modify_for_next_stage(
849 fdt: &mut Fdt,
850 bcc: &[u8],
851 new_instance: bool,
852 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000853 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900854 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000855 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000856) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000857 if let Some(debug_policy) = debug_policy {
858 let backup = Vec::from(fdt.as_slice());
859 fdt.unpack()?;
860 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
861 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
862 info!("Debug policy applied.");
863 } else {
864 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
865 fdt.unpack()?;
866 }
867 } else {
868 info!("No debug policy found.");
869 fdt.unpack()?;
870 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000871
Jiyong Parke9d87e82023-03-21 19:28:40 +0900872 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000873
Alice Wang56ec45b2023-06-15 08:30:32 +0000874 if let Some(mut chosen) = fdt.chosen_mut()? {
875 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
876 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000877 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000878 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900879 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900880 if let Some(bootargs) = read_bootargs_from(fdt)? {
881 filter_out_dangerous_bootargs(fdt, &bootargs)?;
882 }
883 }
884
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000885 fdt.pack()?;
886
887 Ok(())
888}
889
Jiyong Parke9d87e82023-03-21 19:28:40 +0900890/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
891fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000892 // We reject DTs with missing reserved-memory node as validation should have checked that the
893 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900894 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000895
Jiyong Parke9d87e82023-03-21 19:28:40 +0900896 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000897
Jiyong Parke9d87e82023-03-21 19:28:40 +0900898 let addr: u64 = addr.try_into().unwrap();
899 let size: u64 = size.try_into().unwrap();
900 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000901}
902
Alice Wang56ec45b2023-06-15 08:30:32 +0000903fn empty_or_delete_prop(
904 fdt_node: &mut FdtNodeMut,
905 prop_name: &CStr,
906 keep_prop: bool,
907) -> libfdt::Result<()> {
908 if keep_prop {
909 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000910 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000911 fdt_node
912 .delprop(prop_name)
913 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000914 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000915}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900916
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000917/// Apply the debug policy overlay to the guest DT.
918///
919/// 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 +0000920fn apply_debug_policy(
921 fdt: &mut Fdt,
922 backup_fdt: &Fdt,
923 debug_policy: &[u8],
924) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000925 let mut debug_policy = Vec::from(debug_policy);
926 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900927 Ok(overlay) => overlay,
928 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000929 warn!("Corrupted debug policy found: {e}. Not applying.");
930 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900931 }
932 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900933
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100934 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900935 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000936 warn!("Failed to apply debug policy: {e}. Recovering...");
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000937 fdt.clone_from(backup_fdt)?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900938 // A successful restoration is considered success because an invalid debug policy
939 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000940 Ok(false)
941 } else {
942 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900943 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900944}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900945
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000946fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900947 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
948 if let Some(value) = node.getprop_u32(debug_feature_name)? {
949 return Ok(value == 1);
950 }
951 }
952 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
953}
954
955fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000956 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
957 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900958
959 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
960 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
961 ("crashkernel", Box::new(|_| has_crashkernel)),
962 ("console", Box::new(|_| has_console)),
963 ];
964
965 // parse and filter out unwanted
966 let mut filtered = Vec::new();
967 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
968 info!("Invalid bootarg: {e}");
969 FdtError::BadValue
970 })? {
971 match accepted.iter().find(|&t| t.0 == arg.name()) {
972 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
973 _ => debug!("Rejected bootarg {}", arg.as_ref()),
974 }
975 }
976
977 // flatten into a new C-string
978 let mut new_bootargs = Vec::new();
979 for (i, arg) in filtered.iter().enumerate() {
980 if i != 0 {
981 new_bootargs.push(b' '); // separator
982 }
983 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
984 }
985 new_bootargs.push(b'\0');
986
987 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
988 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
989}