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; |
Jaewan Kim | 52477ae | 2023-11-21 21:20:52 +0900 | [diff] [blame] | 18 | use crate::device_assignment::{DeviceAssignmentInfo, VmDtbo}; |
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; |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 22 | use alloc::collections::BTreeMap; |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 23 | use alloc::ffi::CString; |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 24 | use alloc::format; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 25 | use alloc::vec::Vec; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 26 | use core::cmp::max; |
| 27 | use core::cmp::min; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 28 | use core::ffi::CStr; |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 29 | use core::fmt; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 30 | use core::mem::size_of; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 31 | use core::ops::Range; |
Pierre-Clément Tosi | 1bf532b | 2023-11-13 11:06:20 +0000 | [diff] [blame] | 32 | use cstr::cstr; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 33 | use fdtpci::PciMemoryFlags; |
| 34 | use fdtpci::PciRangeType; |
| 35 | use libfdt::AddressRange; |
| 36 | use libfdt::CellIterator; |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 37 | use libfdt::Fdt; |
| 38 | use libfdt::FdtError; |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 39 | use libfdt::FdtNode; |
Alice Wang | 56ec45b | 2023-06-15 08:30:32 +0000 | [diff] [blame] | 40 | use libfdt::FdtNodeMut; |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 41 | use libfdt::Phandle; |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 42 | use log::debug; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 43 | use log::error; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 44 | use log::info; |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 45 | use log::warn; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 46 | use static_assertions::const_assert; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 47 | use tinyvec::ArrayVec; |
Alice Wang | a397106 | 2023-06-13 11:48:53 +0000 | [diff] [blame] | 48 | use vmbase::fdt::SwiotlbInfo; |
Alice Wang | 63f4c9e | 2023-06-12 09:36:43 +0000 | [diff] [blame] | 49 | use vmbase::layout::{crosvm::MEM_START, MAX_VIRT_ADDR}; |
Alice Wang | eacb738 | 2023-06-05 12:53:54 +0000 | [diff] [blame] | 50 | use vmbase::memory::SIZE_4KB; |
| 51 | use vmbase::util::flatten; |
Alice Wang | 4be4dd0 | 2023-06-07 07:50:40 +0000 | [diff] [blame] | 52 | use vmbase::util::RangeExt as _; |
Pierre-Clément Tosi | 0edc4d6 | 2024-02-05 14:13:53 +0000 | [diff] [blame] | 53 | use zerocopy::AsBytes as _; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 54 | |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 55 | /// An enumeration of errors that can occur during the FDT validation. |
| 56 | #[derive(Clone, Debug)] |
| 57 | pub enum FdtValidationError { |
| 58 | /// Invalid CPU count. |
| 59 | InvalidCpuCount(usize), |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 60 | /// Invalid VCpufreq Range. |
| 61 | InvalidVcpufreq(u64, u64), |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 62 | } |
| 63 | |
| 64 | impl fmt::Display for FdtValidationError { |
| 65 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 66 | match self { |
| 67 | Self::InvalidCpuCount(num_cpus) => write!(f, "Invalid CPU count: {num_cpus}"), |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 68 | Self::InvalidVcpufreq(addr, size) => { |
| 69 | write!(f, "Invalid vcpufreq region: ({addr:#x}, {size:#x})") |
| 70 | } |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 75 | /// Extract from /config the address range containing the pre-loaded kernel. Absence of /config is |
| 76 | /// not an error. |
| 77 | fn read_kernel_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> { |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 78 | let addr = cstr!("kernel-address"); |
| 79 | let size = cstr!("kernel-size"); |
Pierre-Clément Tosi | c3811b8 | 2022-11-29 11:24:16 +0000 | [diff] [blame] | 80 | |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 81 | if let Some(config) = fdt.node(cstr!("/config"))? { |
Pierre-Clément Tosi | c3811b8 | 2022-11-29 11:24:16 +0000 | [diff] [blame] | 82 | if let (Some(addr), Some(size)) = (config.getprop_u32(addr)?, config.getprop_u32(size)?) { |
| 83 | let addr = addr as usize; |
| 84 | let size = size as usize; |
| 85 | |
| 86 | return Ok(Some(addr..(addr + size))); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | Ok(None) |
| 91 | } |
| 92 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 93 | /// Extract from /chosen the address range containing the pre-loaded ramdisk. Absence is not an |
| 94 | /// error as there can be initrd-less VM. |
| 95 | fn read_initrd_range_from(fdt: &Fdt) -> libfdt::Result<Option<Range<usize>>> { |
Jiyong Park | b87f330 | 2023-03-21 10:03:11 +0900 | [diff] [blame] | 96 | let start = cstr!("linux,initrd-start"); |
| 97 | let end = cstr!("linux,initrd-end"); |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 98 | |
| 99 | if let Some(chosen) = fdt.chosen()? { |
| 100 | if let (Some(start), Some(end)) = (chosen.getprop_u32(start)?, chosen.getprop_u32(end)?) { |
| 101 | return Ok(Some((start as usize)..(end as usize))); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | Ok(None) |
| 106 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 107 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 108 | fn patch_initrd_range(fdt: &mut Fdt, initrd_range: &Range<usize>) -> libfdt::Result<()> { |
| 109 | let start = u32::try_from(initrd_range.start).unwrap(); |
| 110 | let end = u32::try_from(initrd_range.end).unwrap(); |
| 111 | |
| 112 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
| 113 | node.setprop(cstr!("linux,initrd-start"), &start.to_be_bytes())?; |
| 114 | node.setprop(cstr!("linux,initrd-end"), &end.to_be_bytes())?; |
| 115 | Ok(()) |
| 116 | } |
| 117 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 118 | fn read_bootargs_from(fdt: &Fdt) -> libfdt::Result<Option<CString>> { |
| 119 | if let Some(chosen) = fdt.chosen()? { |
| 120 | if let Some(bootargs) = chosen.getprop_str(cstr!("bootargs"))? { |
| 121 | // We need to copy the string to heap because the original fdt will be invalidated |
| 122 | // by the templated DT |
| 123 | let copy = CString::new(bootargs.to_bytes()).map_err(|_| FdtError::BadValue)?; |
| 124 | return Ok(Some(copy)); |
| 125 | } |
| 126 | } |
| 127 | Ok(None) |
| 128 | } |
| 129 | |
| 130 | fn patch_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> { |
| 131 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 132 | // This function is called before the verification is done. So, we just copy the bootargs to |
| 133 | // the new FDT unmodified. This will be filtered again in the modify_for_next_stage function |
| 134 | // if the VM is not debuggable. |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 135 | node.setprop(cstr!("bootargs"), bootargs.to_bytes_with_nul()) |
| 136 | } |
| 137 | |
Alice Wang | 0d52747 | 2023-06-13 14:55:38 +0000 | [diff] [blame] | 138 | /// Reads and validates the memory range in the DT. |
| 139 | /// |
| 140 | /// Only one memory range is expected with the crosvm setup for now. |
| 141 | fn read_and_validate_memory_range(fdt: &Fdt) -> Result<Range<usize>, RebootReason> { |
| 142 | let mut memory = fdt.memory().map_err(|e| { |
| 143 | error!("Failed to read memory range from DT: {e}"); |
| 144 | RebootReason::InvalidFdt |
| 145 | })?; |
| 146 | let range = memory.next().ok_or_else(|| { |
| 147 | error!("The /memory node in the DT contains no range."); |
| 148 | RebootReason::InvalidFdt |
| 149 | })?; |
| 150 | if memory.next().is_some() { |
| 151 | warn!( |
| 152 | "The /memory node in the DT contains more than one memory range, \ |
| 153 | while only one is expected." |
| 154 | ); |
| 155 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 156 | let base = range.start; |
Alice Wang | e243d46 | 2023-06-06 15:18:12 +0000 | [diff] [blame] | 157 | if base != MEM_START { |
| 158 | error!("Memory base address {:#x} is not {:#x}", base, MEM_START); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 159 | return Err(RebootReason::InvalidFdt); |
| 160 | } |
| 161 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 162 | let size = range.len(); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 163 | if size % GUEST_PAGE_SIZE != 0 { |
| 164 | error!("Memory size {:#x} is not a multiple of page size {:#x}", size, GUEST_PAGE_SIZE); |
| 165 | return Err(RebootReason::InvalidFdt); |
| 166 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 167 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 168 | if size == 0 { |
| 169 | error!("Memory size is 0"); |
| 170 | return Err(RebootReason::InvalidFdt); |
| 171 | } |
Alice Wang | 0d52747 | 2023-06-13 14:55:38 +0000 | [diff] [blame] | 172 | Ok(range) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 173 | } |
| 174 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 175 | fn patch_memory_range(fdt: &mut Fdt, memory_range: &Range<usize>) -> libfdt::Result<()> { |
Pierre-Clément Tosi | 0edc4d6 | 2024-02-05 14:13:53 +0000 | [diff] [blame] | 176 | let addr = u64::try_from(MEM_START).unwrap(); |
| 177 | let size = u64::try_from(memory_range.len()).unwrap(); |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 178 | fdt.node_mut(cstr!("/memory"))? |
| 179 | .ok_or(FdtError::NotFound)? |
Pierre-Clément Tosi | 0edc4d6 | 2024-02-05 14:13:53 +0000 | [diff] [blame] | 180 | .setprop_inplace(cstr!("reg"), [addr.to_be(), size.to_be()].as_bytes()) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 181 | } |
| 182 | |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 183 | #[derive(Debug, Default)] |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 184 | struct CpuInfo { |
| 185 | opptable_info: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>, |
David Dai | 50168a3 | 2024-02-14 17:00:48 -0800 | [diff] [blame] | 186 | cpu_capacity: Option<u32>, |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 187 | } |
| 188 | |
| 189 | impl CpuInfo { |
David Dai | 622c05d | 2024-02-14 14:03:26 -0800 | [diff] [blame] | 190 | const MAX_OPPTABLES: usize = 20; |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 191 | } |
| 192 | |
| 193 | fn read_opp_info_from( |
| 194 | opp_node: FdtNode, |
| 195 | ) -> libfdt::Result<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>> { |
| 196 | let mut table = ArrayVec::new(); |
| 197 | for subnode in opp_node.subnodes()? { |
| 198 | let prop = subnode.getprop_u64(cstr!("opp-hz"))?.ok_or(FdtError::NotFound)?; |
| 199 | table.push(prop); |
| 200 | } |
| 201 | |
| 202 | Ok(table) |
| 203 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 204 | |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 205 | #[derive(Debug, Default)] |
| 206 | struct ClusterTopology { |
| 207 | // TODO: Support multi-level clusters & threads. |
| 208 | cores: [Option<usize>; ClusterTopology::MAX_CORES_PER_CLUSTER], |
| 209 | } |
| 210 | |
| 211 | impl ClusterTopology { |
| 212 | const MAX_CORES_PER_CLUSTER: usize = 6; |
| 213 | } |
| 214 | |
| 215 | #[derive(Debug, Default)] |
| 216 | struct CpuTopology { |
| 217 | // TODO: Support sockets. |
| 218 | clusters: [Option<ClusterTopology>; CpuTopology::MAX_CLUSTERS], |
| 219 | } |
| 220 | |
| 221 | impl CpuTopology { |
| 222 | const MAX_CLUSTERS: usize = 3; |
| 223 | } |
| 224 | |
| 225 | fn read_cpu_map_from(fdt: &Fdt) -> libfdt::Result<Option<BTreeMap<Phandle, (usize, usize)>>> { |
| 226 | let Some(cpu_map) = fdt.node(cstr!("/cpus/cpu-map"))? else { |
| 227 | return Ok(None); |
| 228 | }; |
| 229 | |
| 230 | let mut topology = BTreeMap::new(); |
| 231 | for n in 0..CpuTopology::MAX_CLUSTERS { |
| 232 | let name = CString::new(format!("cluster{n}")).unwrap(); |
| 233 | let Some(cluster) = cpu_map.subnode(&name)? else { |
| 234 | break; |
| 235 | }; |
| 236 | for m in 0..ClusterTopology::MAX_CORES_PER_CLUSTER { |
| 237 | let name = CString::new(format!("core{n}")).unwrap(); |
| 238 | let Some(core) = cluster.subnode(&name)? else { |
| 239 | break; |
| 240 | }; |
| 241 | let cpu = core.getprop_u32(cstr!("cpu"))?.ok_or(FdtError::NotFound)?; |
| 242 | let prev = topology.insert(cpu.try_into()?, (n, m)); |
| 243 | if prev.is_some() { |
| 244 | return Err(FdtError::BadValue); |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | Ok(Some(topology)) |
| 250 | } |
| 251 | |
| 252 | fn read_cpu_info_from( |
| 253 | fdt: &Fdt, |
| 254 | ) -> libfdt::Result<(ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, Option<CpuTopology>)> { |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 255 | let mut cpus = ArrayVec::new(); |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 256 | |
| 257 | let cpu_map = read_cpu_map_from(fdt)?; |
| 258 | let mut topology: CpuTopology = Default::default(); |
| 259 | |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 260 | let mut cpu_nodes = fdt.compatible_nodes(cstr!("arm,arm-v8"))?; |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 261 | for (idx, cpu) in cpu_nodes.by_ref().take(cpus.capacity()).enumerate() { |
David Dai | 50168a3 | 2024-02-14 17:00:48 -0800 | [diff] [blame] | 262 | let cpu_capacity = cpu.getprop_u32(cstr!("capacity-dmips-mhz"))?; |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 263 | let opp_phandle = cpu.getprop_u32(cstr!("operating-points-v2"))?; |
| 264 | let opptable_info = if let Some(phandle) = opp_phandle { |
| 265 | let phandle = phandle.try_into()?; |
| 266 | let node = fdt.node_with_phandle(phandle)?.ok_or(FdtError::NotFound)?; |
| 267 | Some(read_opp_info_from(node)?) |
| 268 | } else { |
| 269 | None |
| 270 | }; |
David Dai | 50168a3 | 2024-02-14 17:00:48 -0800 | [diff] [blame] | 271 | let info = CpuInfo { opptable_info, cpu_capacity }; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 272 | cpus.push(info); |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 273 | |
| 274 | if let Some(ref cpu_map) = cpu_map { |
| 275 | let phandle = cpu.get_phandle()?.ok_or(FdtError::NotFound)?; |
| 276 | let (cluster, core) = cpu_map.get(&phandle).ok_or(FdtError::BadValue)?; |
| 277 | let cluster = topology.clusters[*cluster].get_or_insert(Default::default()); |
| 278 | let mut core = cluster.cores[*core]; |
| 279 | if core.is_some() { |
| 280 | return Err(FdtError::BadValue); |
| 281 | } |
| 282 | let _ = core.insert(idx); |
| 283 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 284 | } |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 285 | |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 286 | if cpu_nodes.next().is_some() { |
| 287 | warn!("DT has more than {} CPU nodes: discarding extra nodes.", cpus.capacity()); |
| 288 | } |
| 289 | |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 290 | Ok((cpus, cpu_map.map(|_| topology))) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 291 | } |
| 292 | |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 293 | fn validate_cpu_info(cpus: &[CpuInfo]) -> Result<(), FdtValidationError> { |
| 294 | if cpus.is_empty() { |
| 295 | return Err(FdtValidationError::InvalidCpuCount(0)); |
| 296 | } |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 297 | Ok(()) |
| 298 | } |
| 299 | |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 300 | fn read_vcpufreq_info(fdt: &Fdt) -> libfdt::Result<Option<VcpufreqInfo>> { |
Pierre-Clément Tosi | c37c72e | 2024-02-14 12:18:12 +0000 | [diff] [blame] | 301 | let mut nodes = fdt.compatible_nodes(cstr!("virtual,android-v-only-cpufreq"))?; |
| 302 | let Some(node) = nodes.next() else { |
| 303 | return Ok(None); |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 304 | }; |
| 305 | |
Pierre-Clément Tosi | c37c72e | 2024-02-14 12:18:12 +0000 | [diff] [blame] | 306 | if nodes.next().is_some() { |
| 307 | warn!("DT has more than 1 cpufreq node: discarding extra nodes."); |
| 308 | } |
| 309 | |
| 310 | let mut regs = node.reg()?.ok_or(FdtError::NotFound)?; |
| 311 | let reg = regs.next().ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 312 | let size = reg.size.ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | c37c72e | 2024-02-14 12:18:12 +0000 | [diff] [blame] | 313 | |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 314 | Ok(Some(VcpufreqInfo { addr: reg.addr, size })) |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 315 | } |
| 316 | |
| 317 | fn validate_vcpufreq_info( |
| 318 | vcpufreq_info: &VcpufreqInfo, |
| 319 | cpus: &[CpuInfo], |
| 320 | ) -> Result<(), FdtValidationError> { |
| 321 | const VCPUFREQ_BASE_ADDR: u64 = 0x1040000; |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 322 | const VCPUFREQ_SIZE_PER_CPU: u64 = 0x8; |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 323 | |
| 324 | let base = vcpufreq_info.addr; |
| 325 | let size = vcpufreq_info.size; |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 326 | let expected_size = VCPUFREQ_SIZE_PER_CPU * cpus.len() as u64; |
| 327 | |
| 328 | if (base, size) != (VCPUFREQ_BASE_ADDR, expected_size) { |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 329 | return Err(FdtValidationError::InvalidVcpufreq(base, size)); |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 330 | } |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 331 | |
| 332 | Ok(()) |
| 333 | } |
| 334 | |
| 335 | fn patch_opptable( |
| 336 | node: FdtNodeMut, |
David Dai | 622c05d | 2024-02-14 14:03:26 -0800 | [diff] [blame] | 337 | opptable: Option<ArrayVec<[u64; CpuInfo::MAX_OPPTABLES]>>, |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 338 | ) -> libfdt::Result<()> { |
| 339 | let oppcompat = cstr!("operating-points-v2"); |
| 340 | let next = node.next_compatible(oppcompat)?.ok_or(FdtError::NoSpace)?; |
Pierre-Clément Tosi | c37c72e | 2024-02-14 12:18:12 +0000 | [diff] [blame] | 341 | |
| 342 | let Some(opptable) = opptable else { |
| 343 | return next.nop(); |
| 344 | }; |
| 345 | |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 346 | let mut next_subnode = next.first_subnode()?; |
| 347 | |
| 348 | for entry in opptable { |
| 349 | let mut subnode = next_subnode.ok_or(FdtError::NoSpace)?; |
| 350 | subnode.setprop_inplace(cstr!("opp-hz"), &entry.to_be_bytes())?; |
| 351 | next_subnode = subnode.next_subnode()?; |
| 352 | } |
| 353 | |
| 354 | while let Some(current) = next_subnode { |
| 355 | next_subnode = current.delete_and_next_subnode()?; |
| 356 | } |
Pierre-Clément Tosi | 8ba8980 | 2024-02-14 12:26:01 +0000 | [diff] [blame] | 357 | |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 358 | Ok(()) |
| 359 | } |
| 360 | |
| 361 | // TODO(ptosi): Rework FdtNodeMut and replace this function. |
| 362 | fn get_nth_compatible<'a>( |
| 363 | fdt: &'a mut Fdt, |
| 364 | n: usize, |
| 365 | compat: &CStr, |
| 366 | ) -> libfdt::Result<Option<FdtNodeMut<'a>>> { |
| 367 | let mut node = fdt.root_mut()?.next_compatible(compat)?; |
| 368 | for _ in 0..n { |
| 369 | node = node.ok_or(FdtError::NoSpace)?.next_compatible(compat)?; |
| 370 | } |
| 371 | Ok(node) |
| 372 | } |
| 373 | |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 374 | fn patch_cpus( |
| 375 | fdt: &mut Fdt, |
| 376 | cpus: &[CpuInfo], |
| 377 | topology: &Option<CpuTopology>, |
| 378 | ) -> libfdt::Result<()> { |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 379 | const COMPAT: &CStr = cstr!("arm,arm-v8"); |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 380 | let mut cpu_phandles = Vec::new(); |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 381 | for (idx, cpu) in cpus.iter().enumerate() { |
David Dai | 50168a3 | 2024-02-14 17:00:48 -0800 | [diff] [blame] | 382 | let mut cur = get_nth_compatible(fdt, idx, COMPAT)?.ok_or(FdtError::NoSpace)?; |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 383 | let phandle = cur.as_node().get_phandle()?.unwrap(); |
| 384 | cpu_phandles.push(phandle); |
David Dai | 50168a3 | 2024-02-14 17:00:48 -0800 | [diff] [blame] | 385 | if let Some(cpu_capacity) = cpu.cpu_capacity { |
| 386 | cur.setprop_inplace(cstr!("capacity-dmips-mhz"), &cpu_capacity.to_be_bytes())?; |
| 387 | } |
Pierre-Clément Tosi | c37c72e | 2024-02-14 12:18:12 +0000 | [diff] [blame] | 388 | patch_opptable(cur, cpu.opptable_info)?; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 389 | } |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 390 | let mut next = get_nth_compatible(fdt, cpus.len(), COMPAT)?; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 391 | while let Some(current) = next { |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 392 | next = current.delete_and_next_compatible(COMPAT)?; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 393 | } |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 394 | |
| 395 | if let Some(topology) = topology { |
| 396 | for (n, cluster) in topology.clusters.iter().enumerate() { |
| 397 | let path = CString::new(format!("/cpus/cpu-map/cluster{n}")).unwrap(); |
| 398 | let cluster_node = fdt.node_mut(&path)?.unwrap(); |
| 399 | if let Some(cluster) = cluster { |
| 400 | let mut iter = cluster_node.first_subnode()?; |
| 401 | for core in cluster.cores { |
| 402 | let mut core_node = iter.unwrap(); |
| 403 | iter = if let Some(core_idx) = core { |
| 404 | let phandle = *cpu_phandles.get(core_idx).unwrap(); |
| 405 | let value = u32::from(phandle).to_be_bytes(); |
| 406 | core_node.setprop_inplace(cstr!("cpu"), &value)?; |
| 407 | core_node.next_subnode()? |
| 408 | } else { |
| 409 | core_node.delete_and_next_subnode()? |
| 410 | }; |
| 411 | } |
| 412 | assert!(iter.is_none()); |
| 413 | } else { |
| 414 | cluster_node.nop()?; |
| 415 | } |
| 416 | } |
| 417 | } else { |
| 418 | fdt.node_mut(cstr!("/cpus/cpu-map"))?.unwrap().nop()?; |
| 419 | } |
| 420 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 421 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 422 | } |
| 423 | |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 424 | /// Read candidate properties' names from DT which could be overlaid |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 425 | fn parse_vm_ref_dt(fdt: &Fdt) -> libfdt::Result<BTreeMap<CString, Vec<u8>>> { |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 426 | let mut property_map = BTreeMap::new(); |
Seungjae Yoo | ed67fd5 | 2023-11-29 18:54:36 +0900 | [diff] [blame] | 427 | if let Some(avf_node) = fdt.node(cstr!("/avf"))? { |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 428 | for property in avf_node.properties()? { |
| 429 | let name = property.name()?; |
| 430 | let value = property.value()?; |
| 431 | property_map.insert( |
| 432 | CString::new(name.to_bytes()).map_err(|_| FdtError::BadValue)?, |
| 433 | value.to_vec(), |
| 434 | ); |
Seungjae Yoo | ed67fd5 | 2023-11-29 18:54:36 +0900 | [diff] [blame] | 435 | } |
| 436 | } |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 437 | Ok(property_map) |
Seungjae Yoo | ed67fd5 | 2023-11-29 18:54:36 +0900 | [diff] [blame] | 438 | } |
| 439 | |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 440 | /// Overlay VM reference DT into VM DT based on the props_info. Property is overlaid in vm_dt only |
| 441 | /// when it exists both in vm_ref_dt and props_info. If the values mismatch, it returns error. |
| 442 | fn validate_vm_ref_dt( |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 443 | vm_dt: &mut Fdt, |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 444 | vm_ref_dt: &Fdt, |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 445 | props_info: &BTreeMap<CString, Vec<u8>>, |
Seungjae Yoo | 192e99c | 2023-12-15 16:42:39 +0900 | [diff] [blame] | 446 | ) -> libfdt::Result<()> { |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 447 | let mut root_vm_dt = vm_dt.root_mut()?; |
| 448 | let mut avf_vm_dt = root_vm_dt.add_subnode(cstr!("avf"))?; |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 449 | // TODO(b/318431677): Validate nodes beyond /avf. |
| 450 | let avf_node = vm_ref_dt.node(cstr!("/avf"))?.ok_or(FdtError::NotFound)?; |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 451 | for (name, value) in props_info.iter() { |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 452 | if let Some(ref_value) = avf_node.getprop(name)? { |
| 453 | if value != ref_value { |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 454 | error!( |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 455 | "Property mismatches while applying overlay VM reference DT. \ |
| 456 | Name:{:?}, Value from host as hex:{:x?}, Value from VM reference DT as hex:{:x?}", |
| 457 | name, value, ref_value |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 458 | ); |
| 459 | return Err(FdtError::BadValue); |
| 460 | } |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 461 | avf_vm_dt.setprop(name, ref_value)?; |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 462 | } |
| 463 | } |
Seungjae Yoo | ed67fd5 | 2023-11-29 18:54:36 +0900 | [diff] [blame] | 464 | Ok(()) |
| 465 | } |
| 466 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 467 | #[derive(Debug)] |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 468 | struct PciInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 469 | ranges: [PciAddrRange; 2], |
| 470 | irq_masks: ArrayVec<[PciIrqMask; PciInfo::MAX_IRQS]>, |
| 471 | irq_maps: ArrayVec<[PciIrqMap; PciInfo::MAX_IRQS]>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 472 | } |
| 473 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 474 | impl PciInfo { |
| 475 | const IRQ_MASK_CELLS: usize = 4; |
| 476 | const IRQ_MAP_CELLS: usize = 10; |
Nikita Ioffe | 85d8026 | 2023-07-12 17:34:07 +0100 | [diff] [blame] | 477 | const MAX_IRQS: usize = 10; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 478 | } |
| 479 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 480 | type PciAddrRange = AddressRange<(u32, u64), u64, u64>; |
| 481 | type PciIrqMask = [u32; PciInfo::IRQ_MASK_CELLS]; |
| 482 | type PciIrqMap = [u32; PciInfo::IRQ_MAP_CELLS]; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 483 | |
| 484 | /// Iterator that takes N cells as a chunk |
| 485 | struct CellChunkIterator<'a, const N: usize> { |
| 486 | cells: CellIterator<'a>, |
| 487 | } |
| 488 | |
| 489 | impl<'a, const N: usize> CellChunkIterator<'a, N> { |
| 490 | fn new(cells: CellIterator<'a>) -> Self { |
| 491 | Self { cells } |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | impl<'a, const N: usize> Iterator for CellChunkIterator<'a, N> { |
| 496 | type Item = [u32; N]; |
| 497 | fn next(&mut self) -> Option<Self::Item> { |
| 498 | let mut ret: Self::Item = [0; N]; |
| 499 | for i in ret.iter_mut() { |
| 500 | *i = self.cells.next()?; |
| 501 | } |
| 502 | Some(ret) |
| 503 | } |
| 504 | } |
| 505 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 506 | /// Read pci host controller ranges, irq maps, and irq map masks from DT |
| 507 | fn read_pci_info_from(fdt: &Fdt) -> libfdt::Result<PciInfo> { |
| 508 | let node = |
| 509 | fdt.compatible_nodes(cstr!("pci-host-cam-generic"))?.next().ok_or(FdtError::NotFound)?; |
| 510 | |
| 511 | let mut ranges = node.ranges::<(u32, u64), u64, u64>()?.ok_or(FdtError::NotFound)?; |
| 512 | let range0 = ranges.next().ok_or(FdtError::NotFound)?; |
| 513 | let range1 = ranges.next().ok_or(FdtError::NotFound)?; |
| 514 | |
| 515 | let irq_masks = node.getprop_cells(cstr!("interrupt-map-mask"))?.ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | aa0f655 | 2023-07-12 14:49:35 +0000 | [diff] [blame] | 516 | let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MASK_CELLS }>::new(irq_masks); |
| 517 | let irq_masks = (&mut chunks).take(PciInfo::MAX_IRQS).collect(); |
| 518 | |
| 519 | if chunks.next().is_some() { |
| 520 | warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS); |
| 521 | return Err(FdtError::NoSpace); |
| 522 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 523 | |
| 524 | let irq_maps = node.getprop_cells(cstr!("interrupt-map"))?.ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | aa0f655 | 2023-07-12 14:49:35 +0000 | [diff] [blame] | 525 | let mut chunks = CellChunkIterator::<{ PciInfo::IRQ_MAP_CELLS }>::new(irq_maps); |
| 526 | let irq_maps = (&mut chunks).take(PciInfo::MAX_IRQS).collect(); |
| 527 | |
| 528 | if chunks.next().is_some() { |
| 529 | warn!("Input DT has more than {} PCI entries!", PciInfo::MAX_IRQS); |
| 530 | return Err(FdtError::NoSpace); |
| 531 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 532 | |
| 533 | Ok(PciInfo { ranges: [range0, range1], irq_masks, irq_maps }) |
| 534 | } |
| 535 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 536 | 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] | 537 | for range in pci_info.ranges.iter() { |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 538 | validate_pci_addr_range(range, memory_range)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 539 | } |
| 540 | for irq_mask in pci_info.irq_masks.iter() { |
| 541 | validate_pci_irq_mask(irq_mask)?; |
| 542 | } |
| 543 | for (idx, irq_map) in pci_info.irq_maps.iter().enumerate() { |
| 544 | validate_pci_irq_map(irq_map, idx)?; |
| 545 | } |
| 546 | Ok(()) |
| 547 | } |
| 548 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 549 | fn validate_pci_addr_range( |
| 550 | range: &PciAddrRange, |
| 551 | memory_range: &Range<usize>, |
| 552 | ) -> Result<(), RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 553 | let mem_flags = PciMemoryFlags(range.addr.0); |
| 554 | let range_type = mem_flags.range_type(); |
| 555 | let prefetchable = mem_flags.prefetchable(); |
| 556 | let bus_addr = range.addr.1; |
| 557 | let cpu_addr = range.parent_addr; |
| 558 | let size = range.size; |
| 559 | |
| 560 | if range_type != PciRangeType::Memory64 { |
| 561 | error!("Invalid range type {:?} for bus address {:#x} in PCI node", range_type, bus_addr); |
| 562 | return Err(RebootReason::InvalidFdt); |
| 563 | } |
| 564 | if prefetchable { |
| 565 | error!("PCI bus address {:#x} in PCI node is prefetchable", bus_addr); |
| 566 | return Err(RebootReason::InvalidFdt); |
| 567 | } |
| 568 | // Enforce ID bus-to-cpu mappings, as used by crosvm. |
| 569 | if bus_addr != cpu_addr { |
| 570 | error!("PCI bus address: {:#x} is different from CPU address: {:#x}", bus_addr, cpu_addr); |
| 571 | return Err(RebootReason::InvalidFdt); |
| 572 | } |
| 573 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 574 | let Some(bus_end) = bus_addr.checked_add(size) else { |
| 575 | error!("PCI address range size {:#x} overflows", size); |
| 576 | return Err(RebootReason::InvalidFdt); |
| 577 | }; |
Alice Wang | 63f4c9e | 2023-06-12 09:36:43 +0000 | [diff] [blame] | 578 | if bus_end > MAX_VIRT_ADDR.try_into().unwrap() { |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 579 | error!("PCI address end {:#x} is outside of translatable range", bus_end); |
| 580 | return Err(RebootReason::InvalidFdt); |
| 581 | } |
| 582 | |
| 583 | let memory_start = memory_range.start.try_into().unwrap(); |
| 584 | let memory_end = memory_range.end.try_into().unwrap(); |
| 585 | |
| 586 | if max(bus_addr, memory_start) < min(bus_end, memory_end) { |
| 587 | error!( |
| 588 | "PCI address range {:#x}-{:#x} overlaps with main memory range {:#x}-{:#x}", |
| 589 | bus_addr, bus_end, memory_start, memory_end |
| 590 | ); |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 591 | return Err(RebootReason::InvalidFdt); |
| 592 | } |
| 593 | |
| 594 | Ok(()) |
| 595 | } |
| 596 | |
| 597 | fn validate_pci_irq_mask(irq_mask: &PciIrqMask) -> Result<(), RebootReason> { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 598 | const IRQ_MASK_ADDR_HI: u32 = 0xf800; |
| 599 | const IRQ_MASK_ADDR_ME: u32 = 0x0; |
| 600 | const IRQ_MASK_ADDR_LO: u32 = 0x0; |
| 601 | const IRQ_MASK_ANY_IRQ: u32 = 0x7; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 602 | const EXPECTED: PciIrqMask = |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 603 | [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] | 604 | if *irq_mask != EXPECTED { |
| 605 | error!("Invalid PCI irq mask {:#?}", irq_mask); |
| 606 | return Err(RebootReason::InvalidFdt); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 607 | } |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 608 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 609 | } |
| 610 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 611 | fn validate_pci_irq_map(irq_map: &PciIrqMap, idx: usize) -> Result<(), RebootReason> { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 612 | const PCI_DEVICE_IDX: usize = 11; |
| 613 | const PCI_IRQ_ADDR_ME: u32 = 0; |
| 614 | const PCI_IRQ_ADDR_LO: u32 = 0; |
| 615 | const PCI_IRQ_INTC: u32 = 1; |
| 616 | const AARCH64_IRQ_BASE: u32 = 4; // from external/crosvm/aarch64/src/lib.rs |
| 617 | const GIC_SPI: u32 = 0; |
| 618 | const IRQ_TYPE_LEVEL_HIGH: u32 = 4; |
| 619 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 620 | let pci_addr = (irq_map[0], irq_map[1], irq_map[2]); |
| 621 | let pci_irq_number = irq_map[3]; |
| 622 | let _controller_phandle = irq_map[4]; // skipped. |
| 623 | let gic_addr = (irq_map[5], irq_map[6]); // address-cells is <2> for GIC |
| 624 | // interrupt-cells is <3> for GIC |
| 625 | let gic_peripheral_interrupt_type = irq_map[7]; |
| 626 | let gic_irq_number = irq_map[8]; |
| 627 | let gic_irq_type = irq_map[9]; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 628 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 629 | let phys_hi: u32 = (0x1 << PCI_DEVICE_IDX) * (idx + 1) as u32; |
| 630 | 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] | 631 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 632 | if pci_addr != expected_pci_addr { |
| 633 | error!("PCI device address {:#x} {:#x} {:#x} in interrupt-map is different from expected address \ |
| 634 | {:#x} {:#x} {:#x}", |
| 635 | pci_addr.0, pci_addr.1, pci_addr.2, expected_pci_addr.0, expected_pci_addr.1, expected_pci_addr.2); |
| 636 | return Err(RebootReason::InvalidFdt); |
| 637 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 638 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 639 | if pci_irq_number != PCI_IRQ_INTC { |
| 640 | error!( |
| 641 | "PCI INT# {:#x} in interrupt-map is different from expected value {:#x}", |
| 642 | pci_irq_number, PCI_IRQ_INTC |
| 643 | ); |
| 644 | return Err(RebootReason::InvalidFdt); |
| 645 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 646 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 647 | if gic_addr != (0, 0) { |
| 648 | error!( |
| 649 | "GIC address {:#x} {:#x} in interrupt-map is different from expected address \ |
| 650 | {:#x} {:#x}", |
| 651 | gic_addr.0, gic_addr.1, 0, 0 |
| 652 | ); |
| 653 | return Err(RebootReason::InvalidFdt); |
| 654 | } |
| 655 | |
| 656 | if gic_peripheral_interrupt_type != GIC_SPI { |
| 657 | error!("GIC peripheral interrupt type {:#x} in interrupt-map is different from expected value \ |
| 658 | {:#x}", gic_peripheral_interrupt_type, GIC_SPI); |
| 659 | return Err(RebootReason::InvalidFdt); |
| 660 | } |
| 661 | |
| 662 | let irq_nr: u32 = AARCH64_IRQ_BASE + (idx as u32); |
| 663 | if gic_irq_number != irq_nr { |
| 664 | error!( |
| 665 | "GIC irq number {:#x} in interrupt-map is unexpected. Expected {:#x}", |
| 666 | gic_irq_number, irq_nr |
| 667 | ); |
| 668 | return Err(RebootReason::InvalidFdt); |
| 669 | } |
| 670 | |
| 671 | if gic_irq_type != IRQ_TYPE_LEVEL_HIGH { |
| 672 | error!( |
| 673 | "IRQ type in {:#x} is invalid. Must be LEVEL_HIGH {:#x}", |
| 674 | gic_irq_type, IRQ_TYPE_LEVEL_HIGH |
| 675 | ); |
| 676 | return Err(RebootReason::InvalidFdt); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 677 | } |
| 678 | Ok(()) |
| 679 | } |
| 680 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 681 | fn patch_pci_info(fdt: &mut Fdt, pci_info: &PciInfo) -> libfdt::Result<()> { |
| 682 | let mut node = fdt |
| 683 | .root_mut()? |
| 684 | .next_compatible(cstr!("pci-host-cam-generic"))? |
| 685 | .ok_or(FdtError::NotFound)?; |
| 686 | |
| 687 | let irq_masks_size = pci_info.irq_masks.len() * size_of::<PciIrqMask>(); |
| 688 | node.trimprop(cstr!("interrupt-map-mask"), irq_masks_size)?; |
| 689 | |
| 690 | let irq_maps_size = pci_info.irq_maps.len() * size_of::<PciIrqMap>(); |
| 691 | node.trimprop(cstr!("interrupt-map"), irq_maps_size)?; |
| 692 | |
| 693 | node.setprop_inplace( |
| 694 | cstr!("ranges"), |
| 695 | flatten(&[pci_info.ranges[0].to_cells(), pci_info.ranges[1].to_cells()]), |
| 696 | ) |
| 697 | } |
| 698 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 699 | #[derive(Default, Debug)] |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 700 | struct SerialInfo { |
| 701 | addrs: ArrayVec<[u64; Self::MAX_SERIALS]>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 702 | } |
| 703 | |
| 704 | impl SerialInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 705 | const MAX_SERIALS: usize = 4; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 706 | } |
| 707 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 708 | fn read_serial_info_from(fdt: &Fdt) -> libfdt::Result<SerialInfo> { |
Pierre-Clément Tosi | be89361 | 2024-02-05 14:23:44 +0000 | [diff] [blame] | 709 | let mut addrs = ArrayVec::new(); |
| 710 | |
| 711 | let mut serial_nodes = fdt.compatible_nodes(cstr!("ns16550a"))?; |
| 712 | for node in serial_nodes.by_ref().take(addrs.capacity()) { |
Alice Wang | 6ff2d0c | 2023-09-19 15:28:43 +0000 | [diff] [blame] | 713 | let reg = node.first_reg()?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 714 | addrs.push(reg.addr); |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 715 | } |
Pierre-Clément Tosi | be89361 | 2024-02-05 14:23:44 +0000 | [diff] [blame] | 716 | if serial_nodes.next().is_some() { |
| 717 | warn!("DT has more than {} UART nodes: discarding extra nodes.", addrs.capacity()); |
| 718 | } |
| 719 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 720 | Ok(SerialInfo { addrs }) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 721 | } |
| 722 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 723 | /// Patch the DT by deleting the ns16550a compatible nodes whose address are unknown |
| 724 | fn patch_serial_info(fdt: &mut Fdt, serial_info: &SerialInfo) -> libfdt::Result<()> { |
| 725 | let name = cstr!("ns16550a"); |
| 726 | let mut next = fdt.root_mut()?.next_compatible(name); |
| 727 | while let Some(current) = next? { |
Pierre-Clément Tosi | c01fd0d | 2024-01-25 22:26:22 +0000 | [diff] [blame] | 728 | let reg = |
| 729 | current.as_node().reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)?; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 730 | next = if !serial_info.addrs.contains(®.addr) { |
| 731 | current.delete_and_next_compatible(name) |
| 732 | } else { |
| 733 | current.next_compatible(name) |
| 734 | } |
| 735 | } |
| 736 | Ok(()) |
| 737 | } |
| 738 | |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 739 | fn validate_swiotlb_info( |
| 740 | swiotlb_info: &SwiotlbInfo, |
| 741 | memory: &Range<usize>, |
| 742 | ) -> Result<(), RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 743 | let size = swiotlb_info.size; |
| 744 | let align = swiotlb_info.align; |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 745 | |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 746 | if size == 0 || (size % GUEST_PAGE_SIZE) != 0 { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 747 | error!("Invalid swiotlb size {:#x}", size); |
| 748 | return Err(RebootReason::InvalidFdt); |
| 749 | } |
| 750 | |
Pierre-Clément Tosi | be3a97b | 2023-05-19 14:56:23 +0000 | [diff] [blame] | 751 | if let Some(align) = align.filter(|&a| a % GUEST_PAGE_SIZE != 0) { |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 752 | error!("Invalid swiotlb alignment {:#x}", align); |
| 753 | return Err(RebootReason::InvalidFdt); |
| 754 | } |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 755 | |
Alice Wang | 9cfbfd6 | 2023-06-14 11:19:03 +0000 | [diff] [blame] | 756 | if let Some(addr) = swiotlb_info.addr { |
| 757 | if addr.checked_add(size).is_none() { |
| 758 | error!("Invalid swiotlb range: addr:{addr:#x} size:{size:#x}"); |
| 759 | return Err(RebootReason::InvalidFdt); |
| 760 | } |
| 761 | } |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 762 | if let Some(range) = swiotlb_info.fixed_range() { |
| 763 | if !range.is_within(memory) { |
| 764 | error!("swiotlb range {range:#x?} not part of memory range {memory:#x?}"); |
| 765 | return Err(RebootReason::InvalidFdt); |
| 766 | } |
| 767 | } |
| 768 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 769 | Ok(()) |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 770 | } |
| 771 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 772 | fn patch_swiotlb_info(fdt: &mut Fdt, swiotlb_info: &SwiotlbInfo) -> libfdt::Result<()> { |
| 773 | let mut node = |
| 774 | 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] | 775 | |
| 776 | if let Some(range) = swiotlb_info.fixed_range() { |
Pierre-Clément Tosi | c27c427 | 2023-05-19 15:46:26 +0000 | [diff] [blame] | 777 | node.setprop_addrrange_inplace( |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 778 | cstr!("reg"), |
| 779 | range.start.try_into().unwrap(), |
| 780 | range.len().try_into().unwrap(), |
| 781 | )?; |
Pierre-Clément Tosi | be3a97b | 2023-05-19 14:56:23 +0000 | [diff] [blame] | 782 | node.nop_property(cstr!("size"))?; |
| 783 | node.nop_property(cstr!("alignment"))?; |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 784 | } else { |
Pierre-Clément Tosi | c27c427 | 2023-05-19 15:46:26 +0000 | [diff] [blame] | 785 | node.nop_property(cstr!("reg"))?; |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 786 | 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] | 787 | node.setprop_inplace(cstr!("alignment"), &swiotlb_info.align.unwrap().to_be_bytes())?; |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 788 | } |
| 789 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 790 | Ok(()) |
| 791 | } |
| 792 | |
| 793 | fn patch_gic(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> { |
| 794 | let node = fdt.compatible_nodes(cstr!("arm,gic-v3"))?.next().ok_or(FdtError::NotFound)?; |
| 795 | let mut ranges = node.reg()?.ok_or(FdtError::NotFound)?; |
| 796 | let range0 = ranges.next().ok_or(FdtError::NotFound)?; |
| 797 | let mut range1 = ranges.next().ok_or(FdtError::NotFound)?; |
| 798 | |
| 799 | let addr = range0.addr; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 800 | // `read_cpu_info_from()` guarantees that we have at most MAX_CPUS. |
| 801 | const_assert!(DeviceTreeInfo::gic_patched_size(DeviceTreeInfo::MAX_CPUS).is_some()); |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 802 | 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] | 803 | |
| 804 | // range1 is just below range0 |
| 805 | range1.addr = addr - size; |
| 806 | range1.size = Some(size); |
| 807 | |
Pierre-Clément Tosi | eea2a98 | 2024-02-05 15:10:59 +0000 | [diff] [blame] | 808 | let (addr0, size0) = range0.to_cells(); |
| 809 | let (addr1, size1) = range1.to_cells(); |
| 810 | let value = [addr0, size0.unwrap(), addr1, size1.unwrap()]; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 811 | |
| 812 | let mut node = |
| 813 | fdt.root_mut()?.next_compatible(cstr!("arm,gic-v3"))?.ok_or(FdtError::NotFound)?; |
| 814 | node.setprop_inplace(cstr!("reg"), flatten(&value)) |
| 815 | } |
| 816 | |
| 817 | fn patch_timer(fdt: &mut Fdt, num_cpus: usize) -> libfdt::Result<()> { |
| 818 | const NUM_INTERRUPTS: usize = 4; |
| 819 | const CELLS_PER_INTERRUPT: usize = 3; |
| 820 | let node = fdt.compatible_nodes(cstr!("arm,armv8-timer"))?.next().ok_or(FdtError::NotFound)?; |
| 821 | let interrupts = node.getprop_cells(cstr!("interrupts"))?.ok_or(FdtError::NotFound)?; |
| 822 | let mut value: ArrayVec<[u32; NUM_INTERRUPTS * CELLS_PER_INTERRUPT]> = |
| 823 | interrupts.take(NUM_INTERRUPTS * CELLS_PER_INTERRUPT).collect(); |
| 824 | |
| 825 | let num_cpus: u32 = num_cpus.try_into().unwrap(); |
| 826 | let cpu_mask: u32 = (((0x1 << num_cpus) - 1) & 0xff) << 8; |
| 827 | for v in value.iter_mut().skip(2).step_by(CELLS_PER_INTERRUPT) { |
| 828 | *v |= cpu_mask; |
| 829 | } |
| 830 | for v in value.iter_mut() { |
| 831 | *v = v.to_be(); |
| 832 | } |
| 833 | |
Pierre-Clément Tosi | 0edc4d6 | 2024-02-05 14:13:53 +0000 | [diff] [blame] | 834 | let value = value.into_inner(); |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 835 | |
| 836 | let mut node = |
| 837 | fdt.root_mut()?.next_compatible(cstr!("arm,armv8-timer"))?.ok_or(FdtError::NotFound)?; |
Pierre-Clément Tosi | 0edc4d6 | 2024-02-05 14:13:53 +0000 | [diff] [blame] | 838 | node.setprop_inplace(cstr!("interrupts"), value.as_bytes()) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 839 | } |
| 840 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 841 | #[derive(Debug)] |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 842 | struct VcpufreqInfo { |
| 843 | addr: u64, |
| 844 | size: u64, |
| 845 | } |
| 846 | |
| 847 | fn patch_vcpufreq(fdt: &mut Fdt, vcpufreq_info: &Option<VcpufreqInfo>) -> libfdt::Result<()> { |
| 848 | let mut node = fdt.node_mut(cstr!("/cpufreq"))?.unwrap(); |
| 849 | if let Some(info) = vcpufreq_info { |
| 850 | node.setprop_addrrange_inplace(cstr!("reg"), info.addr, info.size) |
| 851 | } else { |
| 852 | node.nop() |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | #[derive(Debug)] |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 857 | pub struct DeviceTreeInfo { |
| 858 | pub kernel_range: Option<Range<usize>>, |
| 859 | pub initrd_range: Option<Range<usize>>, |
| 860 | pub memory_range: Range<usize>, |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 861 | bootargs: Option<CString>, |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 862 | cpus: ArrayVec<[CpuInfo; DeviceTreeInfo::MAX_CPUS]>, |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 863 | cpu_topology: Option<CpuTopology>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 864 | pci_info: PciInfo, |
| 865 | serial_info: SerialInfo, |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 866 | pub swiotlb_info: SwiotlbInfo, |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 867 | device_assignment: Option<DeviceAssignmentInfo>, |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 868 | vm_ref_dt_props_info: BTreeMap<CString, Vec<u8>>, |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 869 | vcpufreq_info: Option<VcpufreqInfo>, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 870 | } |
| 871 | |
| 872 | impl DeviceTreeInfo { |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 873 | const MAX_CPUS: usize = 16; |
| 874 | |
| 875 | const fn gic_patched_size(num_cpus: usize) -> Option<usize> { |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 876 | const GIC_REDIST_SIZE_PER_CPU: usize = 32 * SIZE_4KB; |
| 877 | |
| 878 | GIC_REDIST_SIZE_PER_CPU.checked_mul(num_cpus) |
| 879 | } |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 880 | } |
| 881 | |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 882 | pub fn sanitize_device_tree( |
| 883 | fdt: &mut [u8], |
| 884 | vm_dtbo: Option<&mut [u8]>, |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 885 | vm_ref_dt: Option<&[u8]>, |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 886 | ) -> Result<DeviceTreeInfo, RebootReason> { |
| 887 | let fdt = Fdt::from_mut_slice(fdt).map_err(|e| { |
| 888 | error!("Failed to load FDT: {e}"); |
| 889 | RebootReason::InvalidFdt |
| 890 | })?; |
| 891 | |
| 892 | let vm_dtbo = match vm_dtbo { |
| 893 | Some(vm_dtbo) => Some(VmDtbo::from_mut_slice(vm_dtbo).map_err(|e| { |
| 894 | error!("Failed to load VM DTBO: {e}"); |
| 895 | RebootReason::InvalidFdt |
| 896 | })?), |
| 897 | None => None, |
| 898 | }; |
| 899 | |
| 900 | let info = parse_device_tree(fdt, vm_dtbo.as_deref())?; |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 901 | |
Pierre-Clément Tosi | ce0b36d | 2024-01-26 10:50:05 +0000 | [diff] [blame] | 902 | // SAFETY: We trust that the template (hardcoded in our RO data) is a valid DT. |
| 903 | let fdt_template = unsafe { Fdt::unchecked_from_slice(pvmfw_fdt_template::RAW) }; |
| 904 | fdt.clone_from(fdt_template).map_err(|e| { |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 905 | error!("Failed to instantiate FDT from the template DT: {e}"); |
| 906 | RebootReason::InvalidFdt |
| 907 | })?; |
| 908 | |
Jaewan Kim | 9220e85 | 2023-12-01 10:58:40 +0900 | [diff] [blame] | 909 | fdt.unpack().map_err(|e| { |
| 910 | error!("Failed to unpack DT for patching: {e}"); |
| 911 | RebootReason::InvalidFdt |
| 912 | })?; |
| 913 | |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 914 | if let Some(device_assignment_info) = &info.device_assignment { |
| 915 | let vm_dtbo = vm_dtbo.unwrap(); |
| 916 | device_assignment_info.filter(vm_dtbo).map_err(|e| { |
| 917 | error!("Failed to filter VM DTBO: {e}"); |
| 918 | RebootReason::InvalidFdt |
| 919 | })?; |
| 920 | // SAFETY: Damaged VM DTBO isn't used in this API after this unsafe block. |
| 921 | // VM DTBO can't be reused in any way as Fdt nor VmDtbo outside of this API because |
| 922 | // it can only be instantiated after validation. |
| 923 | unsafe { |
| 924 | fdt.apply_overlay(vm_dtbo.as_mut()).map_err(|e| { |
| 925 | error!("Failed to apply filtered VM DTBO: {e}"); |
| 926 | RebootReason::InvalidFdt |
| 927 | })?; |
| 928 | } |
| 929 | } |
| 930 | |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 931 | if let Some(vm_ref_dt) = vm_ref_dt { |
| 932 | let vm_ref_dt = Fdt::from_slice(vm_ref_dt).map_err(|e| { |
| 933 | error!("Failed to load VM reference DT: {e}"); |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 934 | RebootReason::InvalidFdt |
| 935 | })?; |
| 936 | |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 937 | validate_vm_ref_dt(fdt, vm_ref_dt, &info.vm_ref_dt_props_info).map_err(|e| { |
| 938 | error!("Failed to apply VM reference DT: {e}"); |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 939 | RebootReason::InvalidFdt |
| 940 | })?; |
| 941 | } |
| 942 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 943 | patch_device_tree(fdt, &info)?; |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 944 | |
Jaewan Kim | 19b984f | 2023-12-04 15:16:50 +0900 | [diff] [blame] | 945 | // TODO(b/317201360): Ensure no overlapping in <reg> among devices |
| 946 | |
Jaewan Kim | 9220e85 | 2023-12-01 10:58:40 +0900 | [diff] [blame] | 947 | fdt.pack().map_err(|e| { |
| 948 | error!("Failed to unpack DT after patching: {e}"); |
| 949 | RebootReason::InvalidFdt |
| 950 | })?; |
| 951 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 952 | Ok(info) |
Jiyong Park | 8331612 | 2023-03-21 09:39:39 +0900 | [diff] [blame] | 953 | } |
| 954 | |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 955 | fn parse_device_tree(fdt: &Fdt, vm_dtbo: Option<&VmDtbo>) -> Result<DeviceTreeInfo, RebootReason> { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 956 | let kernel_range = read_kernel_range_from(fdt).map_err(|e| { |
| 957 | error!("Failed to read kernel range from DT: {e}"); |
| 958 | RebootReason::InvalidFdt |
| 959 | })?; |
| 960 | |
| 961 | let initrd_range = read_initrd_range_from(fdt).map_err(|e| { |
| 962 | error!("Failed to read initrd range from DT: {e}"); |
| 963 | RebootReason::InvalidFdt |
| 964 | })?; |
| 965 | |
Alice Wang | 0d52747 | 2023-06-13 14:55:38 +0000 | [diff] [blame] | 966 | let memory_range = read_and_validate_memory_range(fdt)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 967 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 968 | let bootargs = read_bootargs_from(fdt).map_err(|e| { |
| 969 | error!("Failed to read bootargs from DT: {e}"); |
| 970 | RebootReason::InvalidFdt |
| 971 | })?; |
| 972 | |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 973 | let (cpus, cpu_topology) = read_cpu_info_from(fdt).map_err(|e| { |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 974 | error!("Failed to read CPU info from DT: {e}"); |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 975 | RebootReason::InvalidFdt |
| 976 | })?; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 977 | validate_cpu_info(&cpus).map_err(|e| { |
| 978 | error!("Failed to validate CPU info from DT: {e}"); |
Alice Wang | abc7d63 | 2023-06-14 09:10:14 +0000 | [diff] [blame] | 979 | RebootReason::InvalidFdt |
| 980 | })?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 981 | |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 982 | let vcpufreq_info = read_vcpufreq_info(fdt).map_err(|e| { |
| 983 | error!("Failed to read vcpufreq info from DT: {e}"); |
| 984 | RebootReason::InvalidFdt |
| 985 | })?; |
| 986 | if let Some(ref info) = vcpufreq_info { |
| 987 | validate_vcpufreq_info(info, &cpus).map_err(|e| { |
| 988 | error!("Failed to validate vcpufreq info from DT: {e}"); |
| 989 | RebootReason::InvalidFdt |
| 990 | })?; |
| 991 | } |
| 992 | |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 993 | let pci_info = read_pci_info_from(fdt).map_err(|e| { |
| 994 | error!("Failed to read pci info from DT: {e}"); |
| 995 | RebootReason::InvalidFdt |
| 996 | })?; |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 997 | validate_pci_info(&pci_info, &memory_range)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 998 | |
| 999 | let serial_info = read_serial_info_from(fdt).map_err(|e| { |
| 1000 | error!("Failed to read serial info from DT: {e}"); |
| 1001 | RebootReason::InvalidFdt |
| 1002 | })?; |
| 1003 | |
Alice Wang | 9cfbfd6 | 2023-06-14 11:19:03 +0000 | [diff] [blame] | 1004 | let swiotlb_info = SwiotlbInfo::new_from_fdt(fdt).map_err(|e| { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 1005 | error!("Failed to read swiotlb info from DT: {e}"); |
| 1006 | RebootReason::InvalidFdt |
| 1007 | })?; |
Srivatsa Vaddagiri | 2df297f | 2023-04-12 03:11:05 -0700 | [diff] [blame] | 1008 | validate_swiotlb_info(&swiotlb_info, &memory_range)?; |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 1009 | |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 1010 | let device_assignment = match vm_dtbo { |
Jaewan Kim | 52477ae | 2023-11-21 21:20:52 +0900 | [diff] [blame] | 1011 | Some(vm_dtbo) => { |
| 1012 | if let Some(hypervisor) = hyp::get_device_assigner() { |
| 1013 | DeviceAssignmentInfo::parse(fdt, vm_dtbo, hypervisor).map_err(|e| { |
| 1014 | error!("Failed to parse device assignment from DT and VM DTBO: {e}"); |
| 1015 | RebootReason::InvalidFdt |
| 1016 | })? |
| 1017 | } else { |
| 1018 | warn!( |
| 1019 | "Device assignment is ignored because device assigning hypervisor is missing" |
| 1020 | ); |
| 1021 | None |
| 1022 | } |
| 1023 | } |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 1024 | None => None, |
| 1025 | }; |
| 1026 | |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 1027 | let vm_ref_dt_props_info = parse_vm_ref_dt(fdt).map_err(|e| { |
Seungjae Yoo | 013f4c4 | 2024-01-02 13:04:19 +0900 | [diff] [blame] | 1028 | error!("Failed to read names of properties under /avf from DT: {e}"); |
| 1029 | RebootReason::InvalidFdt |
| 1030 | })?; |
Seungjae Yoo | ed67fd5 | 2023-11-29 18:54:36 +0900 | [diff] [blame] | 1031 | |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 1032 | Ok(DeviceTreeInfo { |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 1033 | kernel_range, |
| 1034 | initrd_range, |
| 1035 | memory_range, |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1036 | bootargs, |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 1037 | cpus, |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 1038 | cpu_topology, |
Jiyong Park | 6a8789a | 2023-03-21 14:50:59 +0900 | [diff] [blame] | 1039 | pci_info, |
| 1040 | serial_info, |
| 1041 | swiotlb_info, |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 1042 | device_assignment, |
Seungjae Yoo | f0af81d | 2024-01-17 13:48:36 +0900 | [diff] [blame] | 1043 | vm_ref_dt_props_info, |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 1044 | vcpufreq_info, |
Jiyong Park | 00ceff3 | 2023-03-13 05:43:23 +0000 | [diff] [blame] | 1045 | }) |
| 1046 | } |
| 1047 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1048 | fn patch_device_tree(fdt: &mut Fdt, info: &DeviceTreeInfo) -> Result<(), RebootReason> { |
| 1049 | if let Some(initrd_range) = &info.initrd_range { |
| 1050 | patch_initrd_range(fdt, initrd_range).map_err(|e| { |
| 1051 | error!("Failed to patch initrd range to DT: {e}"); |
| 1052 | RebootReason::InvalidFdt |
| 1053 | })?; |
| 1054 | } |
| 1055 | patch_memory_range(fdt, &info.memory_range).map_err(|e| { |
| 1056 | error!("Failed to patch memory range to DT: {e}"); |
| 1057 | RebootReason::InvalidFdt |
| 1058 | })?; |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1059 | if let Some(bootargs) = &info.bootargs { |
| 1060 | patch_bootargs(fdt, bootargs.as_c_str()).map_err(|e| { |
| 1061 | error!("Failed to patch bootargs to DT: {e}"); |
| 1062 | RebootReason::InvalidFdt |
| 1063 | })?; |
| 1064 | } |
Pierre-Clément Tosi | a0823f1 | 2024-02-15 16:41:05 +0000 | [diff] [blame^] | 1065 | patch_cpus(fdt, &info.cpus, &info.cpu_topology).map_err(|e| { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1066 | error!("Failed to patch cpus to DT: {e}"); |
| 1067 | RebootReason::InvalidFdt |
| 1068 | })?; |
David Dai | 9bdb10c | 2024-02-01 22:42:54 -0800 | [diff] [blame] | 1069 | patch_vcpufreq(fdt, &info.vcpufreq_info).map_err(|e| { |
| 1070 | error!("Failed to patch vcpufreq info to DT: {e}"); |
| 1071 | RebootReason::InvalidFdt |
| 1072 | })?; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1073 | patch_pci_info(fdt, &info.pci_info).map_err(|e| { |
| 1074 | error!("Failed to patch pci info to DT: {e}"); |
| 1075 | RebootReason::InvalidFdt |
| 1076 | })?; |
| 1077 | patch_serial_info(fdt, &info.serial_info).map_err(|e| { |
| 1078 | error!("Failed to patch serial info to DT: {e}"); |
| 1079 | RebootReason::InvalidFdt |
| 1080 | })?; |
| 1081 | patch_swiotlb_info(fdt, &info.swiotlb_info).map_err(|e| { |
| 1082 | error!("Failed to patch swiotlb info to DT: {e}"); |
| 1083 | RebootReason::InvalidFdt |
| 1084 | })?; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 1085 | patch_gic(fdt, info.cpus.len()).map_err(|e| { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1086 | error!("Failed to patch gic info to DT: {e}"); |
| 1087 | RebootReason::InvalidFdt |
| 1088 | })?; |
Pierre-Clément Tosi | 689e473 | 2024-02-05 14:39:51 +0000 | [diff] [blame] | 1089 | patch_timer(fdt, info.cpus.len()).map_err(|e| { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1090 | error!("Failed to patch timer info to DT: {e}"); |
| 1091 | RebootReason::InvalidFdt |
| 1092 | })?; |
Jaewan Kim | c6e023b | 2023-10-12 15:11:05 +0900 | [diff] [blame] | 1093 | if let Some(device_assignment) = &info.device_assignment { |
| 1094 | // Note: We patch values after VM DTBO is overlaid because patch may require more space |
| 1095 | // then VM DTBO's underlying slice is allocated. |
| 1096 | device_assignment.patch(fdt).map_err(|e| { |
| 1097 | error!("Failed to patch device assignment info to DT: {e}"); |
| 1098 | RebootReason::InvalidFdt |
| 1099 | })?; |
| 1100 | } |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1101 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 1102 | Ok(()) |
| 1103 | } |
| 1104 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 1105 | /// Modifies the input DT according to the fields of the configuration. |
| 1106 | pub fn modify_for_next_stage( |
| 1107 | fdt: &mut Fdt, |
| 1108 | bcc: &[u8], |
| 1109 | new_instance: bool, |
| 1110 | strict_boot: bool, |
Alan Stokes | 6561833 | 2023-12-15 14:09:25 +0000 | [diff] [blame] | 1111 | debug_policy: Option<&[u8]>, |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 1112 | debuggable: bool, |
Pierre-Clément Tosi | 8025197 | 2023-07-12 12:51:12 +0000 | [diff] [blame] | 1113 | kaslr_seed: u64, |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 1114 | ) -> libfdt::Result<()> { |
Pierre-Clément Tosi | eb887ac | 2023-05-02 13:33:37 +0000 | [diff] [blame] | 1115 | if let Some(debug_policy) = debug_policy { |
| 1116 | let backup = Vec::from(fdt.as_slice()); |
| 1117 | fdt.unpack()?; |
| 1118 | let backup_fdt = Fdt::from_slice(backup.as_slice()).unwrap(); |
| 1119 | if apply_debug_policy(fdt, backup_fdt, debug_policy)? { |
| 1120 | info!("Debug policy applied."); |
| 1121 | } else { |
| 1122 | // apply_debug_policy restored fdt to backup_fdt so unpack it again. |
| 1123 | fdt.unpack()?; |
| 1124 | } |
| 1125 | } else { |
| 1126 | info!("No debug policy found."); |
| 1127 | fdt.unpack()?; |
| 1128 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 1129 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1130 | 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] | 1131 | |
Alice Wang | 56ec45b | 2023-06-15 08:30:32 +0000 | [diff] [blame] | 1132 | if let Some(mut chosen) = fdt.chosen_mut()? { |
| 1133 | empty_or_delete_prop(&mut chosen, cstr!("avf,strict-boot"), strict_boot)?; |
| 1134 | empty_or_delete_prop(&mut chosen, cstr!("avf,new-instance"), new_instance)?; |
Pierre-Clément Tosi | 8025197 | 2023-07-12 12:51:12 +0000 | [diff] [blame] | 1135 | chosen.setprop_inplace(cstr!("kaslr-seed"), &kaslr_seed.to_be_bytes())?; |
Alice Wang | 56ec45b | 2023-06-15 08:30:32 +0000 | [diff] [blame] | 1136 | }; |
Jiyong Park | 32f37ef | 2023-05-17 16:15:58 +0900 | [diff] [blame] | 1137 | if !debuggable { |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 1138 | if let Some(bootargs) = read_bootargs_from(fdt)? { |
| 1139 | filter_out_dangerous_bootargs(fdt, &bootargs)?; |
| 1140 | } |
| 1141 | } |
| 1142 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 1143 | fdt.pack()?; |
| 1144 | |
| 1145 | Ok(()) |
| 1146 | } |
| 1147 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1148 | /// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range |
| 1149 | 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] | 1150 | // We reject DTs with missing reserved-memory node as validation should have checked that the |
| 1151 | // "swiotlb" subnode (compatible = "restricted-dma-pool") was present. |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1152 | 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] | 1153 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1154 | 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] | 1155 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 1156 | let addr: u64 = addr.try_into().unwrap(); |
| 1157 | let size: u64 = size.try_into().unwrap(); |
| 1158 | 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] | 1159 | } |
| 1160 | |
Alice Wang | 56ec45b | 2023-06-15 08:30:32 +0000 | [diff] [blame] | 1161 | fn empty_or_delete_prop( |
| 1162 | fdt_node: &mut FdtNodeMut, |
| 1163 | prop_name: &CStr, |
| 1164 | keep_prop: bool, |
| 1165 | ) -> libfdt::Result<()> { |
| 1166 | if keep_prop { |
| 1167 | fdt_node.setprop_empty(prop_name) |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 1168 | } else { |
Alice Wang | 56ec45b | 2023-06-15 08:30:32 +0000 | [diff] [blame] | 1169 | fdt_node |
| 1170 | .delprop(prop_name) |
| 1171 | .or_else(|e| if e == FdtError::NotFound { Ok(()) } else { Err(e) }) |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 1172 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 1173 | } |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1174 | |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 1175 | /// Apply the debug policy overlay to the guest DT. |
| 1176 | /// |
| 1177 | /// 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] | 1178 | fn apply_debug_policy( |
| 1179 | fdt: &mut Fdt, |
| 1180 | backup_fdt: &Fdt, |
| 1181 | debug_policy: &[u8], |
| 1182 | ) -> libfdt::Result<bool> { |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 1183 | let mut debug_policy = Vec::from(debug_policy); |
| 1184 | let overlay = match Fdt::from_mut_slice(debug_policy.as_mut_slice()) { |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1185 | Ok(overlay) => overlay, |
| 1186 | Err(e) => { |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 1187 | warn!("Corrupted debug policy found: {e}. Not applying."); |
| 1188 | return Ok(false); |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1189 | } |
| 1190 | }; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1191 | |
Andrew Walbran | 20bb4e4 | 2023-07-07 13:55:55 +0100 | [diff] [blame] | 1192 | // SAFETY: on failure, the corrupted DT is restored using the backup. |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1193 | if let Err(e) = unsafe { fdt.apply_overlay(overlay) } { |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 1194 | warn!("Failed to apply debug policy: {e}. Recovering..."); |
Pierre-Clément Tosi | ce0b36d | 2024-01-26 10:50:05 +0000 | [diff] [blame] | 1195 | fdt.clone_from(backup_fdt)?; |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1196 | // A successful restoration is considered success because an invalid debug policy |
| 1197 | // shouldn't DOS the pvmfw |
Pierre-Clément Tosi | a50167b | 2023-05-02 13:19:29 +0000 | [diff] [blame] | 1198 | Ok(false) |
| 1199 | } else { |
| 1200 | Ok(true) |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1201 | } |
Jiyong Park | c23426b | 2023-04-10 17:32:27 +0900 | [diff] [blame] | 1202 | } |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 1203 | |
Pierre-Clément Tosi | 1fbc2e9 | 2023-05-02 17:28:17 +0000 | [diff] [blame] | 1204 | fn has_common_debug_policy(fdt: &Fdt, debug_feature_name: &CStr) -> libfdt::Result<bool> { |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 1205 | if let Some(node) = fdt.node(cstr!("/avf/guest/common"))? { |
| 1206 | if let Some(value) = node.getprop_u32(debug_feature_name)? { |
| 1207 | return Ok(value == 1); |
| 1208 | } |
| 1209 | } |
| 1210 | Ok(false) // if the policy doesn't exist or not 1, don't enable the debug feature |
| 1211 | } |
| 1212 | |
| 1213 | fn filter_out_dangerous_bootargs(fdt: &mut Fdt, bootargs: &CStr) -> libfdt::Result<()> { |
Pierre-Clément Tosi | 1fbc2e9 | 2023-05-02 17:28:17 +0000 | [diff] [blame] | 1214 | let has_crashkernel = has_common_debug_policy(fdt, cstr!("ramdump"))?; |
| 1215 | let has_console = has_common_debug_policy(fdt, cstr!("log"))?; |
Jiyong Park | c5d2ef2 | 2023-04-11 01:23:46 +0900 | [diff] [blame] | 1216 | |
| 1217 | let accepted: &[(&str, Box<dyn Fn(Option<&str>) -> bool>)] = &[ |
| 1218 | ("panic", Box::new(|v| if let Some(v) = v { v == "=-1" } else { false })), |
| 1219 | ("crashkernel", Box::new(|_| has_crashkernel)), |
| 1220 | ("console", Box::new(|_| has_console)), |
| 1221 | ]; |
| 1222 | |
| 1223 | // parse and filter out unwanted |
| 1224 | let mut filtered = Vec::new(); |
| 1225 | for arg in BootArgsIterator::new(bootargs).map_err(|e| { |
| 1226 | info!("Invalid bootarg: {e}"); |
| 1227 | FdtError::BadValue |
| 1228 | })? { |
| 1229 | match accepted.iter().find(|&t| t.0 == arg.name()) { |
| 1230 | Some((_, pred)) if pred(arg.value()) => filtered.push(arg), |
| 1231 | _ => debug!("Rejected bootarg {}", arg.as_ref()), |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | // flatten into a new C-string |
| 1236 | let mut new_bootargs = Vec::new(); |
| 1237 | for (i, arg) in filtered.iter().enumerate() { |
| 1238 | if i != 0 { |
| 1239 | new_bootargs.push(b' '); // separator |
| 1240 | } |
| 1241 | new_bootargs.extend_from_slice(arg.as_ref().as_bytes()); |
| 1242 | } |
| 1243 | new_bootargs.push(b'\0'); |
| 1244 | |
| 1245 | let mut node = fdt.chosen_mut()?.ok_or(FdtError::NotFound)?; |
| 1246 | node.setprop(cstr!("bootargs"), new_bootargs.as_slice()) |
| 1247 | } |