Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 1 | // 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 Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 17 | use crate::bootargs::BootArgsIterator; |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 18 | use crate::cstr; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 19 | use crate::helpers::flatten; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 20 | use crate::helpers::GUEST_PAGE_SIZE; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 21 | use crate::helpers::SIZE_4KB; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 22 | use crate::memory::BASE_ADDR; |
| 23 | use crate::memory::MAX_ADDR; |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 24 | use crate::Box; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 25 | use crate::RebootReason; |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 26 | use alloc::ffi::CString; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 27 | use alloc::vec::Vec; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 28 | use core::cmp::max; |
| 29 | use core::cmp::min; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 30 | use core::ffi::CStr; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 31 | use core::mem::size_of; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 32 | use core::ops::Range; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 33 | use fdtpci::PciMemoryFlags; |
| 34 | use fdtpci::PciRangeType; |
| 35 | use libfdt::AddressRange; |
| 36 | use libfdt::CellIterator; |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 37 | use libfdt::Fdt; |
| 38 | use libfdt::FdtError; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 39 | use libfdt::FdtNode; |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 40 | use log::debug; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 41 | use log::error; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 42 | use log::info; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 43 | use tinyvec::ArrayVec; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 44 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 45 | /// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is |
| 46 | /// not an error. |
| 47 | fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> { |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 48 | let addr = cstr!("kernel-address"); |
| 49 | let size = cstr!("kernel-size"); |
Pierre-Clément Tosi | c3811b8 | 2022-11-29 11:24:16 +0000 | [diff] [blame] | 50 | |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 51 | if let Some(config) = fdt.node(cstr!("/config"))? { |
Pierre-Clément Tosi | c3811b8 | 2022-11-29 11:24:16 +0000 | [diff] [blame] | 52 | if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) { |
| 53 | let addr = addr as usize; |
| 54 | let size = size as usize; |
| 55 | |
| 56 | return Ok(Some(addr..(addr + size))); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | Ok(None) |
| 61 | } |
| 62 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 63 | /// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an |
| 64 | /// error as there can be initrd-less VM. |
| 65 | fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> { |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 66 | let start = cstr!("linux,initrd-start"); |
| 67 | let end = cstr!("linux,initrd-end"); |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 68 | |
| 69 | if let Some(chosen) = fdt.chosen()? { |
| 70 | if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) { |
| 71 | return Ok(Some((start as usize)..(end as usize))); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | Ok(None) |
| 76 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 77 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 78 | fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> { |
| 79 | let start = u32::try_from(initrd_range.start).unwrap(); |
| 80 | let end = u32::try_from(initrd_range.end).unwrap(); |
| 81 | |
| 82 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
| 83 | node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?; |
| 84 | node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?; |
| 85 | Ok(()) |
| 86 | } |
| 87 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 88 | fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> { |
| 89 | if let Some(chosen) = fdt.chosen()? { |
| 90 | if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? { |
| 91 | // We need to copy the string to heap because the original fdt will be invalidated |
| 92 | // by the templated DT |
| 93 | let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?; |
| 94 | return Ok(Some(copy)); |
| 95 | } |
| 96 | } |
| 97 | Ok(None) |
| 98 | } |
| 99 | |
| 100 | fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> { |
| 101 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 102 | // This function is called before the verification is done. So, we just copy the bootargs to |
| 103 | // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function |
| 104 | // if the VM is not debuggable. |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 105 | node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul()) |
| 106 | } |
| 107 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 108 | /// Read the first range in /memory node in DT |
| 109 | fn read_memory_range_from(fdt: &Fdt) -> libfdt::Result<Range<usize>> { |
| 110 | fdt.memory()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound) |
| 111 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 112 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 113 | /// Check if memory range is ok |
| 114 | fn validate_memory_range(range: &Range<usize>) -> Result<(), RebootReason> { |
| 115 | let base = range.start; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 116 | if base != BASE_ADDR { |
| 117 | error!("Memory base address {:#x} is not {:#x}", base, BASE_ADDR); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 118 | return Err(RebootReason::InvalidFdt); |
| 119 | } |
| 120 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 121 | let size = range.len(); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 122 | if size % GUEST_PAGE_SIZE != 0 { |
| 123 | error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE); |
| 124 | return Err(RebootReason::InvalidFdt); |
| 125 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 126 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 127 | if size == 0 { |
| 128 | error!("Memory size is 0"); |
| 129 | return Err(RebootReason::InvalidFdt); |
| 130 | } |
| 131 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 132 | } |
| 133 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 134 | fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> { |
| 135 | let size = memory_range.len() as u64; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 136 | fdt.node_mut(cstr!("/memory"))? |
| 137 | .ok_or(FdtError::NotFound)? |
| 138 | .setprop_inplace(cstr!("reg"), flatten(&[BASE_ADDR.to_be_bytes(), size.to_be_bytes()])) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 139 | } |
| 140 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 141 | /// Read the number of CPUs from DT |
| 142 | fn read_num_cpus_from(fdt: &Fdt) -> libfdt::Result<usize> { |
| 143 | Ok(fdt.compatible_nodes(cstr!("arm,arm-v8"))?.count()) |
| 144 | } |
| 145 | |
| 146 | /// Validate number of CPUs |
| 147 | fn validate_num_cpus(num_cpus: usize) -> Result<(), RebootReason> { |
| 148 | if num_cpus == 0 { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 149 | error!("Number of CPU can't be 0"); |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 150 | return Err(RebootReason::InvalidFdt); |
| 151 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 152 | if DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).is_none() { |
| 153 | error!("Too many CPUs for gic: {}", num_cpus); |
| 154 | return Err(RebootReason::InvalidFdt); |
| 155 | } |
| 156 | Ok(()) |
| 157 | } |
| 158 | |
| 159 | /// Patch DT by keeping `num_cpus` number of arm,arm-v8 compatible nodes, and pruning the rest. |
| 160 | fn patch_num_cpus(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> { |
| 161 | let cpu = cstr!("arm,arm-v8"); |
| 162 | let mut next = fdt.root_mut()?.next_compatible(cpu)?; |
| 163 | for _ in 0..num_cpus { |
| 164 | next = if let Some(current) = next { |
| 165 | current.next_compatible(cpu)? |
| 166 | } else { |
| 167 | return Err(FdtError::NoSpace); |
| 168 | }; |
| 169 | } |
| 170 | while let Some(current) = next { |
| 171 | next = current.delete_and_next_compatible(cpu)?; |
| 172 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 173 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 174 | } |
| 175 | |
| 176 | #[derive(Debug)] |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 177 | struct PciInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 178 | ranges: [PciAddrRange; 2], |
| 179 | irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>, |
| 180 | irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 181 | } |
| 182 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 183 | impl PciInfo { |
| 184 | const IRQ_MASK_CELLS: usize = 4; |
| 185 | const IRQ_MAP_CELLS: usize = 10; |
| 186 | const MAX_IRQS: usize = 8; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 187 | } |
| 188 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 189 | type PciAddrRange = AddressRange<(u32, u64), u64, u64>; |
| 190 | type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS]; |
| 191 | type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS]; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 192 | |
| 193 | /// Iterator that takes N cells as a chunk |
| 194 | struct CellChunkIterator<'a, const N: usize> { |
| 195 | cells: CellIterator<'a>, |
| 196 | } |
| 197 | |
| 198 | impl<'a, const N: usize> CellChunkIterator<'a, N> { |
| 199 | fn new(cells: CellIterator<'a>) -> Self { |
| 200 | Self { cells } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> { |
| 205 | type Item = [u32; N]; |
| 206 | fn next(&mut self) -> Option<Self::Item> { |
| 207 | let mut ret: Self::Item = [0; N]; |
| 208 | for i in ret.iter_mut() { |
| 209 | *i = self.cells.next()?; |
| 210 | } |
| 211 | Some(ret) |
| 212 | } |
| 213 | } |
| 214 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 215 | /// Read pci host controller ranges, irq maps, and irq map masks from DT |
| 216 | fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> { |
| 217 | let node = |
| 218 | fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?; |
| 219 | |
| 220 | let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?; |
| 221 | let range0 = ranges.next().ok_or(FdtError::NotFound)?; |
| 222 | let range1 = ranges.next().ok_or(FdtError::NotFound)?; |
| 223 | |
| 224 | let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?; |
| 225 | let irq_masks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks); |
| 226 | let irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]> = |
| 227 | irq_masks.take(PciInfo::MAX_IRQS).collect(); |
| 228 | |
| 229 | let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?; |
| 230 | let irq_maps = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps); |
| 231 | let irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]> = |
| 232 | irq_maps.take(PciInfo::MAX_IRQS).collect(); |
| 233 | |
| 234 | Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps }) |
| 235 | } |
| 236 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 237 | fn validate_pci_info(pci_info: &PciInfo, memory_range: &Range<usize>) -> Result<(), RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 238 | for range in pci_info.ranges.iter() { |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 239 | validate_pci_addr_range(range, memory_range)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 240 | } |
| 241 | for irq_mask in pci_info.irq_masks.iter() { |
| 242 | validate_pci_irq_mask(irq_mask)?; |
| 243 | } |
| 244 | for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() { |
| 245 | validate_pci_irq_map(irq_map, idx)?; |
| 246 | } |
| 247 | Ok(()) |
| 248 | } |
| 249 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 250 | fn validate_pci_addr_range( |
| 251 | range: &PciAddrRange, |
| 252 | memory_range: &Range<usize>, |
| 253 | ) -> Result<(), RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 254 | let mem_flags = PciMemoryFlags(range.addr.0); |
| 255 | let range_type = mem_flags.range_type(); |
| 256 | let prefetchable = mem_flags.prefetchable(); |
| 257 | let bus_addr = range.addr.1; |
| 258 | let cpu_addr = range.parent_addr; |
| 259 | let size = range.size; |
| 260 | |
| 261 | if range_type != PciRangeType::Memory64 { |
| 262 | error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr); |
| 263 | return Err(RebootReason::InvalidFdt); |
| 264 | } |
| 265 | if prefetchable { |
| 266 | error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr); |
| 267 | return Err(RebootReason::InvalidFdt); |
| 268 | } |
| 269 | // Enforce ID bus-to-cpu mappings, as used by crosvm. |
| 270 | if bus_addr != cpu_addr { |
| 271 | error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr); |
| 272 | return Err(RebootReason::InvalidFdt); |
| 273 | } |
| 274 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 275 | let Some(bus_end) = bus_addr.checked_add(size) else { |
| 276 | error!("PCI address range size {:#x} overflows", size); |
| 277 | return Err(RebootReason::InvalidFdt); |
| 278 | }; |
| 279 | if bus_end > MAX_ADDR.try_into().unwrap() { |
| 280 | error!("PCI address end {:#x} is outside of translatable range", bus_end); |
| 281 | return Err(RebootReason::InvalidFdt); |
| 282 | } |
| 283 | |
| 284 | let memory_start = memory_range.start.try_into().unwrap(); |
| 285 | let memory_end = memory_range.end.try_into().unwrap(); |
| 286 | |
| 287 | if max(bus_addr, memory_start) < min(bus_end, memory_end) { |
| 288 | error!( |
| 289 | "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}", |
| 290 | bus_addr, bus_end, memory_start, memory_end |
| 291 | ); |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 292 | return Err(RebootReason::InvalidFdt); |
| 293 | } |
| 294 | |
| 295 | Ok(()) |
| 296 | } |
| 297 | |
| 298 | fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 299 | const IRQ_MASK_ADDR_HI: u32 = 0xf800; |
| 300 | const IRQ_MASK_ADDR_ME: u32 = 0x0; |
| 301 | const IRQ_MASK_ADDR_LO: u32 = 0x0; |
| 302 | const IRQ_MASK_ANY_IRQ: u32 = 0x7; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 303 | const EXPECTED: PciIrqMask = |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 304 | [IRQ_MASK_ADDR_HI, IRQ_MASK_ADDR_ME, IRQ_MASK_ADDR_LO, IRQ_MASK_ANY_IRQ]; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 305 | if *irq_mask != EXPECTED { |
| 306 | error!("Invalid PCI irq mask {:#?}", irq_mask); |
| 307 | return Err(RebootReason::InvalidFdt); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 308 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 309 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 310 | } |
| 311 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 312 | fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 313 | const PCI_DEVICE_IDX: usize = 11; |
| 314 | const PCI_IRQ_ADDR_ME: u32 = 0; |
| 315 | const PCI_IRQ_ADDR_LO: u32 = 0; |
| 316 | const PCI_IRQ_INTC: u32 = 1; |
| 317 | const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs |
| 318 | const GIC_SPI: u32 = 0; |
| 319 | const IRQ_TYPE_LEVEL_HIGH: u32 = 4; |
| 320 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 321 | let pci_addr = (irq_map[0], irq_map[1], irq_map[2]); |
| 322 | let pci_irq_number = irq_map[3]; |
| 323 | let _controller_phandle = irq_map[4]; // skipped. |
| 324 | let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC |
| 325 | // interrupt-cells is <3> for GIC |
| 326 | let gic_peripheral_interrupt_type = irq_map[7]; |
| 327 | let gic_irq_number = irq_map[8]; |
| 328 | let gic_irq_type = irq_map[9]; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 329 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 330 | let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32; |
| 331 | let expected_pci_addr = (phys_hi, PCI_IRQ_ADDR_ME, PCI_IRQ_ADDR_LO); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 332 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 333 | if pci_addr != expected_pci_addr { |
| 334 | error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \ |
| 335 | {:#x} {:#x} {:#x}", |
| 336 | pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2); |
| 337 | return Err(RebootReason::InvalidFdt); |
| 338 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 339 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 340 | if pci_irq_number != PCI_IRQ_INTC { |
| 341 | error!( |
| 342 | "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}", |
| 343 | pci_irq_number, PCI_IRQ_INTC |
| 344 | ); |
| 345 | return Err(RebootReason::InvalidFdt); |
| 346 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 347 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 348 | if gic_addr != (0, 0) { |
| 349 | error!( |
| 350 | "GIC address {:#x} {:#x} in interrupt-map is different from expected address \ |
| 351 | {:#x} {:#x}", |
| 352 | gic_addr.0, gic_addr.1, 0, 0 |
| 353 | ); |
| 354 | return Err(RebootReason::InvalidFdt); |
| 355 | } |
| 356 | |
| 357 | if gic_peripheral_interrupt_type != GIC_SPI { |
| 358 | error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \ |
| 359 | {:#x}", gic_peripheral_interrupt_type, GIC_SPI); |
| 360 | return Err(RebootReason::InvalidFdt); |
| 361 | } |
| 362 | |
| 363 | let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32); |
| 364 | if gic_irq_number != irq_nr { |
| 365 | error!( |
| 366 | "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}", |
| 367 | gic_irq_number, irq_nr |
| 368 | ); |
| 369 | return Err(RebootReason::InvalidFdt); |
| 370 | } |
| 371 | |
| 372 | if gic_irq_type != IRQ_TYPE_LEVEL_HIGH { |
| 373 | error!( |
| 374 | "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}", |
| 375 | gic_irq_type, IRQ_TYPE_LEVEL_HIGH |
| 376 | ); |
| 377 | return Err(RebootReason::InvalidFdt); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 378 | } |
| 379 | Ok(()) |
| 380 | } |
| 381 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 382 | fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> { |
| 383 | let mut node = fdt |
| 384 | .root_mut()? |
| 385 | .next_compatible(cstr!("pci-host-cam-generic"))? |
| 386 | .ok_or(FdtError::NotFound)?; |
| 387 | |
| 388 | let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>(); |
| 389 | node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?; |
| 390 | |
| 391 | let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>(); |
| 392 | node.trimprop(cstr!("interrupt-map"), irq_maps_size)?; |
| 393 | |
| 394 | node.setprop_inplace( |
| 395 | cstr!("ranges"), |
| 396 | flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]), |
| 397 | ) |
| 398 | } |
| 399 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 400 | #[derive(Default, Debug)] |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 401 | struct SerialInfo { |
| 402 | addrs: ArrayVec<[u64; Self::MAX_SERIALS]>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 403 | } |
| 404 | |
| 405 | impl SerialInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 406 | const MAX_SERIALS: usize = 4; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 407 | } |
| 408 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 409 | fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> { |
| 410 | let mut addrs: ArrayVec<[u64; SerialInfo::MAX_SERIALS]> = Default::default(); |
| 411 | for node in fdt.compatible_nodes(cstr!("ns16550a"))?.take(SerialInfo::MAX_SERIALS) { |
| 412 | let reg = node.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?; |
| 413 | addrs.push(reg.addr); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 414 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 415 | Ok(SerialInfo { addrs }) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 416 | } |
| 417 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 418 | /// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown |
| 419 | fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> { |
| 420 | let name = cstr!("ns16550a"); |
| 421 | let mut next = fdt.root_mut()?.next_compatible(name); |
| 422 | while let Some(current) = next? { |
| 423 | let reg = FdtNode::from_mut(¤t) |
| 424 | .reg()? |
| 425 | .ok_or(FdtError::NotFound)? |
| 426 | .next() |
| 427 | .ok_or(FdtError::NotFound)?; |
| 428 | next = if !serial_info.addrs.contains(®.addr) { |
| 429 | current.delete_and_next_compatible(name) |
| 430 | } else { |
| 431 | current.next_compatible(name) |
| 432 | } |
| 433 | } |
| 434 | Ok(()) |
| 435 | } |
| 436 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 437 | #[derive(Debug)] |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 438 | struct SwiotlbInfo { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 439 | size: u64, |
| 440 | align: u64, |
| 441 | } |
| 442 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 443 | fn read_swiotlb_info_from(fdt: &Fdt) -> libfdt::Result<SwiotlbInfo> { |
| 444 | let node = |
| 445 | fdt.compatible_nodes(cstr!("restricted-dma-pool"))?.next().ok_or(FdtError::NotFound)?; |
| 446 | let size = node.getprop_u64(cstr!("size"))?.ok_or(FdtError::NotFound)?; |
| 447 | let align = node.getprop_u64(cstr!("alignment"))?.ok_or(FdtError::NotFound)?; |
| 448 | Ok(SwiotlbInfo { size, align }) |
| 449 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 450 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 451 | fn validate_swiotlb_info(swiotlb_info: &SwiotlbInfo) -> Result<(), RebootReason> { |
| 452 | let size = swiotlb_info.size; |
| 453 | let align = swiotlb_info.align; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 454 | |
| 455 | if size == 0 || (size % GUEST_PAGE_SIZE as u64) != 0 { |
| 456 | error!("Invalid swiotlb size {:#x}", size); |
| 457 | return Err(RebootReason::InvalidFdt); |
| 458 | } |
| 459 | |
| 460 | if (align % GUEST_PAGE_SIZE as u64) != 0 { |
| 461 | error!("Invalid swiotlb alignment {:#x}", align); |
| 462 | return Err(RebootReason::InvalidFdt); |
| 463 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 464 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 465 | } |
| 466 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 467 | fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> { |
| 468 | let mut node = |
| 469 | fdt.root_mut()?.next_compatible(cstr!("restricted-dma-pool"))?.ok_or(FdtError::NotFound)?; |
| 470 | node.setprop_inplace(cstr!("size"), &swiotlb_info.size.to_be_bytes())?; |
| 471 | node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.to_be_bytes())?; |
| 472 | Ok(()) |
| 473 | } |
| 474 | |
| 475 | fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> { |
| 476 | let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?; |
| 477 | let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?; |
| 478 | let range0 = ranges.next().ok_or(FdtError::NotFound)?; |
| 479 | let mut range1 = ranges.next().ok_or(FdtError::NotFound)?; |
| 480 | |
| 481 | let addr = range0.addr; |
| 482 | // SAFETY - doesn't overflow. checked in validate_num_cpus |
| 483 | let size: u64 = |
| 484 | DeviceTreeInfo::GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus.try_into().unwrap()).unwrap(); |
| 485 | |
| 486 | // range1 is just below range0 |
| 487 | range1.addr = addr - size; |
| 488 | range1.size = Some(size); |
| 489 | |
| 490 | let range0 = range0.to_cells(); |
| 491 | let range1 = range1.to_cells(); |
| 492 | let value = [ |
| 493 | range0.0, // addr |
| 494 | range0.1.unwrap(), //size |
| 495 | range1.0, // addr |
| 496 | range1.1.unwrap(), //size |
| 497 | ]; |
| 498 | |
| 499 | let mut node = |
| 500 | fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?; |
| 501 | node.setprop_inplace(cstr!("reg"), flatten(&value)) |
| 502 | } |
| 503 | |
| 504 | fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> { |
| 505 | const NUM_INTERRUPTS: usize = 4; |
| 506 | const CELLS_PER_INTERRUPT: usize = 3; |
| 507 | let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?; |
| 508 | let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?; |
| 509 | let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> = |
| 510 | interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect(); |
| 511 | |
| 512 | let num_cpus: u32 = num_cpus.try_into().unwrap(); |
| 513 | let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8; |
| 514 | for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) { |
| 515 | *v |= cpu_mask; |
| 516 | } |
| 517 | for v in value.iter_mut() { |
| 518 | *v = v.to_be(); |
| 519 | } |
| 520 | |
| 521 | // SAFETY - array size is the same |
| 522 | let value = unsafe { |
| 523 | core::mem::transmute::< |
| 524 | [u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT], |
| 525 | [u8; NUM_INTERRUPTS * CELLS_PER_INTERRUPT * size_of::<u32>()], |
| 526 | >(value.into_inner()) |
| 527 | }; |
| 528 | |
| 529 | let mut node = |
| 530 | fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?; |
| 531 | node.setprop_inplace(cstr!("interrupts"), value.as_slice()) |
| 532 | } |
| 533 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 534 | #[derive(Debug)] |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 535 | pub struct DeviceTreeInfo { |
| 536 | pub kernel_range: Option<Range<usize>>, |
| 537 | pub initrd_range: Option<Range<usize>>, |
| 538 | pub memory_range: Range<usize>, |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 539 | bootargs: Option<CString>, |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 540 | num_cpus: usize, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 541 | pci_info: PciInfo, |
| 542 | serial_info: SerialInfo, |
| 543 | swiotlb_info: SwiotlbInfo, |
| 544 | } |
| 545 | |
| 546 | impl DeviceTreeInfo { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 547 | const GIC_REDIST_SIZE_PER_CPU: u64 = (32 * SIZE_4KB) as u64; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 548 | } |
| 549 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 550 | pub fn sanitize_device_tree(fdt: &mut Fdt) -> Result<DeviceTreeInfo, RebootReason> { |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 551 | let info = parse_device_tree(fdt)?; |
| 552 | debug!("Device tree info: {:?}", info); |
| 553 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 554 | fdt.copy_from_slice(pvmfw_fdt_template::RAW).map_err(|e| { |
| 555 | error!("Failed to instantiate FDT from the template DT: {e}"); |
| 556 | RebootReason::InvalidFdt |
| 557 | })?; |
| 558 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 559 | patch_device_tree(fdt, &info)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 560 | Ok(info) |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 561 | } |
| 562 | |
| 563 | fn parse_device_tree(fdt: &libfdt::Fdt) -> Result<DeviceTreeInfo, RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 564 | let kernel_range = read_kernel_range_from(fdt).map_err(|e| { |
| 565 | error!("Failed to read kernel range from DT: {e}"); |
| 566 | RebootReason::InvalidFdt |
| 567 | })?; |
| 568 | |
| 569 | let initrd_range = read_initrd_range_from(fdt).map_err(|e| { |
| 570 | error!("Failed to read initrd range from DT: {e}"); |
| 571 | RebootReason::InvalidFdt |
| 572 | })?; |
| 573 | |
| 574 | let memory_range = read_memory_range_from(fdt).map_err(|e| { |
| 575 | error!("Failed to read memory range from DT: {e}"); |
| 576 | RebootReason::InvalidFdt |
| 577 | })?; |
| 578 | validate_memory_range(&memory_range)?; |
| 579 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 580 | let bootargs = read_bootargs_from(fdt).map_err(|e| { |
| 581 | error!("Failed to read bootargs from DT: {e}"); |
| 582 | RebootReason::InvalidFdt |
| 583 | })?; |
| 584 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 585 | let num_cpus = read_num_cpus_from(fdt).map_err(|e| { |
| 586 | error!("Failed to read num cpus from DT: {e}"); |
| 587 | RebootReason::InvalidFdt |
| 588 | })?; |
| 589 | validate_num_cpus(num_cpus)?; |
| 590 | |
| 591 | let pci_info = read_pci_info_from(fdt).map_err(|e| { |
| 592 | error!("Failed to read pci info from DT: {e}"); |
| 593 | RebootReason::InvalidFdt |
| 594 | })?; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 595 | validate_pci_info(&pci_info, &memory_range)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 596 | |
| 597 | let serial_info = read_serial_info_from(fdt).map_err(|e| { |
| 598 | error!("Failed to read serial info from DT: {e}"); |
| 599 | RebootReason::InvalidFdt |
| 600 | })?; |
| 601 | |
| 602 | let swiotlb_info = read_swiotlb_info_from(fdt).map_err(|e| { |
| 603 | error!("Failed to read swiotlb info from DT: {e}"); |
| 604 | RebootReason::InvalidFdt |
| 605 | })?; |
| 606 | validate_swiotlb_info(&swiotlb_info)?; |
| 607 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 608 | Ok(DeviceTreeInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 609 | kernel_range, |
| 610 | initrd_range, |
| 611 | memory_range, |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 612 | bootargs, |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 613 | num_cpus, |
| 614 | pci_info, |
| 615 | serial_info, |
| 616 | swiotlb_info, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 617 | }) |
| 618 | } |
| 619 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 620 | fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> { |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 621 | fdt.unpack().map_err(|e| { |
| 622 | error!("Failed to unpack DT for patching: {e}"); |
| 623 | RebootReason::InvalidFdt |
| 624 | })?; |
| 625 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 626 | if let Some(initrd_range) = &info.initrd_range { |
| 627 | patch_initrd_range(fdt, initrd_range).map_err(|e| { |
| 628 | error!("Failed to patch initrd range to DT: {e}"); |
| 629 | RebootReason::InvalidFdt |
| 630 | })?; |
| 631 | } |
| 632 | patch_memory_range(fdt, &info.memory_range).map_err(|e| { |
| 633 | error!("Failed to patch memory range to DT: {e}"); |
| 634 | RebootReason::InvalidFdt |
| 635 | })?; |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 636 | if let Some(bootargs) = &info.bootargs { |
| 637 | patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| { |
| 638 | error!("Failed to patch bootargs to DT: {e}"); |
| 639 | RebootReason::InvalidFdt |
| 640 | })?; |
| 641 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 642 | patch_num_cpus(fdt, info.num_cpus).map_err(|e| { |
| 643 | error!("Failed to patch cpus to DT: {e}"); |
| 644 | RebootReason::InvalidFdt |
| 645 | })?; |
| 646 | patch_pci_info(fdt, &info.pci_info).map_err(|e| { |
| 647 | error!("Failed to patch pci info to DT: {e}"); |
| 648 | RebootReason::InvalidFdt |
| 649 | })?; |
| 650 | patch_serial_info(fdt, &info.serial_info).map_err(|e| { |
| 651 | error!("Failed to patch serial info to DT: {e}"); |
| 652 | RebootReason::InvalidFdt |
| 653 | })?; |
| 654 | patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| { |
| 655 | error!("Failed to patch swiotlb info to DT: {e}"); |
| 656 | RebootReason::InvalidFdt |
| 657 | })?; |
| 658 | patch_gic(fdt, info.num_cpus).map_err(|e| { |
| 659 | error!("Failed to patch gic info to DT: {e}"); |
| 660 | RebootReason::InvalidFdt |
| 661 | })?; |
| 662 | patch_timer(fdt, info.num_cpus).map_err(|e| { |
| 663 | error!("Failed to patch timer info to DT: {e}"); |
| 664 | RebootReason::InvalidFdt |
| 665 | })?; |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 666 | |
| 667 | fdt.pack().map_err(|e| { |
| 668 | error!("Failed to pack DT after patching: {e}"); |
| 669 | RebootReason::InvalidFdt |
| 670 | })?; |
| 671 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 672 | Ok(()) |
| 673 | } |
| 674 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 675 | /// Modifies the input DT according to the fields of the configuration. |
| 676 | pub fn modify_for_next_stage( |
| 677 | fdt: &mut Fdt, |
| 678 | bcc: &[u8], |
| 679 | new_instance: bool, |
| 680 | strict_boot: bool, |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 681 | debug_policy: Option<&mut [u8]>, |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 682 | debuggable: bool, |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 683 | ) -> libfdt::Result<()> { |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 684 | fdt.unpack()?; |
| 685 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 686 | patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?; |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 687 | |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 688 | set_or_clear_chosen_flag(fdt, cstr!("avf,strict-boot"), strict_boot)?; |
| 689 | set_or_clear_chosen_flag(fdt, cstr!("avf,new-instance"), new_instance)?; |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 690 | |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 691 | if let Some(debug_policy) = debug_policy { |
| 692 | apply_debug_policy(fdt, debug_policy)?; |
| 693 | info!("Debug policy applied."); |
| 694 | } else { |
| 695 | info!("No debug policy found."); |
| 696 | } |
| 697 | |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 698 | if debuggable { |
| 699 | if let Some(bootargs) = read_bootargs_from(fdt)? { |
| 700 | filter_out_dangerous_bootargs(fdt, &bootargs)?; |
| 701 | } |
| 702 | } |
| 703 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 704 | fdt.pack()?; |
| 705 | |
| 706 | Ok(()) |
| 707 | } |
| 708 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 709 | /// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range |
| 710 | fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> { |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 711 | // We reject DTs with missing reserved-memory node as validation should have checked that the |
| 712 | // "swiotlb" subnode (compatible = "restricted-dma-pool") was present. |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 713 | let node = fdt.node_mut(cstr!("/reserved-memory"))?.ok_or(libfdt::FdtError::NotFound)?; |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 714 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 715 | let mut node = node.next_compatible(cstr!("google,open-dice"))?.ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 716 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 717 | let addr: u64 = addr.try_into().unwrap(); |
| 718 | let size: u64 = size.try_into().unwrap(); |
| 719 | node.setprop_inplace(cstr!("reg"), flatten(&[addr.to_be_bytes(), size.to_be_bytes()])) |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 720 | } |
| 721 | |
| 722 | fn set_or_clear_chosen_flag(fdt: &mut Fdt, flag: &CStr, value: bool) -> libfdt::Result<()> { |
| 723 | // TODO(b/249054080): Refactor to not panic if the DT doesn't contain a /chosen node. |
| 724 | let mut chosen = fdt.chosen_mut()?.unwrap(); |
| 725 | if value { |
| 726 | chosen.setprop_empty(flag)?; |
| 727 | } else { |
| 728 | match chosen.delprop(flag) { |
| 729 | Ok(()) | Err(FdtError::NotFound) => (), |
| 730 | Err(e) => return Err(e), |
| 731 | } |
| 732 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 733 | |
| 734 | Ok(()) |
| 735 | } |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 736 | |
| 737 | fn apply_debug_policy(fdt: &mut Fdt, debug_policy: &mut [u8]) -> libfdt::Result<()> { |
| 738 | let backup_fdt = Vec::from(fdt.as_slice()); |
| 739 | |
| 740 | let overlay = match Fdt::from_mut_slice(debug_policy) { |
| 741 | Ok(overlay) => overlay, |
| 742 | Err(e) => { |
| 743 | info!("Corrupted debug policy found: {e}. Not applying."); |
| 744 | return Ok(()); |
| 745 | } |
| 746 | }; |
| 747 | let backup_overlay = Vec::from(overlay.as_slice()); |
| 748 | |
| 749 | // SAFETY - on failure, the corrupted fdts are discarded and are restored using the backups. |
| 750 | if let Err(e) = unsafe { fdt.apply_overlay(overlay) } { |
| 751 | error!("Failed to apply debug policy: {e}. Recovering..."); |
| 752 | fdt.copy_from_slice(backup_fdt.as_slice())?; |
| 753 | overlay.copy_from_slice(backup_overlay.as_slice())?; |
| 754 | // A successful restoration is considered success because an invalid debug policy |
| 755 | // shouldn't DOS the pvmfw |
| 756 | } |
| 757 | Ok(()) |
| 758 | } |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 759 | |
| 760 | fn read_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> { |
| 761 | if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? { |
| 762 | if let Some(value) = node.getprop_u32(debug_feature_name)? { |
| 763 | return Ok(value == 1); |
| 764 | } |
| 765 | } |
| 766 | Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature |
| 767 | } |
| 768 | |
| 769 | fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> { |
| 770 | let has_crashkernel = read_common_debug_policy(fdt, cstr!("ramdump"))?; |
| 771 | let has_console = read_common_debug_policy(fdt, cstr!("log"))?; |
| 772 | |
| 773 | let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[ |
| 774 | ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })), |
| 775 | ("crashkernel", Box::new(|_| has_crashkernel)), |
| 776 | ("console", Box::new(|_| has_console)), |
| 777 | ]; |
| 778 | |
| 779 | // parse and filter out unwanted |
| 780 | let mut filtered = Vec::new(); |
| 781 | for arg in BootArgsIterator::new(bootargs).map_err(|e| { |
| 782 | info!("Invalid bootarg: {e}"); |
| 783 | FdtError::BadValue |
| 784 | })? { |
| 785 | match accepted.iter().find(|&t| t.0 == arg.name()) { |
| 786 | Some((_, pred)) if pred(arg.value()) => filtered.push(arg), |
| 787 | _ => debug!("Rejected bootarg {}", arg.as_ref()), |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | // flatten into a new C-string |
| 792 | let mut new_bootargs = Vec::new(); |
| 793 | for (i, arg) in filtered.iter().enumerate() { |
| 794 | if i != 0 { |
| 795 | new_bootargs.push(b' '); // separator |
| 796 | } |
| 797 | new_bootargs.extend_from_slice(arg.as_ref().as_bytes()); |
| 798 | } |
| 799 | new_bootargs.push(b'\0'); |
| 800 | |
| 801 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
| 802 | node.setprop(cstr!("bootargs"), new_bootargs.as_slice()) |
| 803 | } |