blob: 2cd1061fe65e73e93f215d7285a3dbb22fb82d81 [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;
Jiyong Parke9d87e82023-03-21 19:28:40 +090022use alloc::ffi::CString;
Jiyong Parkc23426b2023-04-10 17:32:27 +090023use alloc::vec::Vec;
Jiyong Park0ee65392023-03-27 20:52:45 +090024use core::cmp::max;
25use core::cmp::min;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000026use core::ffi::CStr;
Alice Wangabc7d632023-06-14 09:10:14 +000027use core::fmt;
Jiyong Park9c63cd12023-03-21 17:53:07 +090028use core::mem::size_of;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000029use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000030use cstr::cstr;
Jiyong Park00ceff32023-03-13 05:43:23 +000031use fdtpci::PciMemoryFlags;
32use fdtpci::PciRangeType;
33use libfdt::AddressRange;
34use libfdt::CellIterator;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +000035use libfdt::Fdt;
36use libfdt::FdtError;
Jiyong Park9c63cd12023-03-21 17:53:07 +090037use libfdt::FdtNode;
Alice Wang56ec45b2023-06-15 08:30:32 +000038use libfdt::FdtNodeMut;
Jiyong Park83316122023-03-21 09:39:39 +090039use log::debug;
Jiyong Park00ceff32023-03-13 05:43:23 +000040use log::error;
Jiyong Parkc23426b2023-04-10 17:32:27 +090041use log::info;
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +000042use log::warn;
Jiyong Park00ceff32023-03-13 05:43:23 +000043use tinyvec::ArrayVec;
Alice Wanga3971062023-06-13 11:48:53 +000044use vmbase::fdt::SwiotlbInfo;
Alice Wang63f4c9e2023-06-12 09:36:43 +000045use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR};
Alice Wangeacb7382023-06-05 12:53:54 +000046use vmbase::memory::SIZE_4KB;
47use vmbase::util::flatten;
Alice Wang4be4dd02023-06-07 07:50:40 +000048use vmbase::util::RangeExt as _;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000049
Alice Wangabc7d632023-06-14 09:10:14 +000050/// An enumeration of errors that can occur during the FDT validation.
51#[derive(Clone, Debug)]
52pub enum FdtValidationError {
53 /// Invalid CPU count.
54 InvalidCpuCount(usize),
55}
56
57impl fmt::Display for FdtValidationError {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 match self {
60 Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"),
61 }
62 }
63}
64
Jiyong Park6a8789a2023-03-21 14:50:59 +090065/// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is
66/// not an error.
67fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090068 let addr = cstr!("kernel-address");
69 let size = cstr!("kernel-size");
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000070
Jiyong Parkb87f3302023-03-21 10:03:11 +090071 if let Some(config) = fdt.node(cstr!("/config"))? {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +000072 if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) {
73 let addr = addr as usize;
74 let size = size as usize;
75
76 return Ok(Some(addr..(addr + size)));
77 }
78 }
79
80 Ok(None)
81}
82
Jiyong Park6a8789a2023-03-21 14:50:59 +090083/// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an
84/// error as there can be initrd-less VM.
85fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> {
Jiyong Parkb87f3302023-03-21 10:03:11 +090086 let start = cstr!("linux,initrd-start");
87 let end = cstr!("linux,initrd-end");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000088
89 if let Some(chosen) = fdt.chosen()? {
90 if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) {
91 return Ok(Some((start as usize)..(end as usize)));
92 }
93 }
94
95 Ok(None)
96}
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +000097
Jiyong Park9c63cd12023-03-21 17:53:07 +090098fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> {
99 let start = u32::try_from(initrd_range.start).unwrap();
100 let end = u32::try_from(initrd_range.end).unwrap();
101
102 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
103 node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?;
104 node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?;
105 Ok(())
106}
107
Jiyong Parke9d87e82023-03-21 19:28:40 +0900108fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> {
109 if let Some(chosen) = fdt.chosen()? {
110 if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? {
111 // We need to copy the string to heap because the original fdt will be invalidated
112 // by the templated DT
113 let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?;
114 return Ok(Some(copy));
115 }
116 }
117 Ok(None)
118}
119
120fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
121 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900122 // This function is called before the verification is done. So, we just copy the bootargs to
123 // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function
124 // if the VM is not debuggable.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900125 node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul())
126}
127
Alice Wang0d527472023-06-13 14:55:38 +0000128/// Reads and validates the memory range in the DT.
129///
130/// Only one memory range is expected with the crosvm setup for now.
131fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> {
132 let mut memory = fdt.memory().map_err(|e| {
133 error!("Failed to read memory range from DT: {e}");
134 RebootReason::InvalidFdt
135 })?;
136 let range = memory.next().ok_or_else(|| {
137 error!("The /memory node in the DT contains no range.");
138 RebootReason::InvalidFdt
139 })?;
140 if memory.next().is_some() {
141 warn!(
142 "The /memory node in the DT contains more than one memory range, \
143 while only one is expected."
144 );
145 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900146 let base = range.start;
Alice Wange243d462023-06-06 15:18:12 +0000147 if base != MEM_START {
148 error!("Memory base address {:#x} is not {:#x}", base, MEM_START);
Jiyong Park00ceff32023-03-13 05:43:23 +0000149 return Err(RebootReason::InvalidFdt);
150 }
151
Jiyong Park6a8789a2023-03-21 14:50:59 +0900152 let size = range.len();
Jiyong Park00ceff32023-03-13 05:43:23 +0000153 if size % GUEST_PAGE_SIZE != 0 {
154 error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE);
155 return Err(RebootReason::InvalidFdt);
156 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000157
Jiyong Park6a8789a2023-03-21 14:50:59 +0900158 if size == 0 {
159 error!("Memory size is 0");
160 return Err(RebootReason::InvalidFdt);
161 }
Alice Wang0d527472023-06-13 14:55:38 +0000162 Ok(range)
Jiyong Park00ceff32023-03-13 05:43:23 +0000163}
164
Jiyong Park9c63cd12023-03-21 17:53:07 +0900165fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> {
166 let size = memory_range.len() as u64;
Jiyong Park0ee65392023-03-27 20:52:45 +0900167 fdt.node_mut(cstr!("/memory"))?
168 .ok_or(FdtError::NotFound)?
Alice Wange243d462023-06-06 15:18:12 +0000169 .setprop_inplace(cstr!("reg"), flatten(&[MEM_START.to_be_bytes(), size.to_be_bytes()]))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900170}
171
Jiyong Park6a8789a2023-03-21 14:50:59 +0900172/// Read the number of CPUs from DT
173fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> {
174 Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count())
175}
176
177/// Validate number of CPUs
Alice Wangabc7d632023-06-14 09:10:14 +0000178fn validate_num_cpus(num_cpus: usize) -> Result<(), FdtValidationError> {
179 if num_cpus == 0 || DeviceTreeInfo::gic_patched_size(num_cpus).is_none() {
180 Err(FdtValidationError::InvalidCpuCount(num_cpus))
181 } else {
182 Ok(())
Jiyong Park6a8789a2023-03-21 14:50:59 +0900183 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900184}
185
186/// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest.
187fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
188 let cpu = cstr!("arm,arm-v8");
189 let mut next = fdt.root_mut()?.next_compatible(cpu)?;
190 for _ in 0..num_cpus {
191 next = if let Some(current) = next {
192 current.next_compatible(cpu)?
193 } else {
194 return Err(FdtError::NoSpace);
195 };
196 }
197 while let Some(current) = next {
198 next = current.delete_and_next_compatible(cpu)?;
199 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900200 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000201}
202
Seungjae Yooed67fd52023-11-29 18:54:36 +0900203fn read_vendor_public_key_from(fdt: &Fdt) -> libfdt::Result<Option<Vec<u8>>> {
204 if let Some(avf_node) = fdt.node(cstr!("/avf"))? {
205 if let Some(vendor_public_key) = avf_node.getprop(cstr!("vendor_public_key"))? {
206 return Ok(Some(vendor_public_key.to_vec()));
207 }
208 }
209 Ok(None)
210}
211
212fn patch_vendor_public_key(fdt: &mut Fdt, vendor_public_key: &[u8]) -> libfdt::Result<()> {
213 let mut root_node = fdt.root_mut()?;
214 let mut avf_node = root_node.add_subnode(cstr!("/avf"))?;
215 avf_node.setprop(cstr!("vendor_public_key"), vendor_public_key)?;
216 Ok(())
217}
218
Jiyong Park00ceff32023-03-13 05:43:23 +0000219#[derive(Debug)]
Jiyong Park00ceff32023-03-13 05:43:23 +0000220struct PciInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900221 ranges: [PciAddrRange; 2],
222 irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>,
223 irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000224}
225
Jiyong Park6a8789a2023-03-21 14:50:59 +0900226impl PciInfo {
227 const IRQ_MASK_CELLS: usize = 4;
228 const IRQ_MAP_CELLS: usize = 10;
Nikita Ioffe85d80262023-07-12 17:34:07 +0100229 const MAX_IRQS: usize = 10;
Jiyong Park00ceff32023-03-13 05:43:23 +0000230}
231
Jiyong Park6a8789a2023-03-21 14:50:59 +0900232type PciAddrRange = AddressRange<(u32, u64), u64, u64>;
233type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS];
234type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS];
Jiyong Park00ceff32023-03-13 05:43:23 +0000235
236/// Iterator that takes N cells as a chunk
237struct CellChunkIterator<'a, const N: usize> {
238 cells: CellIterator<'a>,
239}
240
241impl<'a, const N: usize> CellChunkIterator<'a, N> {
242 fn new(cells: CellIterator<'a>) -> Self {
243 Self { cells }
244 }
245}
246
247impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> {
248 type Item = [u32; N];
249 fn next(&mut self) -> Option<Self::Item> {
250 let mut ret: Self::Item = [0; N];
251 for i in ret.iter_mut() {
252 *i = self.cells.next()?;
253 }
254 Some(ret)
255 }
256}
257
Jiyong Park6a8789a2023-03-21 14:50:59 +0900258/// Read pci host controller ranges, irq maps, and irq map masks from DT
259fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> {
260 let node =
261 fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?;
262
263 let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?;
264 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
265 let range1 = ranges.next().ok_or(FdtError::NotFound)?;
266
267 let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000268 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks);
269 let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
270
271 if chunks.next().is_some() {
272 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
273 return Err(FdtError::NoSpace);
274 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900275
276 let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosiaa0f6552023-07-12 14:49:35 +0000277 let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps);
278 let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect();
279
280 if chunks.next().is_some() {
281 warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS);
282 return Err(FdtError::NoSpace);
283 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900284
285 Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps })
286}
287
Jiyong Park0ee65392023-03-27 20:52:45 +0900288fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900289 for range in pci_info.ranges.iter() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900290 validate_pci_addr_range(range, memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900291 }
292 for irq_mask in pci_info.irq_masks.iter() {
293 validate_pci_irq_mask(irq_mask)?;
294 }
295 for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() {
296 validate_pci_irq_map(irq_map, idx)?;
297 }
298 Ok(())
299}
300
Jiyong Park0ee65392023-03-27 20:52:45 +0900301fn validate_pci_addr_range(
302 range: &PciAddrRange,
303 memory_range: &Range<usize>,
304) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900305 let mem_flags = PciMemoryFlags(range.addr.0);
306 let range_type = mem_flags.range_type();
307 let prefetchable = mem_flags.prefetchable();
308 let bus_addr = range.addr.1;
309 let cpu_addr = range.parent_addr;
310 let size = range.size;
311
312 if range_type != PciRangeType::Memory64 {
313 error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr);
314 return Err(RebootReason::InvalidFdt);
315 }
316 if prefetchable {
317 error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr);
318 return Err(RebootReason::InvalidFdt);
319 }
320 // Enforce ID bus-to-cpu mappings, as used by crosvm.
321 if bus_addr != cpu_addr {
322 error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr);
323 return Err(RebootReason::InvalidFdt);
324 }
325
Jiyong Park0ee65392023-03-27 20:52:45 +0900326 let Some(bus_end) = bus_addr.checked_add(size) else {
327 error!("PCI address range size {:#x} overflows", size);
328 return Err(RebootReason::InvalidFdt);
329 };
Alice Wang63f4c9e2023-06-12 09:36:43 +0000330 if bus_end > MAX_VIRT_ADDR.try_into().unwrap() {
Jiyong Park0ee65392023-03-27 20:52:45 +0900331 error!("PCI address end {:#x} is outside of translatable range", bus_end);
332 return Err(RebootReason::InvalidFdt);
333 }
334
335 let memory_start = memory_range.start.try_into().unwrap();
336 let memory_end = memory_range.end.try_into().unwrap();
337
338 if max(bus_addr, memory_start) < min(bus_end, memory_end) {
339 error!(
340 "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}",
341 bus_addr, bus_end, memory_start, memory_end
342 );
Jiyong Park6a8789a2023-03-21 14:50:59 +0900343 return Err(RebootReason::InvalidFdt);
344 }
345
346 Ok(())
347}
348
349fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000350 const IRQ_MASK_ADDR_HI: u32 = 0xf800;
351 const IRQ_MASK_ADDR_ME: u32 = 0x0;
352 const IRQ_MASK_ADDR_LO: u32 = 0x0;
353 const IRQ_MASK_ANY_IRQ: u32 = 0x7;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900354 const EXPECTED: PciIrqMask =
Jiyong Park00ceff32023-03-13 05:43:23 +0000355 [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ];
Jiyong Park6a8789a2023-03-21 14:50:59 +0900356 if *irq_mask != EXPECTED {
357 error!("Invalid PCI irq mask {:#?}", irq_mask);
358 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000359 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900360 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000361}
362
Jiyong Park6a8789a2023-03-21 14:50:59 +0900363fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> {
Jiyong Park00ceff32023-03-13 05:43:23 +0000364 const PCI_DEVICE_IDX: usize = 11;
365 const PCI_IRQ_ADDR_ME: u32 = 0;
366 const PCI_IRQ_ADDR_LO: u32 = 0;
367 const PCI_IRQ_INTC: u32 = 1;
368 const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs
369 const GIC_SPI: u32 = 0;
370 const IRQ_TYPE_LEVEL_HIGH: u32 = 4;
371
Jiyong Park6a8789a2023-03-21 14:50:59 +0900372 let pci_addr = (irq_map[0], irq_map[1], irq_map[2]);
373 let pci_irq_number = irq_map[3];
374 let _controller_phandle = irq_map[4]; // skipped.
375 let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC
376 // interrupt-cells is <3> for GIC
377 let gic_peripheral_interrupt_type = irq_map[7];
378 let gic_irq_number = irq_map[8];
379 let gic_irq_type = irq_map[9];
Jiyong Park00ceff32023-03-13 05:43:23 +0000380
Jiyong Park6a8789a2023-03-21 14:50:59 +0900381 let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32;
382 let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO);
Jiyong Park00ceff32023-03-13 05:43:23 +0000383
Jiyong Park6a8789a2023-03-21 14:50:59 +0900384 if pci_addr != expected_pci_addr {
385 error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \
386 {:#x} {:#x} {:#x}",
387 pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2);
388 return Err(RebootReason::InvalidFdt);
389 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000390
Jiyong Park6a8789a2023-03-21 14:50:59 +0900391 if pci_irq_number != PCI_IRQ_INTC {
392 error!(
393 "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}",
394 pci_irq_number, PCI_IRQ_INTC
395 );
396 return Err(RebootReason::InvalidFdt);
397 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000398
Jiyong Park6a8789a2023-03-21 14:50:59 +0900399 if gic_addr != (0, 0) {
400 error!(
401 "GIC address {:#x} {:#x} in interrupt-map is different from expected address \
402 {:#x} {:#x}",
403 gic_addr.0, gic_addr.1, 0, 0
404 );
405 return Err(RebootReason::InvalidFdt);
406 }
407
408 if gic_peripheral_interrupt_type != GIC_SPI {
409 error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \
410 {:#x}", gic_peripheral_interrupt_type, GIC_SPI);
411 return Err(RebootReason::InvalidFdt);
412 }
413
414 let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32);
415 if gic_irq_number != irq_nr {
416 error!(
417 "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}",
418 gic_irq_number, irq_nr
419 );
420 return Err(RebootReason::InvalidFdt);
421 }
422
423 if gic_irq_type != IRQ_TYPE_LEVEL_HIGH {
424 error!(
425 "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}",
426 gic_irq_type, IRQ_TYPE_LEVEL_HIGH
427 );
428 return Err(RebootReason::InvalidFdt);
Jiyong Park00ceff32023-03-13 05:43:23 +0000429 }
430 Ok(())
431}
432
Jiyong Park9c63cd12023-03-21 17:53:07 +0900433fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> {
434 let mut node = fdt
435 .root_mut()?
436 .next_compatible(cstr!("pci-host-cam-generic"))?
437 .ok_or(FdtError::NotFound)?;
438
439 let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>();
440 node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?;
441
442 let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>();
443 node.trimprop(cstr!("interrupt-map"), irq_maps_size)?;
444
445 node.setprop_inplace(
446 cstr!("ranges"),
447 flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]),
448 )
449}
450
Jiyong Park00ceff32023-03-13 05:43:23 +0000451#[derive(Default, Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900452struct SerialInfo {
453 addrs: ArrayVec<[u64; Self::MAX_SERIALS]>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000454}
455
456impl SerialInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900457 const MAX_SERIALS: usize = 4;
Jiyong Park00ceff32023-03-13 05:43:23 +0000458}
459
Jiyong Park6a8789a2023-03-21 14:50:59 +0900460fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> {
461 let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default();
462 for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) {
Alice Wang6ff2d0c2023-09-19 15:28:43 +0000463 let reg = node.first_reg()?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900464 addrs.push(reg.addr);
Jiyong Park00ceff32023-03-13 05:43:23 +0000465 }
Jiyong Park6a8789a2023-03-21 14:50:59 +0900466 Ok(SerialInfo { addrs })
Jiyong Park00ceff32023-03-13 05:43:23 +0000467}
468
Jiyong Park9c63cd12023-03-21 17:53:07 +0900469/// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown
470fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> {
471 let name = cstr!("ns16550a");
472 let mut next = fdt.root_mut()?.next_compatible(name);
473 while let Some(current) = next? {
474 let reg = FdtNode::from_mut(&current)
475 .reg()?
476 .ok_or(FdtError::NotFound)?
477 .next()
478 .ok_or(FdtError::NotFound)?;
479 next = if !serial_info.addrs.contains(&reg.addr) {
480 current.delete_and_next_compatible(name)
481 } else {
482 current.next_compatible(name)
483 }
484 }
485 Ok(())
486}
487
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700488fn validate_swiotlb_info(
489 swiotlb_info: &SwiotlbInfo,
490 memory: &Range<usize>,
491) -> Result<(), RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900492 let size = swiotlb_info.size;
493 let align = swiotlb_info.align;
Jiyong Park00ceff32023-03-13 05:43:23 +0000494
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700495 if size == 0 || (size % GUEST_PAGE_SIZE) != 0 {
Jiyong Park00ceff32023-03-13 05:43:23 +0000496 error!("Invalid swiotlb size {:#x}", size);
497 return Err(RebootReason::InvalidFdt);
498 }
499
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000500 if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) {
Jiyong Park00ceff32023-03-13 05:43:23 +0000501 error!("Invalid swiotlb alignment {:#x}", align);
502 return Err(RebootReason::InvalidFdt);
503 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700504
Alice Wang9cfbfd62023-06-14 11:19:03 +0000505 if let Some(addr) = swiotlb_info.addr {
506 if addr.checked_add(size).is_none() {
507 error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}");
508 return Err(RebootReason::InvalidFdt);
509 }
510 }
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700511 if let Some(range) = swiotlb_info.fixed_range() {
512 if !range.is_within(memory) {
513 error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}");
514 return Err(RebootReason::InvalidFdt);
515 }
516 }
517
Jiyong Park6a8789a2023-03-21 14:50:59 +0900518 Ok(())
Jiyong Park00ceff32023-03-13 05:43:23 +0000519}
520
Jiyong Park9c63cd12023-03-21 17:53:07 +0900521fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> {
522 let mut node =
523 fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700524
525 if let Some(range) = swiotlb_info.fixed_range() {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000526 node.setprop_addrrange_inplace(
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700527 cstr!("reg"),
528 range.start.try_into().unwrap(),
529 range.len().try_into().unwrap(),
530 )?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000531 node.nop_property(cstr!("size"))?;
532 node.nop_property(cstr!("alignment"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700533 } else {
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000534 node.nop_property(cstr!("reg"))?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700535 node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?;
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000536 node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700537 }
538
Jiyong Park9c63cd12023-03-21 17:53:07 +0900539 Ok(())
540}
541
542fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
543 let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?;
544 let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?;
545 let range0 = ranges.next().ok_or(FdtError::NotFound)?;
546 let mut range1 = ranges.next().ok_or(FdtError::NotFound)?;
547
548 let addr = range0.addr;
Alice Wangabc7d632023-06-14 09:10:14 +0000549 // `validate_num_cpus()` checked that this wouldn't panic
550 let size = u64::try_from(DeviceTreeInfo::gic_patched_size(num_cpus).unwrap()).unwrap();
Jiyong Park9c63cd12023-03-21 17:53:07 +0900551
552 // range1 is just below range0
553 range1.addr = addr - size;
554 range1.size = Some(size);
555
556 let range0 = range0.to_cells();
557 let range1 = range1.to_cells();
558 let value = [
559 range0.0, // addr
560 range0.1.unwrap(), //size
561 range1.0, // addr
562 range1.1.unwrap(), //size
563 ];
564
565 let mut node =
566 fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?;
567 node.setprop_inplace(cstr!("reg"), flatten(&value))
568}
569
570fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> {
571 const NUM_INTERRUPTS: usize = 4;
572 const CELLS_PER_INTERRUPT: usize = 3;
573 let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?;
574 let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?;
575 let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> =
576 interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect();
577
578 let num_cpus: u32 = num_cpus.try_into().unwrap();
579 let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8;
580 for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) {
581 *v |= cpu_mask;
582 }
583 for v in value.iter_mut() {
584 *v = v.to_be();
585 }
586
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100587 // SAFETY: array size is the same
Jiyong Park9c63cd12023-03-21 17:53:07 +0900588 let value = unsafe {
589 core::mem::transmute::<
590 [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT],
591 [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()],
592 >(value.into_inner())
593 };
594
595 let mut node =
596 fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?;
597 node.setprop_inplace(cstr!("interrupts"), value.as_slice())
598}
599
Jiyong Park00ceff32023-03-13 05:43:23 +0000600#[derive(Debug)]
Jiyong Park6a8789a2023-03-21 14:50:59 +0900601pub struct DeviceTreeInfo {
602 pub kernel_range: Option<Range<usize>>,
603 pub initrd_range: Option<Range<usize>>,
604 pub memory_range: Range<usize>,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900605 bootargs: Option<CString>,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900606 num_cpus: usize,
Jiyong Park00ceff32023-03-13 05:43:23 +0000607 pci_info: PciInfo,
608 serial_info: SerialInfo,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700609 pub swiotlb_info: SwiotlbInfo,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900610 device_assignment: Option<DeviceAssignmentInfo>,
Seungjae Yooed67fd52023-11-29 18:54:36 +0900611 vendor_public_key: Option<Vec<u8>>,
Jiyong Park00ceff32023-03-13 05:43:23 +0000612}
613
614impl DeviceTreeInfo {
Alice Wangabc7d632023-06-14 09:10:14 +0000615 fn gic_patched_size(num_cpus: usize) -> Option<usize> {
616 const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB;
617
618 GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus)
619 }
Jiyong Park00ceff32023-03-13 05:43:23 +0000620}
621
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900622pub fn sanitize_device_tree(
623 fdt: &mut [u8],
624 vm_dtbo: Option<&mut [u8]>,
625) -> Result<DeviceTreeInfo, RebootReason> {
626 let fdt = Fdt::from_mut_slice(fdt).map_err(|e| {
627 error!("Failed to load FDT: {e}");
628 RebootReason::InvalidFdt
629 })?;
630
631 let vm_dtbo = match vm_dtbo {
632 Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| {
633 error!("Failed to load VM DTBO: {e}");
634 RebootReason::InvalidFdt
635 })?),
636 None => None,
637 };
638
639 let info = parse_device_tree(fdt, vm_dtbo.as_deref())?;
Jiyong Park83316122023-03-21 09:39:39 +0900640
Jiyong Parke9d87e82023-03-21 19:28:40 +0900641 fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| {
642 error!("Failed to instantiate FDT from the template DT: {e}");
643 RebootReason::InvalidFdt
644 })?;
645
Jaewan Kim9220e852023-12-01 10:58:40 +0900646 fdt.unpack().map_err(|e| {
647 error!("Failed to unpack DT for patching: {e}");
648 RebootReason::InvalidFdt
649 })?;
650
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900651 if let Some(device_assignment_info) = &info.device_assignment {
652 let vm_dtbo = vm_dtbo.unwrap();
653 device_assignment_info.filter(vm_dtbo).map_err(|e| {
654 error!("Failed to filter VM DTBO: {e}");
655 RebootReason::InvalidFdt
656 })?;
657 // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block.
658 // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because
659 // it can only be instantiated after validation.
660 unsafe {
661 fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| {
662 error!("Failed to apply filtered VM DTBO: {e}");
663 RebootReason::InvalidFdt
664 })?;
665 }
666 }
667
Jiyong Park9c63cd12023-03-21 17:53:07 +0900668 patch_device_tree(fdt, &info)?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900669
Jaewan Kim9220e852023-12-01 10:58:40 +0900670 fdt.pack().map_err(|e| {
671 error!("Failed to unpack DT after patching: {e}");
672 RebootReason::InvalidFdt
673 })?;
674
Jiyong Park6a8789a2023-03-21 14:50:59 +0900675 Ok(info)
Jiyong Park83316122023-03-21 09:39:39 +0900676}
677
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900678fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900679 let kernel_range = read_kernel_range_from(fdt).map_err(|e| {
680 error!("Failed to read kernel range from DT: {e}");
681 RebootReason::InvalidFdt
682 })?;
683
684 let initrd_range = read_initrd_range_from(fdt).map_err(|e| {
685 error!("Failed to read initrd range from DT: {e}");
686 RebootReason::InvalidFdt
687 })?;
688
Alice Wang0d527472023-06-13 14:55:38 +0000689 let memory_range = read_and_validate_memory_range(fdt)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900690
Jiyong Parke9d87e82023-03-21 19:28:40 +0900691 let bootargs = read_bootargs_from(fdt).map_err(|e| {
692 error!("Failed to read bootargs from DT: {e}");
693 RebootReason::InvalidFdt
694 })?;
695
Jiyong Park6a8789a2023-03-21 14:50:59 +0900696 let num_cpus = read_num_cpus_from(fdt).map_err(|e| {
697 error!("Failed to read num cpus from DT: {e}");
698 RebootReason::InvalidFdt
699 })?;
Alice Wangabc7d632023-06-14 09:10:14 +0000700 validate_num_cpus(num_cpus).map_err(|e| {
701 error!("Failed to validate num cpus from DT: {e}");
702 RebootReason::InvalidFdt
703 })?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900704
705 let pci_info = read_pci_info_from(fdt).map_err(|e| {
706 error!("Failed to read pci info from DT: {e}");
707 RebootReason::InvalidFdt
708 })?;
Jiyong Park0ee65392023-03-27 20:52:45 +0900709 validate_pci_info(&pci_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900710
711 let serial_info = read_serial_info_from(fdt).map_err(|e| {
712 error!("Failed to read serial info from DT: {e}");
713 RebootReason::InvalidFdt
714 })?;
715
Alice Wang9cfbfd62023-06-14 11:19:03 +0000716 let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900717 error!("Failed to read swiotlb info from DT: {e}");
718 RebootReason::InvalidFdt
719 })?;
Srivatsa Vaddagiri2df297f2023-04-12 03:11:05 -0700720 validate_swiotlb_info(&swiotlb_info, &memory_range)?;
Jiyong Park6a8789a2023-03-21 14:50:59 +0900721
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900722 let device_assignment = match vm_dtbo {
Jaewan Kim52477ae2023-11-21 21:20:52 +0900723 Some(vm_dtbo) => {
724 if let Some(hypervisor) = hyp::get_device_assigner() {
725 DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| {
726 error!("Failed to parse device assignment from DT and VM DTBO: {e}");
727 RebootReason::InvalidFdt
728 })?
729 } else {
730 warn!(
731 "Device assignment is ignored because device assigning hypervisor is missing"
732 );
733 None
734 }
735 }
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900736 None => None,
737 };
738
Seungjae Yooed67fd52023-11-29 18:54:36 +0900739 // TODO(b/285854379) : A temporary solution lives. This is for enabling
740 // microdroid vendor partition for non-protected VM as well. When passing
741 // DT path containing vendor_public_key via fstab, init stage will check
742 // if vendor_public_key exists in the init stage, regardless the protection.
743 // Adding this temporary solution will prevent fatal in init stage for
744 // protected VM. However, this data is not trustable without validating
745 // with vendor public key value comes from ABL.
746 let vendor_public_key = read_vendor_public_key_from(fdt).map_err(|e| {
747 error!("Failed to read vendor_public_key from DT: {e}");
748 RebootReason::InvalidFdt
749 })?;
750
Jiyong Park00ceff32023-03-13 05:43:23 +0000751 Ok(DeviceTreeInfo {
Jiyong Park6a8789a2023-03-21 14:50:59 +0900752 kernel_range,
753 initrd_range,
754 memory_range,
Jiyong Parke9d87e82023-03-21 19:28:40 +0900755 bootargs,
Jiyong Park6a8789a2023-03-21 14:50:59 +0900756 num_cpus,
757 pci_info,
758 serial_info,
759 swiotlb_info,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900760 device_assignment,
Seungjae Yooed67fd52023-11-29 18:54:36 +0900761 vendor_public_key,
Jiyong Park00ceff32023-03-13 05:43:23 +0000762 })
763}
764
Jiyong Park9c63cd12023-03-21 17:53:07 +0900765fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> {
766 if let Some(initrd_range) = &info.initrd_range {
767 patch_initrd_range(fdt, initrd_range).map_err(|e| {
768 error!("Failed to patch initrd range to DT: {e}");
769 RebootReason::InvalidFdt
770 })?;
771 }
772 patch_memory_range(fdt, &info.memory_range).map_err(|e| {
773 error!("Failed to patch memory range to DT: {e}");
774 RebootReason::InvalidFdt
775 })?;
Jiyong Parke9d87e82023-03-21 19:28:40 +0900776 if let Some(bootargs) = &info.bootargs {
777 patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| {
778 error!("Failed to patch bootargs to DT: {e}");
779 RebootReason::InvalidFdt
780 })?;
781 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900782 patch_num_cpus(fdt, info.num_cpus).map_err(|e| {
783 error!("Failed to patch cpus to DT: {e}");
784 RebootReason::InvalidFdt
785 })?;
786 patch_pci_info(fdt, &info.pci_info).map_err(|e| {
787 error!("Failed to patch pci info to DT: {e}");
788 RebootReason::InvalidFdt
789 })?;
790 patch_serial_info(fdt, &info.serial_info).map_err(|e| {
791 error!("Failed to patch serial info to DT: {e}");
792 RebootReason::InvalidFdt
793 })?;
794 patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| {
795 error!("Failed to patch swiotlb info to DT: {e}");
796 RebootReason::InvalidFdt
797 })?;
798 patch_gic(fdt, info.num_cpus).map_err(|e| {
799 error!("Failed to patch gic info to DT: {e}");
800 RebootReason::InvalidFdt
801 })?;
802 patch_timer(fdt, info.num_cpus).map_err(|e| {
803 error!("Failed to patch timer info to DT: {e}");
804 RebootReason::InvalidFdt
805 })?;
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900806 if let Some(device_assignment) = &info.device_assignment {
807 // Note: We patch values after VM DTBO is overlaid because patch may require more space
808 // then VM DTBO's underlying slice is allocated.
809 device_assignment.patch(fdt).map_err(|e| {
810 error!("Failed to patch device assignment info to DT: {e}");
811 RebootReason::InvalidFdt
812 })?;
813 }
Seungjae Yooed67fd52023-11-29 18:54:36 +0900814 if let Some(vendor_public_key) = &info.vendor_public_key {
815 patch_vendor_public_key(fdt, vendor_public_key).map_err(|e| {
816 error!("Failed to patch vendor_public_key to DT: {e}");
817 RebootReason::InvalidFdt
818 })?;
819 }
Jiyong Parke9d87e82023-03-21 19:28:40 +0900820
Jiyong Park9c63cd12023-03-21 17:53:07 +0900821 Ok(())
822}
823
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000824/// Modifies the input DT according to the fields of the configuration.
825pub fn modify_for_next_stage(
826 fdt: &mut Fdt,
827 bcc: &[u8],
828 new_instance: bool,
829 strict_boot: bool,
Jiyong Parkc23426b2023-04-10 17:32:27 +0900830 debug_policy: Option<&mut [u8]>,
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900831 debuggable: bool,
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000832 kaslr_seed: u64,
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000833) -> libfdt::Result<()> {
Pierre-Clément Tosieb887ac2023-05-02 13:33:37 +0000834 if let Some(debug_policy) = debug_policy {
835 let backup = Vec::from(fdt.as_slice());
836 fdt.unpack()?;
837 let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap();
838 if apply_debug_policy(fdt, backup_fdt, debug_policy)? {
839 info!("Debug policy applied.");
840 } else {
841 // apply_debug_policy restored fdt to backup_fdt so unpack it again.
842 fdt.unpack()?;
843 }
844 } else {
845 info!("No debug policy found.");
846 fdt.unpack()?;
847 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000848
Jiyong Parke9d87e82023-03-21 19:28:40 +0900849 patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000850
Alice Wang56ec45b2023-06-15 08:30:32 +0000851 if let Some(mut chosen) = fdt.chosen_mut()? {
852 empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?;
853 empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?;
Pierre-Clément Tosi80251972023-07-12 12:51:12 +0000854 chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?;
Alice Wang56ec45b2023-06-15 08:30:32 +0000855 };
Jiyong Park32f37ef2023-05-17 16:15:58 +0900856 if !debuggable {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900857 if let Some(bootargs) = read_bootargs_from(fdt)? {
858 filter_out_dangerous_bootargs(fdt, &bootargs)?;
859 }
860 }
861
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000862 fdt.pack()?;
863
864 Ok(())
865}
866
Jiyong Parke9d87e82023-03-21 19:28:40 +0900867/// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
868fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000869 // We reject DTs with missing reserved-memory node as validation should have checked that the
870 // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900871 let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000872
Jiyong Parke9d87e82023-03-21 19:28:40 +0900873 let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?;
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000874
Jiyong Parke9d87e82023-03-21 19:28:40 +0900875 let addr: u64 = addr.try_into().unwrap();
876 let size: u64 = size.try_into().unwrap();
877 node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()]))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000878}
879
Alice Wang56ec45b2023-06-15 08:30:32 +0000880fn empty_or_delete_prop(
881 fdt_node: &mut FdtNodeMut,
882 prop_name: &CStr,
883 keep_prop: bool,
884) -> libfdt::Result<()> {
885 if keep_prop {
886 fdt_node.setprop_empty(prop_name)
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000887 } else {
Alice Wang56ec45b2023-06-15 08:30:32 +0000888 fdt_node
889 .delprop(prop_name)
890 .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) })
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000891 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000892}
Jiyong Parkc23426b2023-04-10 17:32:27 +0900893
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000894/// Apply the debug policy overlay to the guest DT.
895///
896/// 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 +0000897fn apply_debug_policy(
898 fdt: &mut Fdt,
899 backup_fdt: &Fdt,
900 debug_policy: &[u8],
901) -> libfdt::Result<bool> {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000902 let mut debug_policy = Vec::from(debug_policy);
903 let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) {
Jiyong Parkc23426b2023-04-10 17:32:27 +0900904 Ok(overlay) => overlay,
905 Err(e) => {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000906 warn!("Corrupted debug policy found: {e}. Not applying.");
907 return Ok(false);
Jiyong Parkc23426b2023-04-10 17:32:27 +0900908 }
909 };
Jiyong Parkc23426b2023-04-10 17:32:27 +0900910
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100911 // SAFETY: on failure, the corrupted DT is restored using the backup.
Jiyong Parkc23426b2023-04-10 17:32:27 +0900912 if let Err(e) = unsafe { fdt.apply_overlay(overlay) } {
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000913 warn!("Failed to apply debug policy: {e}. Recovering...");
Jiyong Parkc23426b2023-04-10 17:32:27 +0900914 fdt.copy_from_slice(backup_fdt.as_slice())?;
Jiyong Parkc23426b2023-04-10 17:32:27 +0900915 // A successful restoration is considered success because an invalid debug policy
916 // shouldn't DOS the pvmfw
Pierre-Clément Tosia50167b2023-05-02 13:19:29 +0000917 Ok(false)
918 } else {
919 Ok(true)
Jiyong Parkc23426b2023-04-10 17:32:27 +0900920 }
Jiyong Parkc23426b2023-04-10 17:32:27 +0900921}
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900922
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000923fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> {
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900924 if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? {
925 if let Some(value) = node.getprop_u32(debug_feature_name)? {
926 return Ok(value == 1);
927 }
928 }
929 Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature
930}
931
932fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> {
Pierre-Clément Tosi1fbc2e92023-05-02 17:28:17 +0000933 let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?;
934 let has_console = has_common_debug_policy(fdt, cstr!("log"))?;
Jiyong Parkc5d2ef22023-04-11 01:23:46 +0900935
936 let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[
937 ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })),
938 ("crashkernel", Box::new(|_| has_crashkernel)),
939 ("console", Box::new(|_| has_console)),
940 ];
941
942 // parse and filter out unwanted
943 let mut filtered = Vec::new();
944 for arg in BootArgsIterator::new(bootargs).map_err(|e| {
945 info!("Invalid bootarg: {e}");
946 FdtError::BadValue
947 })? {
948 match accepted.iter().find(|&t| t.0 == arg.name()) {
949 Some((_, pred)) if pred(arg.value()) => filtered.push(arg),
950 _ => debug!("Rejected bootarg {}", arg.as_ref()),
951 }
952 }
953
954 // flatten into a new C-string
955 let mut new_bootargs = Vec::new();
956 for (i, arg) in filtered.iter().enumerate() {
957 if i != 0 {
958 new_bootargs.push(b' '); // separator
959 }
960 new_bootargs.extend_from_slice(arg.as_ref().as_bytes());
961 }
962 new_bootargs.push(b'\0');
963
964 let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?;
965 node.setprop(cstr!("bootargs"), new_bootargs.as_slice())
966}