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