blob: e682ab22a19e6085183672159e2181f1f54da017 [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 Tosi0edc4d62024-02-05 14:13:53 +000050use zerocopy::AsBytes as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000051
Alice Wangabc7d632023-06-14 09:10:14 +000052/// An enumeration of errors that can occur during the FDT validation.
53#[derive(Clone, Debug)]
54pub enum FdtValidationError {
55 /// Invalid CPU count.
56 InvalidCpuCount(usize),
57}
58
59impl fmt::Display for FdtValidationError {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 match self {
62 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
63 }
64 }
65}
66
Jiyong Park6a8789a2023-03-21 14:50:59 +090067/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
68/// not an error.
69fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090070 let addr = cstr!("kernel-address");
71 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000072
Jiyong Parkb87f3302023-03-21 10:03:11 +090073 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000074 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
75 let addr = addr as usize;
76 let size = size as usize;
77
78 return Ok(Some(addr..(addr + size)));
79 }
80 }
81
82 Ok(None)
83}
84
Jiyong Park6a8789a2023-03-21 14:50:59 +090085/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
86/// error as there can be initrd-less VM.
87fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090088 let start = cstr!("linux,initrd-start");
89 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000090
91 if let Some(chosen) = fdt.chosen()? {
92 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
93 return Ok(Some((start as usize)..(end as usize)));
94 }
95 }
96
97 Ok(None)
98}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000099
Jiyong Park9c63cd12023-03-21 17:53:07 +0900100fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
101 let start = u32::try_from(initrd_range.start).unwrap();
102 let end = u32::try_from(initrd_range.end).unwrap();
103
104 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
105 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
106 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
107 Ok(())
108}
109
Jiyong Parke9d87e82023-03-21 19:28:40 +0900110fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
111 if let Some(chosen) = fdt.chosen()? {
112 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
113 // We need to copy the string to heap because the original fdt will be invalidated
114 // by the templated DT
115 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
116 return Ok(Some(copy));
117 }
118 }
119 Ok(None)
120}
121
122fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
123 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900124 // This function is called before the verification is done. So, we just copy the bootargs to
125 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
126 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900127 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
128}
129
Alice Wang0d527472023-06-13 14:55:38 +0000130/// Reads and validates the memory range in the DT.
131///
132/// Only one memory range is expected with the crosvm setup for now.
133fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
134 let mut memory = fdt.memory().map_err(|e| {
135 error!("Failed to read memory range from DT: {e}");
136 RebootReason::InvalidFdt
137 })?;
138 let range = memory.next().ok_or_else(|| {
139 error!("The /memory node in the DT contains no range.");
140 RebootReason::InvalidFdt
141 })?;
142 if memory.next().is_some() {
143 warn!(
144 "The /memory node in the DT contains more than one memory range, \
145 while only one is expected."
146 );
147 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900148 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000149 if base != MEM_START {
150 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000151 return Err(RebootReason::InvalidFdt);
152 }
153
Jiyong Park6a8789a2023-03-21 14:50:59 +0900154 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000155 if size % GUEST_PAGE_SIZE != 0 {
156 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
157 return Err(RebootReason::InvalidFdt);
158 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000159
Jiyong Park6a8789a2023-03-21 14:50:59 +0900160 if size == 0 {
161 error!("Memory size is 0");
162 return Err(RebootReason::InvalidFdt);
163 }
Alice Wang0d527472023-06-13 14:55:38 +0000164 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000165}
166
Jiyong Park9c63cd12023-03-21 17:53:07 +0900167fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000168 let addr = u64::try_from(MEM_START).unwrap();
169 let size = u64::try_from(memory_range.len()).unwrap();
Jiyong Park0ee65392023-03-27 20:52:45 +0900170 fdt.node_mut(cstr!("/memory"))?
171 .ok_or(FdtError::NotFound)?
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000172 .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900173}
174
Jiyong Park6a8789a2023-03-21 14:50:59 +0900175/// Read the number of CPUs from DT
176fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
177 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
178}
179
180/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000181fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
182 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
183 Err(FdtValidationError::InvalidCpuCount(num_cpus))
184 } else {
185 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900186 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900187}
188
189/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
190fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
191 let cpu = cstr!("arm,arm-v8");
192 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
193 for _ in 0..num_cpus {
194 next = if let Some(current) = next {
195 current.next_compatible(cpu)?
196 } else {
197 return Err(FdtError::NoSpace);
198 };
199 }
200 while let Some(current) = next {
201 next = current.delete_and_next_compatible(cpu)?;
202 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900203 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000204}
205
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900206/// Read candidate properties' names from DT which could be overlaid
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900207fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900208 let mut property_map = BTreeMap::new();
Seungjae Yooed67fd52023-11-29 18:54:36 +0900209 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900210 for property in avf_node.properties()? {
211 let name = property.name()?;
212 let value = property.value()?;
213 property_map.insert(
214 CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?,
215 value.to_vec(),
216 );
Seungjae Yooed67fd52023-11-29 18:54:36 +0900217 }
218 }
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900219 Ok(property_map)
Seungjae Yooed67fd52023-11-29 18:54:36 +0900220}
221
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900222/// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only
223/// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error.
224fn validate_vm_ref_dt(
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900225 vm_dt: &mut Fdt,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900226 vm_ref_dt: &Fdt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900227 props_info: &BTreeMap<CString, Vec<u8>>,
Seungjae Yoo192e99c2023-12-15 16:42:39 +0900228) -> libfdt::Result<()> {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900229 let mut root_vm_dt = vm_dt.root_mut()?;
230 let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?;
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900231 // TODO(b/318431677): Validate nodes beyond /avf.
232 let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900233 for (name, value) in props_info.iter() {
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900234 if let Some(ref_value) = avf_node.getprop(name)? {
235 if value != ref_value {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900236 error!(
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900237 "Property mismatches while applying overlay VM reference DT. \
238 Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}",
239 name, value, ref_value
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900240 );
241 return Err(FdtError::BadValue);
242 }
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900243 avf_vm_dt.setprop(name, ref_value)?;
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900244 }
245 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900246 Ok(())
247}
248
Jiyong Park00ceff32023-03-13 05:43:23 +0000249#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000250struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900251 ranges: [PciAddrRange; 2],
252 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
253 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000254}
255
Jiyong Park6a8789a2023-03-21 14:50:59 +0900256impl PciInfo {
257 const IRQ_MASK_CELLS: usize = 4;
258 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100259 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000260}
261
Jiyong Park6a8789a2023-03-21 14:50:59 +0900262type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
263type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
264type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000265
266/// Iterator that takes N cells as a chunk
267struct CellChunkIterator<'a, const N: usize> {
268 cells: CellIterator<'a>,
269}
270
271impl<'a, const N: usize> CellChunkIterator<'a, N> {
272 fn new(cells: CellIterator<'a>) -> Self {
273 Self { cells }
274 }
275}
276
277impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
278 type Item = [u32; N];
279 fn next(&mut self) -> Option<Self::Item> {
280 let mut ret: Self::Item = [0; N];
281 for i in ret.iter_mut() {
282 *i = self.cells.next()?;
283 }
284 Some(ret)
285 }
286}
287
Jiyong Park6a8789a2023-03-21 14:50:59 +0900288/// Read pci host controller ranges, irq maps, and irq map masks from DT
289fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
290 let node =
291 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
292
293 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
294 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
295 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
296
297 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000298 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
299 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
300
301 if chunks.next().is_some() {
302 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
303 return Err(FdtError::NoSpace);
304 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900305
306 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000307 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
308 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
309
310 if chunks.next().is_some() {
311 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
312 return Err(FdtError::NoSpace);
313 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900314
315 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
316}
317
Jiyong Park0ee65392023-03-27 20:52:45 +0900318fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900319 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900320 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900321 }
322 for irq_mask in pci_info.irq_masks.iter() {
323 validate_pci_irq_mask(irq_mask)?;
324 }
325 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
326 validate_pci_irq_map(irq_map, idx)?;
327 }
328 Ok(())
329}
330
Jiyong Park0ee65392023-03-27 20:52:45 +0900331fn validate_pci_addr_range(
332 range: &PciAddrRange,
333 memory_range: &Range<usize>,
334) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900335 let mem_flags = PciMemoryFlags(range.addr.0);
336 let range_type = mem_flags.range_type();
337 let prefetchable = mem_flags.prefetchable();
338 let bus_addr = range.addr.1;
339 let cpu_addr = range.parent_addr;
340 let size = range.size;
341
342 if range_type != PciRangeType::Memory64 {
343 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
344 return Err(RebootReason::InvalidFdt);
345 }
346 if prefetchable {
347 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
348 return Err(RebootReason::InvalidFdt);
349 }
350 // Enforce ID bus-to-cpu mappings, as used by crosvm.
351 if bus_addr != cpu_addr {
352 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
353 return Err(RebootReason::InvalidFdt);
354 }
355
Jiyong Park0ee65392023-03-27 20:52:45 +0900356 let Some(bus_end) = bus_addr.checked_add(size) else {
357 error!("PCI address range size {:#x} overflows", size);
358 return Err(RebootReason::InvalidFdt);
359 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000360 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900361 error!("PCI address end {:#x} is outside of translatable range", bus_end);
362 return Err(RebootReason::InvalidFdt);
363 }
364
365 let memory_start = memory_range.start.try_into().unwrap();
366 let memory_end = memory_range.end.try_into().unwrap();
367
368 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
369 error!(
370 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
371 bus_addr, bus_end, memory_start, memory_end
372 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900373 return Err(RebootReason::InvalidFdt);
374 }
375
376 Ok(())
377}
378
379fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000380 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
381 const IRQ_MASK_ADDR_ME: u32 = 0x0;
382 const IRQ_MASK_ADDR_LO: u32 = 0x0;
383 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900384 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000385 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900386 if *irq_mask != EXPECTED {
387 error!("Invalid PCI irq mask {:#?}", irq_mask);
388 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000389 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900390 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000391}
392
Jiyong Park6a8789a2023-03-21 14:50:59 +0900393fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000394 const PCI_DEVICE_IDX: usize = 11;
395 const PCI_IRQ_ADDR_ME: u32 = 0;
396 const PCI_IRQ_ADDR_LO: u32 = 0;
397 const PCI_IRQ_INTC: u32 = 1;
398 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
399 const GIC_SPI: u32 = 0;
400 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
401
Jiyong Park6a8789a2023-03-21 14:50:59 +0900402 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
403 let pci_irq_number = irq_map[3];
404 let _controller_phandle = irq_map[4]; // skipped.
405 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
406 // interrupt-cells is <3> for GIC
407 let gic_peripheral_interrupt_type = irq_map[7];
408 let gic_irq_number = irq_map[8];
409 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000410
Jiyong Park6a8789a2023-03-21 14:50:59 +0900411 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
412 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000413
Jiyong Park6a8789a2023-03-21 14:50:59 +0900414 if pci_addr != expected_pci_addr {
415 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
416 {:#x} {:#x} {:#x}",
417 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
418 return Err(RebootReason::InvalidFdt);
419 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000420
Jiyong Park6a8789a2023-03-21 14:50:59 +0900421 if pci_irq_number != PCI_IRQ_INTC {
422 error!(
423 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
424 pci_irq_number, PCI_IRQ_INTC
425 );
426 return Err(RebootReason::InvalidFdt);
427 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000428
Jiyong Park6a8789a2023-03-21 14:50:59 +0900429 if gic_addr != (0, 0) {
430 error!(
431 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
432 {:#x} {:#x}",
433 gic_addr.0, gic_addr.1, 0, 0
434 );
435 return Err(RebootReason::InvalidFdt);
436 }
437
438 if gic_peripheral_interrupt_type != GIC_SPI {
439 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
440 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
441 return Err(RebootReason::InvalidFdt);
442 }
443
444 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
445 if gic_irq_number != irq_nr {
446 error!(
447 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
448 gic_irq_number, irq_nr
449 );
450 return Err(RebootReason::InvalidFdt);
451 }
452
453 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
454 error!(
455 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
456 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
457 );
458 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000459 }
460 Ok(())
461}
462
Jiyong Park9c63cd12023-03-21 17:53:07 +0900463fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
464 let mut node = fdt
465 .root_mut()?
466 .next_compatible(cstr!("pci-host-cam-generic"))?
467 .ok_or(FdtError::NotFound)?;
468
469 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
470 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
471
472 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
473 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
474
475 node.setprop_inplace(
476 cstr!("ranges"),
477 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
478 )
479}
480
Jiyong Park00ceff32023-03-13 05:43:23 +0000481#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900482struct SerialInfo {
483 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000484}
485
486impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900487 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000488}
489
Jiyong Park6a8789a2023-03-21 14:50:59 +0900490fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
491 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
492 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000493 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900494 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000495 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900496 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000497}
498
Jiyong Park9c63cd12023-03-21 17:53:07 +0900499/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
500fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
501 let name = cstr!("ns16550a");
502 let mut next = fdt.root_mut()?.next_compatible(name);
503 while let Some(current) = next? {
504 let reg = FdtNode::from_mut(&current)
505 .reg()?
506 .ok_or(FdtError::NotFound)?
507 .next()
508 .ok_or(FdtError::NotFound)?;
509 next = if !serial_info.addrs.contains(&reg.addr) {
510 current.delete_and_next_compatible(name)
511 } else {
512 current.next_compatible(name)
513 }
514 }
515 Ok(())
516}
517
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700518fn validate_swiotlb_info(
519 swiotlb_info: &SwiotlbInfo,
520 memory: &Range<usize>,
521) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900522 let size = swiotlb_info.size;
523 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000524
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700525 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000526 error!("Invalid swiotlb size {:#x}", size);
527 return Err(RebootReason::InvalidFdt);
528 }
529
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000530 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000531 error!("Invalid swiotlb alignment {:#x}", align);
532 return Err(RebootReason::InvalidFdt);
533 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700534
Alice Wang9cfbfd62023-06-14 11:19:03 +0000535 if let Some(addr) = swiotlb_info.addr {
536 if addr.checked_add(size).is_none() {
537 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
538 return Err(RebootReason::InvalidFdt);
539 }
540 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700541 if let Some(range) = swiotlb_info.fixed_range() {
542 if !range.is_within(memory) {
543 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
544 return Err(RebootReason::InvalidFdt);
545 }
546 }
547
Jiyong Park6a8789a2023-03-21 14:50:59 +0900548 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000549}
550
Jiyong Park9c63cd12023-03-21 17:53:07 +0900551fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
552 let mut node =
553 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700554
555 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000556 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700557 cstr!("reg"),
558 range.start.try_into().unwrap(),
559 range.len().try_into().unwrap(),
560 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000561 node.nop_property(cstr!("size"))?;
562 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700563 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000564 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700565 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000566 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700567 }
568
Jiyong Park9c63cd12023-03-21 17:53:07 +0900569 Ok(())
570}
571
572fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
573 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
574 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
575 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
576 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
577
578 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000579 // `validate_num_cpus()` checked that this wouldn't panic
580 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900581
582 // range1 is just below range0
583 range1.addr = addr - size;
584 range1.size = Some(size);
585
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000586 let (addr0, size0) = range0.to_cells();
587 let (addr1, size1) = range1.to_cells();
588 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900589
590 let mut node =
591 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
592 node.setprop_inplace(cstr!("reg"), flatten(&value))
593}
594
595fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
596 const NUM_INTERRUPTS: usize = 4;
597 const CELLS_PER_INTERRUPT: usize = 3;
598 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
599 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
600 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
601 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
602
603 let num_cpus: u32 = num_cpus.try_into().unwrap();
604 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
605 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
606 *v |= cpu_mask;
607 }
608 for v in value.iter_mut() {
609 *v = v.to_be();
610 }
611
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000612 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900613
614 let mut node =
615 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000616 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900617}
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
Jiyong Parke9d87e82023-03-21 19:28:40 +0900661 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
662 error!("Failed to instantiate FDT from the template DT: {e}");
663 RebootReason::InvalidFdt
664 })?;
665
Jaewan Kim9220e852023-12-01 10:58:40 +0900666 fdt.unpack().map_err(|e| {
667 error!("Failed to unpack DT for patching: {e}");
668 RebootReason::InvalidFdt
669 })?;
670
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900671 if let Some(device_assignment_info) = &info.device_assignment {
672 let vm_dtbo = vm_dtbo.unwrap();
673 device_assignment_info.filter(vm_dtbo).map_err(|e| {
674 error!("Failed to filter VM DTBO: {e}");
675 RebootReason::InvalidFdt
676 })?;
677 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
678 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
679 // it can only be instantiated after validation.
680 unsafe {
681 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
682 error!("Failed to apply filtered VM DTBO: {e}");
683 RebootReason::InvalidFdt
684 })?;
685 }
686 }
687
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900688 if let Some(vm_ref_dt) = vm_ref_dt {
689 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
690 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900691 RebootReason::InvalidFdt
692 })?;
693
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900694 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
695 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900696 RebootReason::InvalidFdt
697 })?;
698 }
699
Jiyong Park9c63cd12023-03-21 17:53:07 +0900700 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900701
Jaewan Kim19b984f2023-12-04 15:16:50 +0900702 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
703
Jaewan Kim9220e852023-12-01 10:58:40 +0900704 fdt.pack().map_err(|e| {
705 error!("Failed to unpack DT after patching: {e}");
706 RebootReason::InvalidFdt
707 })?;
708
Jiyong Park6a8789a2023-03-21 14:50:59 +0900709 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900710}
711
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900712fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900713 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
714 error!("Failed to read kernel range from DT: {e}");
715 RebootReason::InvalidFdt
716 })?;
717
718 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
719 error!("Failed to read initrd range from DT: {e}");
720 RebootReason::InvalidFdt
721 })?;
722
Alice Wang0d527472023-06-13 14:55:38 +0000723 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900724
Jiyong Parke9d87e82023-03-21 19:28:40 +0900725 let bootargs = read_bootargs_from(fdt).map_err(|e| {
726 error!("Failed to read bootargs from DT: {e}");
727 RebootReason::InvalidFdt
728 })?;
729
Jiyong Park6a8789a2023-03-21 14:50:59 +0900730 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
731 error!("Failed to read num cpus from DT: {e}");
732 RebootReason::InvalidFdt
733 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000734 validate_num_cpus(num_cpus).map_err(|e| {
735 error!("Failed to validate num cpus from DT: {e}");
736 RebootReason::InvalidFdt
737 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900738
739 let pci_info = read_pci_info_from(fdt).map_err(|e| {
740 error!("Failed to read pci info from DT: {e}");
741 RebootReason::InvalidFdt
742 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900743 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900744
745 let serial_info = read_serial_info_from(fdt).map_err(|e| {
746 error!("Failed to read serial info from DT: {e}");
747 RebootReason::InvalidFdt
748 })?;
749
Alice Wang9cfbfd62023-06-14 11:19:03 +0000750 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900751 error!("Failed to read swiotlb info from DT: {e}");
752 RebootReason::InvalidFdt
753 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700754 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900755
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900756 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900757 Some(vm_dtbo) => {
758 if let Some(hypervisor) = hyp::get_device_assigner() {
759 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
760 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
761 RebootReason::InvalidFdt
762 })?
763 } else {
764 warn!(
765 "Device assignment is ignored because device assigning hypervisor is missing"
766 );
767 None
768 }
769 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900770 None => None,
771 };
772
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900773 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900774 error!("Failed to read names of properties under /avf from DT: {e}");
775 RebootReason::InvalidFdt
776 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900777
Jiyong Park00ceff32023-03-13 05:43:23 +0000778 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900779 kernel_range,
780 initrd_range,
781 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900782 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900783 num_cpus,
784 pci_info,
785 serial_info,
786 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900787 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900788 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000789 })
790}
791
Jiyong Park9c63cd12023-03-21 17:53:07 +0900792fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
793 if let Some(initrd_range) = &info.initrd_range {
794 patch_initrd_range(fdt, initrd_range).map_err(|e| {
795 error!("Failed to patch initrd range to DT: {e}");
796 RebootReason::InvalidFdt
797 })?;
798 }
799 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
800 error!("Failed to patch memory range to DT: {e}");
801 RebootReason::InvalidFdt
802 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900803 if let Some(bootargs) = &info.bootargs {
804 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
805 error!("Failed to patch bootargs to DT: {e}");
806 RebootReason::InvalidFdt
807 })?;
808 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900809 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
810 error!("Failed to patch cpus to DT: {e}");
811 RebootReason::InvalidFdt
812 })?;
813 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
814 error!("Failed to patch pci info to DT: {e}");
815 RebootReason::InvalidFdt
816 })?;
817 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
818 error!("Failed to patch serial info to DT: {e}");
819 RebootReason::InvalidFdt
820 })?;
821 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
822 error!("Failed to patch swiotlb info to DT: {e}");
823 RebootReason::InvalidFdt
824 })?;
825 patch_gic(fdt, info.num_cpus).map_err(|e| {
826 error!("Failed to patch gic info to DT: {e}");
827 RebootReason::InvalidFdt
828 })?;
829 patch_timer(fdt, info.num_cpus).map_err(|e| {
830 error!("Failed to patch timer info to DT: {e}");
831 RebootReason::InvalidFdt
832 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900833 if let Some(device_assignment) = &info.device_assignment {
834 // Note: We patch values after VM DTBO is overlaid because patch may require more space
835 // then VM DTBO's underlying slice is allocated.
836 device_assignment.patch(fdt).map_err(|e| {
837 error!("Failed to patch device assignment info to DT: {e}");
838 RebootReason::InvalidFdt
839 })?;
840 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900841
Jiyong Park9c63cd12023-03-21 17:53:07 +0900842 Ok(())
843}
844
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000845/// Modifies the input DT according to the fields of the configuration.
846pub fn modify_for_next_stage(
847 fdt: &mut Fdt,
848 bcc: &[u8],
849 new_instance: bool,
850 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000851 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900852 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000853 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000854) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000855 if let Some(debug_policy) = debug_policy {
856 let backup = Vec::from(fdt.as_slice());
857 fdt.unpack()?;
858 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
859 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
860 info!("Debug policy applied.");
861 } else {
862 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
863 fdt.unpack()?;
864 }
865 } else {
866 info!("No debug policy found.");
867 fdt.unpack()?;
868 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000869
Jiyong Parke9d87e82023-03-21 19:28:40 +0900870 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000871
Alice Wang56ec45b2023-06-15 08:30:32 +0000872 if let Some(mut chosen) = fdt.chosen_mut()? {
873 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
874 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000875 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000876 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900877 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900878 if let Some(bootargs) = read_bootargs_from(fdt)? {
879 filter_out_dangerous_bootargs(fdt, &bootargs)?;
880 }
881 }
882
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000883 fdt.pack()?;
884
885 Ok(())
886}
887
Jiyong Parke9d87e82023-03-21 19:28:40 +0900888/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
889fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000890 // We reject DTs with missing reserved-memory node as validation should have checked that the
891 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900892 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000893
Jiyong Parke9d87e82023-03-21 19:28:40 +0900894 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000895
Jiyong Parke9d87e82023-03-21 19:28:40 +0900896 let addr: u64 = addr.try_into().unwrap();
897 let size: u64 = size.try_into().unwrap();
898 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000899}
900
Alice Wang56ec45b2023-06-15 08:30:32 +0000901fn empty_or_delete_prop(
902 fdt_node: &mut FdtNodeMut,
903 prop_name: &CStr,
904 keep_prop: bool,
905) -> libfdt::Result<()> {
906 if keep_prop {
907 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000908 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000909 fdt_node
910 .delprop(prop_name)
911 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000912 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000913}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900914
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000915/// Apply the debug policy overlay to the guest DT.
916///
917/// 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 +0000918fn apply_debug_policy(
919 fdt: &mut Fdt,
920 backup_fdt: &Fdt,
921 debug_policy: &[u8],
922) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000923 let mut debug_policy = Vec::from(debug_policy);
924 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900925 Ok(overlay) => overlay,
926 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000927 warn!("Corrupted debug policy found: {e}. Not applying.");
928 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900929 }
930 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900931
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100932 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900933 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000934 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900935 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900936 // A successful restoration is considered success because an invalid debug policy
937 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000938 Ok(false)
939 } else {
940 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900941 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900942}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900943
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000944fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900945 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
946 if let Some(value) = node.getprop_u32(debug_feature_name)? {
947 return Ok(value == 1);
948 }
949 }
950 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
951}
952
953fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000954 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
955 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900956
957 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
958 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
959 ("crashkernel", Box::new(|_| has_crashkernel)),
960 ("console", Box::new(|_| has_console)),
961 ];
962
963 // parse and filter out unwanted
964 let mut filtered = Vec::new();
965 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
966 info!("Invalid bootarg: {e}");
967 FdtError::BadValue
968 })? {
969 match accepted.iter().find(|&t| t.0 == arg.name()) {
970 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
971 _ => debug!("Rejected bootarg {}", arg.as_ref()),
972 }
973 }
974
975 // flatten into a new C-string
976 let mut new_bootargs = Vec::new();
977 for (i, arg) in filtered.iter().enumerate() {
978 if i != 0 {
979 new_bootargs.push(b' '); // separator
980 }
981 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
982 }
983 new_bootargs.push(b'\0');
984
985 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
986 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
987}