blob: d2aad616172bd2a627b3d5d2c66e2ce89fcde33a [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> {
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000491 let mut addrs = ArrayVec::new();
492
493 let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?;
494 for node in serial_nodes.by_ref().take(addrs.capacity()) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000495 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900496 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000497 }
Pierre-Clément Tosibe893612024-02-05 14:23:44 +0000498 if serial_nodes.next().is_some() {
499 warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity());
500 }
501
Jiyong Park6a8789a2023-03-21 14:50:59 +0900502 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000503}
504
Jiyong Park9c63cd12023-03-21 17:53:07 +0900505/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
506fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
507 let name = cstr!("ns16550a");
508 let mut next = fdt.root_mut()?.next_compatible(name);
509 while let Some(current) = next? {
510 let reg = FdtNode::from_mut(&current)
511 .reg()?
512 .ok_or(FdtError::NotFound)?
513 .next()
514 .ok_or(FdtError::NotFound)?;
515 next = if !serial_info.addrs.contains(&reg.addr) {
516 current.delete_and_next_compatible(name)
517 } else {
518 current.next_compatible(name)
519 }
520 }
521 Ok(())
522}
523
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700524fn validate_swiotlb_info(
525 swiotlb_info: &SwiotlbInfo,
526 memory: &Range<usize>,
527) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900528 let size = swiotlb_info.size;
529 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000530
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700531 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000532 error!("Invalid swiotlb size {:#x}", size);
533 return Err(RebootReason::InvalidFdt);
534 }
535
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000536 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000537 error!("Invalid swiotlb alignment {:#x}", align);
538 return Err(RebootReason::InvalidFdt);
539 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700540
Alice Wang9cfbfd62023-06-14 11:19:03 +0000541 if let Some(addr) = swiotlb_info.addr {
542 if addr.checked_add(size).is_none() {
543 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
544 return Err(RebootReason::InvalidFdt);
545 }
546 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700547 if let Some(range) = swiotlb_info.fixed_range() {
548 if !range.is_within(memory) {
549 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
550 return Err(RebootReason::InvalidFdt);
551 }
552 }
553
Jiyong Park6a8789a2023-03-21 14:50:59 +0900554 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000555}
556
Jiyong Park9c63cd12023-03-21 17:53:07 +0900557fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
558 let mut node =
559 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700560
561 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000562 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700563 cstr!("reg"),
564 range.start.try_into().unwrap(),
565 range.len().try_into().unwrap(),
566 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000567 node.nop_property(cstr!("size"))?;
568 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700569 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000570 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700571 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000572 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700573 }
574
Jiyong Park9c63cd12023-03-21 17:53:07 +0900575 Ok(())
576}
577
578fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
579 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
580 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
581 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
582 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
583
584 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000585 // `validate_num_cpus()` checked that this wouldn't panic
586 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900587
588 // range1 is just below range0
589 range1.addr = addr - size;
590 range1.size = Some(size);
591
Pierre-Clément Tosieea2a982024-02-05 15:10:59 +0000592 let (addr0, size0) = range0.to_cells();
593 let (addr1, size1) = range1.to_cells();
594 let value = [addr0, size0.unwrap(), addr1, size1.unwrap()];
Jiyong Park9c63cd12023-03-21 17:53:07 +0900595
596 let mut node =
597 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
598 node.setprop_inplace(cstr!("reg"), flatten(&value))
599}
600
601fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
602 const NUM_INTERRUPTS: usize = 4;
603 const CELLS_PER_INTERRUPT: usize = 3;
604 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
605 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
606 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
607 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
608
609 let num_cpus: u32 = num_cpus.try_into().unwrap();
610 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
611 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
612 *v |= cpu_mask;
613 }
614 for v in value.iter_mut() {
615 *v = v.to_be();
616 }
617
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000618 let value = value.into_inner();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900619
620 let mut node =
621 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosi0edc4d62024-02-05 14:13:53 +0000622 node.setprop_inplace(cstr!("interrupts"), value.as_bytes())
Jiyong Park9c63cd12023-03-21 17:53:07 +0900623}
624
Jiyong Park00ceff32023-03-13 05:43:23 +0000625#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900626pub struct DeviceTreeInfo {
627 pub kernel_range: Option<Range<usize>>,
628 pub initrd_range: Option<Range<usize>>,
629 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900630 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900631 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000632 pci_info: PciInfo,
633 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700634 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900635 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900636 vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000637}
638
639impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000640 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
641 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
642
643 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
644 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000645}
646
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900647pub fn sanitize_device_tree(
648 fdt: &mut [u8],
649 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900650 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900651) -> Result<DeviceTreeInfo, RebootReason> {
652 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
653 error!("Failed to load FDT: {e}");
654 RebootReason::InvalidFdt
655 })?;
656
657 let vm_dtbo = match vm_dtbo {
658 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
659 error!("Failed to load VM DTBO: {e}");
660 RebootReason::InvalidFdt
661 })?),
662 None => None,
663 };
664
665 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900666
Jiyong Parke9d87e82023-03-21 19:28:40 +0900667 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
668 error!("Failed to instantiate FDT from the template DT: {e}");
669 RebootReason::InvalidFdt
670 })?;
671
Jaewan Kim9220e852023-12-01 10:58:40 +0900672 fdt.unpack().map_err(|e| {
673 error!("Failed to unpack DT for patching: {e}");
674 RebootReason::InvalidFdt
675 })?;
676
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900677 if let Some(device_assignment_info) = &info.device_assignment {
678 let vm_dtbo = vm_dtbo.unwrap();
679 device_assignment_info.filter(vm_dtbo).map_err(|e| {
680 error!("Failed to filter VM DTBO: {e}");
681 RebootReason::InvalidFdt
682 })?;
683 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
684 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
685 // it can only be instantiated after validation.
686 unsafe {
687 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
688 error!("Failed to apply filtered VM DTBO: {e}");
689 RebootReason::InvalidFdt
690 })?;
691 }
692 }
693
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900694 if let Some(vm_ref_dt) = vm_ref_dt {
695 let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| {
696 error!("Failed to load VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900697 RebootReason::InvalidFdt
698 })?;
699
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900700 validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| {
701 error!("Failed to apply VM reference DT: {e}");
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900702 RebootReason::InvalidFdt
703 })?;
704 }
705
Jiyong Park9c63cd12023-03-21 17:53:07 +0900706 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900707
Jaewan Kim19b984f2023-12-04 15:16:50 +0900708 // TODO(b/317201360): Ensure no overlapping in <reg> among devices
709
Jaewan Kim9220e852023-12-01 10:58:40 +0900710 fdt.pack().map_err(|e| {
711 error!("Failed to unpack DT after patching: {e}");
712 RebootReason::InvalidFdt
713 })?;
714
Jiyong Park6a8789a2023-03-21 14:50:59 +0900715 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900716}
717
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900718fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900719 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
720 error!("Failed to read kernel range from DT: {e}");
721 RebootReason::InvalidFdt
722 })?;
723
724 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
725 error!("Failed to read initrd range from DT: {e}");
726 RebootReason::InvalidFdt
727 })?;
728
Alice Wang0d527472023-06-13 14:55:38 +0000729 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900730
Jiyong Parke9d87e82023-03-21 19:28:40 +0900731 let bootargs = read_bootargs_from(fdt).map_err(|e| {
732 error!("Failed to read bootargs from DT: {e}");
733 RebootReason::InvalidFdt
734 })?;
735
Jiyong Park6a8789a2023-03-21 14:50:59 +0900736 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
737 error!("Failed to read num cpus from DT: {e}");
738 RebootReason::InvalidFdt
739 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000740 validate_num_cpus(num_cpus).map_err(|e| {
741 error!("Failed to validate num cpus from DT: {e}");
742 RebootReason::InvalidFdt
743 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900744
745 let pci_info = read_pci_info_from(fdt).map_err(|e| {
746 error!("Failed to read pci info from DT: {e}");
747 RebootReason::InvalidFdt
748 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900749 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900750
751 let serial_info = read_serial_info_from(fdt).map_err(|e| {
752 error!("Failed to read serial info from DT: {e}");
753 RebootReason::InvalidFdt
754 })?;
755
Alice Wang9cfbfd62023-06-14 11:19:03 +0000756 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900757 error!("Failed to read swiotlb info from DT: {e}");
758 RebootReason::InvalidFdt
759 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700760 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900761
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900762 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900763 Some(vm_dtbo) => {
764 if let Some(hypervisor) = hyp::get_device_assigner() {
765 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
766 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
767 RebootReason::InvalidFdt
768 })?
769 } else {
770 warn!(
771 "Device assignment is ignored because device assigning hypervisor is missing"
772 );
773 None
774 }
775 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900776 None => None,
777 };
778
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900779 let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| {
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900780 error!("Failed to read names of properties under /avf from DT: {e}");
781 RebootReason::InvalidFdt
782 })?;
Seungjae Yooed67fd52023-11-29 18:54:36 +0900783
Jiyong Park00ceff32023-03-13 05:43:23 +0000784 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900785 kernel_range,
786 initrd_range,
787 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900788 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900789 num_cpus,
790 pci_info,
791 serial_info,
792 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900793 device_assignment,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900794 vm_ref_dt_props_info,
Jiyong Park00ceff32023-03-13 05:43:23 +0000795 })
796}
797
Jiyong Park9c63cd12023-03-21 17:53:07 +0900798fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
799 if let Some(initrd_range) = &info.initrd_range {
800 patch_initrd_range(fdt, initrd_range).map_err(|e| {
801 error!("Failed to patch initrd range to DT: {e}");
802 RebootReason::InvalidFdt
803 })?;
804 }
805 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
806 error!("Failed to patch memory range to DT: {e}");
807 RebootReason::InvalidFdt
808 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900809 if let Some(bootargs) = &info.bootargs {
810 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
811 error!("Failed to patch bootargs to DT: {e}");
812 RebootReason::InvalidFdt
813 })?;
814 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900815 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
816 error!("Failed to patch cpus to DT: {e}");
817 RebootReason::InvalidFdt
818 })?;
819 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
820 error!("Failed to patch pci info to DT: {e}");
821 RebootReason::InvalidFdt
822 })?;
823 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
824 error!("Failed to patch serial info to DT: {e}");
825 RebootReason::InvalidFdt
826 })?;
827 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
828 error!("Failed to patch swiotlb info to DT: {e}");
829 RebootReason::InvalidFdt
830 })?;
831 patch_gic(fdt, info.num_cpus).map_err(|e| {
832 error!("Failed to patch gic info to DT: {e}");
833 RebootReason::InvalidFdt
834 })?;
835 patch_timer(fdt, info.num_cpus).map_err(|e| {
836 error!("Failed to patch timer info to DT: {e}");
837 RebootReason::InvalidFdt
838 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900839 if let Some(device_assignment) = &info.device_assignment {
840 // Note: We patch values after VM DTBO is overlaid because patch may require more space
841 // then VM DTBO's underlying slice is allocated.
842 device_assignment.patch(fdt).map_err(|e| {
843 error!("Failed to patch device assignment info to DT: {e}");
844 RebootReason::InvalidFdt
845 })?;
846 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900847
Jiyong Park9c63cd12023-03-21 17:53:07 +0900848 Ok(())
849}
850
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000851/// Modifies the input DT according to the fields of the configuration.
852pub fn modify_for_next_stage(
853 fdt: &mut Fdt,
854 bcc: &[u8],
855 new_instance: bool,
856 strict_boot: bool,
Alan Stokes65618332023-12-15 14:09:25 +0000857 debug_policy: Option<&[u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900858 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000859 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000860) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000861 if let Some(debug_policy) = debug_policy {
862 let backup = Vec::from(fdt.as_slice());
863 fdt.unpack()?;
864 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
865 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
866 info!("Debug policy applied.");
867 } else {
868 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
869 fdt.unpack()?;
870 }
871 } else {
872 info!("No debug policy found.");
873 fdt.unpack()?;
874 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000875
Jiyong Parke9d87e82023-03-21 19:28:40 +0900876 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000877
Alice Wang56ec45b2023-06-15 08:30:32 +0000878 if let Some(mut chosen) = fdt.chosen_mut()? {
879 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
880 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000881 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000882 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900883 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900884 if let Some(bootargs) = read_bootargs_from(fdt)? {
885 filter_out_dangerous_bootargs(fdt, &bootargs)?;
886 }
887 }
888
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000889 fdt.pack()?;
890
891 Ok(())
892}
893
Jiyong Parke9d87e82023-03-21 19:28:40 +0900894/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
895fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000896 // We reject DTs with missing reserved-memory node as validation should have checked that the
897 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900898 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000899
Jiyong Parke9d87e82023-03-21 19:28:40 +0900900 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000901
Jiyong Parke9d87e82023-03-21 19:28:40 +0900902 let addr: u64 = addr.try_into().unwrap();
903 let size: u64 = size.try_into().unwrap();
904 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000905}
906
Alice Wang56ec45b2023-06-15 08:30:32 +0000907fn empty_or_delete_prop(
908 fdt_node: &mut FdtNodeMut,
909 prop_name: &CStr,
910 keep_prop: bool,
911) -> libfdt::Result<()> {
912 if keep_prop {
913 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000914 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000915 fdt_node
916 .delprop(prop_name)
917 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000918 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000919}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900920
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000921/// Apply the debug policy overlay to the guest DT.
922///
923/// 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 +0000924fn apply_debug_policy(
925 fdt: &mut Fdt,
926 backup_fdt: &Fdt,
927 debug_policy: &[u8],
928) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000929 let mut debug_policy = Vec::from(debug_policy);
930 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900931 Ok(overlay) => overlay,
932 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000933 warn!("Corrupted debug policy found: {e}. Not applying.");
934 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900935 }
936 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900937
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100938 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900939 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000940 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900941 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900942 // A successful restoration is considered success because an invalid debug policy
943 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000944 Ok(false)
945 } else {
946 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900947 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900948}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900949
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000950fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900951 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
952 if let Some(value) = node.getprop_u32(debug_feature_name)? {
953 return Ok(value == 1);
954 }
955 }
956 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
957}
958
959fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000960 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
961 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900962
963 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
964 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
965 ("crashkernel", Box::new(|_| has_crashkernel)),
966 ("console", Box::new(|_| has_console)),
967 ];
968
969 // parse and filter out unwanted
970 let mut filtered = Vec::new();
971 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
972 info!("Invalid bootarg: {e}");
973 FdtError::BadValue
974 })? {
975 match accepted.iter().find(|&t| t.0 == arg.name()) {
976 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
977 _ => debug!("Rejected bootarg {}", arg.as_ref()),
978 }
979 }
980
981 // flatten into a new C-string
982 let mut new_bootargs = Vec::new();
983 for (i, arg) in filtered.iter().enumerate() {
984 if i != 0 {
985 new_bootargs.push(b' '); // separator
986 }
987 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
988 }
989 new_bootargs.push(b'\0');
990
991 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
992 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
993}