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