David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [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 | //! Wrapper around libfdt library. Provides parsing/generating functionality |
| 16 | //! to a bare-metal environment. |
| 17 | |
| 18 | #![no_std] |
| 19 | |
Andrew Walbran | 55ad01b | 2022-12-05 17:00:40 +0000 | [diff] [blame] | 20 | mod iterators; |
| 21 | |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 22 | pub use iterators::{AddressRange, CellIterator, MemRegIterator, RangesIterator, Reg, RegIterator}; |
Andrew Walbran | 55ad01b | 2022-12-05 17:00:40 +0000 | [diff] [blame] | 23 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 24 | use core::ffi::{c_int, c_void, CStr}; |
| 25 | use core::fmt; |
| 26 | use core::mem; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 27 | use core::result; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 28 | |
| 29 | /// Error type corresponding to libfdt error codes. |
| 30 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 31 | pub enum FdtError { |
| 32 | /// FDT_ERR_NOTFOUND |
| 33 | NotFound, |
| 34 | /// FDT_ERR_EXISTS |
| 35 | Exists, |
| 36 | /// FDT_ERR_NOSPACE |
| 37 | NoSpace, |
| 38 | /// FDT_ERR_BADOFFSET |
| 39 | BadOffset, |
| 40 | /// FDT_ERR_BADPATH |
| 41 | BadPath, |
| 42 | /// FDT_ERR_BADPHANDLE |
| 43 | BadPhandle, |
| 44 | /// FDT_ERR_BADSTATE |
| 45 | BadState, |
| 46 | /// FDT_ERR_TRUNCATED |
| 47 | Truncated, |
| 48 | /// FDT_ERR_BADMAGIC |
| 49 | BadMagic, |
| 50 | /// FDT_ERR_BADVERSION |
| 51 | BadVersion, |
| 52 | /// FDT_ERR_BADSTRUCTURE |
| 53 | BadStructure, |
| 54 | /// FDT_ERR_BADLAYOUT |
| 55 | BadLayout, |
| 56 | /// FDT_ERR_INTERNAL |
| 57 | Internal, |
| 58 | /// FDT_ERR_BADNCELLS |
| 59 | BadNCells, |
| 60 | /// FDT_ERR_BADVALUE |
| 61 | BadValue, |
| 62 | /// FDT_ERR_BADOVERLAY |
| 63 | BadOverlay, |
| 64 | /// FDT_ERR_NOPHANDLES |
| 65 | NoPhandles, |
| 66 | /// FDT_ERR_BADFLAGS |
| 67 | BadFlags, |
| 68 | /// FDT_ERR_ALIGNMENT |
| 69 | Alignment, |
| 70 | /// Unexpected error code |
| 71 | Unknown(i32), |
| 72 | } |
| 73 | |
| 74 | impl fmt::Display for FdtError { |
| 75 | /// Prints error messages from libfdt.h documentation. |
| 76 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 77 | match self { |
| 78 | Self::NotFound => write!(f, "The requested node or property does not exist"), |
| 79 | Self::Exists => write!(f, "Attempted to create an existing node or property"), |
| 80 | Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"), |
| 81 | Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"), |
| 82 | Self::BadPath => write!(f, "Badly formatted path"), |
| 83 | Self::BadPhandle => write!(f, "Invalid phandle length or value"), |
| 84 | Self::BadState => write!(f, "Received incomplete device tree"), |
| 85 | Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"), |
| 86 | Self::BadMagic => write!(f, "Device tree header missing its magic number"), |
| 87 | Self::BadVersion => write!(f, "Device tree has a version which can't be handled"), |
| 88 | Self::BadStructure => write!(f, "Device tree has a corrupt structure block"), |
| 89 | Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"), |
| 90 | Self::Internal => write!(f, "libfdt has failed an internal assertion"), |
| 91 | Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"), |
| 92 | Self::BadValue => write!(f, "Unexpected property value"), |
| 93 | Self::BadOverlay => write!(f, "Overlay cannot be applied"), |
| 94 | Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"), |
| 95 | Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"), |
| 96 | Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"), |
| 97 | Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"), |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Result type with FdtError enum. |
| 103 | pub type Result<T> = result::Result<T, FdtError>; |
| 104 | |
| 105 | fn fdt_err(val: c_int) -> Result<c_int> { |
| 106 | if val >= 0 { |
| 107 | Ok(val) |
| 108 | } else { |
| 109 | Err(match -val as _ { |
| 110 | libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound, |
| 111 | libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists, |
| 112 | libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace, |
| 113 | libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset, |
| 114 | libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath, |
| 115 | libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle, |
| 116 | libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState, |
| 117 | libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated, |
| 118 | libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic, |
| 119 | libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion, |
| 120 | libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure, |
| 121 | libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout, |
| 122 | libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal, |
| 123 | libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells, |
| 124 | libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue, |
| 125 | libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay, |
| 126 | libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles, |
| 127 | libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags, |
| 128 | libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment, |
| 129 | _ => FdtError::Unknown(val), |
| 130 | }) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn fdt_err_expect_zero(val: c_int) -> Result<()> { |
| 135 | match fdt_err(val)? { |
| 136 | 0 => Ok(()), |
| 137 | _ => Err(FdtError::Unknown(val)), |
| 138 | } |
| 139 | } |
| 140 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 141 | fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> { |
| 142 | match fdt_err(val) { |
| 143 | Ok(val) => Ok(Some(val)), |
| 144 | Err(FdtError::NotFound) => Ok(None), |
| 145 | Err(e) => Err(e), |
| 146 | } |
| 147 | } |
| 148 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 149 | /// Value of a #address-cells property. |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 150 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 151 | enum AddrCells { |
| 152 | Single = 1, |
| 153 | Double = 2, |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 154 | Triple = 3, |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 155 | } |
| 156 | |
| 157 | impl TryFrom<c_int> for AddrCells { |
| 158 | type Error = FdtError; |
| 159 | |
| 160 | fn try_from(res: c_int) -> Result<Self> { |
| 161 | match fdt_err(res)? { |
| 162 | x if x == Self::Single as c_int => Ok(Self::Single), |
| 163 | x if x == Self::Double as c_int => Ok(Self::Double), |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 164 | x if x == Self::Triple as c_int => Ok(Self::Triple), |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 165 | _ => Err(FdtError::BadNCells), |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /// Value of a #size-cells property. |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 171 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 172 | enum SizeCells { |
| 173 | None = 0, |
| 174 | Single = 1, |
| 175 | Double = 2, |
| 176 | } |
| 177 | |
| 178 | impl TryFrom<c_int> for SizeCells { |
| 179 | type Error = FdtError; |
| 180 | |
| 181 | fn try_from(res: c_int) -> Result<Self> { |
| 182 | match fdt_err(res)? { |
| 183 | x if x == Self::None as c_int => Ok(Self::None), |
| 184 | x if x == Self::Single as c_int => Ok(Self::Single), |
| 185 | x if x == Self::Double as c_int => Ok(Self::Double), |
| 186 | _ => Err(FdtError::BadNCells), |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 191 | /// DT node. |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 192 | #[derive(Clone, Copy)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 193 | pub struct FdtNode<'a> { |
| 194 | fdt: &'a Fdt, |
| 195 | offset: c_int, |
| 196 | } |
| 197 | |
| 198 | impl<'a> FdtNode<'a> { |
| 199 | /// Find parent node. |
| 200 | pub fn parent(&self) -> Result<Self> { |
| 201 | // SAFETY - Accesses (read-only) are constrained to the DT totalsize. |
| 202 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 203 | |
| 204 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 205 | } |
| 206 | |
| 207 | /// Retrieve the standard (deprecated) device_type <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 208 | pub fn device_type(&self) -> Result<Option<&CStr>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 209 | self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap()) |
| 210 | } |
| 211 | |
| 212 | /// Retrieve the standard reg <prop-encoded-array> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 213 | pub fn reg(&self) -> Result<Option<RegIterator<'a>>> { |
| 214 | let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap(); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 215 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 216 | if let Some(cells) = self.getprop_cells(reg)? { |
| 217 | let parent = self.parent()?; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 218 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 219 | let addr_cells = parent.address_cells()?; |
| 220 | let size_cells = parent.size_cells()?; |
| 221 | |
| 222 | Ok(Some(RegIterator::new(cells, addr_cells, size_cells))) |
| 223 | } else { |
| 224 | Ok(None) |
| 225 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 226 | } |
| 227 | |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 228 | /// Retrieves the standard ranges property. |
| 229 | pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> { |
| 230 | let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap(); |
| 231 | if let Some(cells) = self.getprop_cells(ranges)? { |
| 232 | let parent = self.parent()?; |
| 233 | let addr_cells = self.address_cells()?; |
| 234 | let parent_addr_cells = parent.address_cells()?; |
| 235 | let size_cells = self.size_cells()?; |
| 236 | Ok(Some(RangesIterator::<A, P, S>::new( |
| 237 | cells, |
| 238 | addr_cells, |
| 239 | parent_addr_cells, |
| 240 | size_cells, |
| 241 | ))) |
| 242 | } else { |
| 243 | Ok(None) |
| 244 | } |
| 245 | } |
| 246 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 247 | /// Retrieve the value of a given <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 248 | pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> { |
| 249 | let value = if let Some(bytes) = self.getprop(name)? { |
| 250 | Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?) |
| 251 | } else { |
| 252 | None |
| 253 | }; |
| 254 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 255 | } |
| 256 | |
| 257 | /// Retrieve the value of a given property as an array of cells. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 258 | pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> { |
| 259 | if let Some(cells) = self.getprop(name)? { |
| 260 | Ok(Some(CellIterator::new(cells))) |
| 261 | } else { |
| 262 | Ok(None) |
| 263 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 264 | } |
| 265 | |
| 266 | /// Retrieve the value of a given <u32> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 267 | pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> { |
| 268 | let value = if let Some(bytes) = self.getprop(name)? { |
| 269 | Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 270 | } else { |
| 271 | None |
| 272 | }; |
| 273 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 274 | } |
| 275 | |
| 276 | /// Retrieve the value of a given <u64> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 277 | pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> { |
| 278 | let value = if let Some(bytes) = self.getprop(name)? { |
| 279 | Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 280 | } else { |
| 281 | None |
| 282 | }; |
| 283 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 284 | } |
| 285 | |
| 286 | /// Retrieve the value of a given property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 287 | pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 288 | let mut len: i32 = 0; |
| 289 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) and the |
| 290 | // function respects the passed number of characters. |
| 291 | let prop = unsafe { |
| 292 | libfdt_bindgen::fdt_getprop_namelen( |
| 293 | self.fdt.as_ptr(), |
| 294 | self.offset, |
| 295 | name.as_ptr(), |
| 296 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 297 | name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?, |
| 298 | &mut len as *mut i32, |
| 299 | ) |
| 300 | } as *const u8; |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 301 | |
| 302 | let Some(len) = fdt_err_or_option(len)? else { |
| 303 | return Ok(None); // Property was not found. |
| 304 | }; |
| 305 | let len = usize::try_from(len).map_err(|_| FdtError::Internal)?; |
| 306 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 307 | if prop.is_null() { |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 308 | // We expected an error code in len but still received a valid value?! |
| 309 | return Err(FdtError::Internal); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 310 | } |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 311 | |
| 312 | let offset = |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 313 | (prop as usize).checked_sub(self.fdt.as_ptr() as usize).ok_or(FdtError::Internal)?; |
| 314 | |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 315 | Ok(Some(self.fdt.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)?)) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 316 | } |
| 317 | |
| 318 | /// Get reference to the containing device tree. |
| 319 | pub fn fdt(&self) -> &Fdt { |
| 320 | self.fdt |
| 321 | } |
| 322 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 323 | fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
| 324 | // SAFETY - Accesses (read-only) are constrained to the DT totalsize. |
| 325 | let ret = unsafe { |
| 326 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 327 | self.fdt.as_ptr(), |
| 328 | self.offset, |
| 329 | compatible.as_ptr(), |
| 330 | ) |
| 331 | }; |
| 332 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 333 | Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset })) |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 334 | } |
| 335 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 336 | fn address_cells(&self) -> Result<AddrCells> { |
| 337 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor). |
| 338 | unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) } |
| 339 | .try_into() |
| 340 | .map_err(|_| FdtError::Internal) |
| 341 | } |
| 342 | |
| 343 | fn size_cells(&self) -> Result<SizeCells> { |
| 344 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor). |
| 345 | unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) } |
| 346 | .try_into() |
| 347 | .map_err(|_| FdtError::Internal) |
| 348 | } |
| 349 | } |
| 350 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 351 | /// Mutable FDT node. |
| 352 | pub struct FdtNodeMut<'a> { |
| 353 | fdt: &'a mut Fdt, |
| 354 | offset: c_int, |
| 355 | } |
| 356 | |
| 357 | impl<'a> FdtNodeMut<'a> { |
| 358 | /// Append a property name-value (possibly empty) pair to the given node. |
| 359 | pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> { |
| 360 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor). |
| 361 | let ret = unsafe { |
| 362 | libfdt_bindgen::fdt_appendprop( |
| 363 | self.fdt.as_mut_ptr(), |
| 364 | self.offset, |
| 365 | name.as_ptr(), |
| 366 | value.as_ref().as_ptr().cast::<c_void>(), |
| 367 | value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?, |
| 368 | ) |
| 369 | }; |
| 370 | |
| 371 | fdt_err_expect_zero(ret) |
| 372 | } |
| 373 | |
| 374 | /// Append a (address, size) pair property to the given node. |
| 375 | pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> { |
| 376 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor). |
| 377 | let ret = unsafe { |
| 378 | libfdt_bindgen::fdt_appendprop_addrrange( |
| 379 | self.fdt.as_mut_ptr(), |
| 380 | self.parent()?.offset, |
| 381 | self.offset, |
| 382 | name.as_ptr(), |
| 383 | addr, |
| 384 | size, |
| 385 | ) |
| 386 | }; |
| 387 | |
| 388 | fdt_err_expect_zero(ret) |
| 389 | } |
| 390 | |
Jaewan Kim | ba8929b | 2023-01-13 11:13:29 +0900 | [diff] [blame] | 391 | /// Create or change a property name-value pair to the given node. |
| 392 | pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> { |
| 393 | // SAFETY - New value size is constrained to the DT totalsize |
| 394 | // (validated by underlying libfdt). |
| 395 | let ret = unsafe { |
| 396 | libfdt_bindgen::fdt_setprop( |
| 397 | self.fdt.as_mut_ptr(), |
| 398 | self.offset, |
| 399 | name.as_ptr(), |
| 400 | value.as_ptr().cast::<c_void>(), |
| 401 | value.len().try_into().map_err(|_| FdtError::BadValue)?, |
| 402 | ) |
| 403 | }; |
| 404 | |
| 405 | fdt_err_expect_zero(ret) |
| 406 | } |
| 407 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 408 | /// Get reference to the containing device tree. |
| 409 | pub fn fdt(&mut self) -> &mut Fdt { |
| 410 | self.fdt |
| 411 | } |
| 412 | |
| 413 | /// Add a new subnode to the given node and return it as a FdtNodeMut on success. |
| 414 | pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> { |
| 415 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor). |
| 416 | let ret = unsafe { |
| 417 | libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 418 | }; |
| 419 | |
| 420 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 421 | } |
| 422 | |
| 423 | fn parent(&'a self) -> Result<FdtNode<'a>> { |
| 424 | // SAFETY - Accesses (read-only) are constrained to the DT totalsize. |
| 425 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 426 | |
| 427 | Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? }) |
| 428 | } |
| 429 | } |
| 430 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 431 | /// Iterator over nodes sharing a same compatible string. |
| 432 | pub struct CompatibleIterator<'a> { |
| 433 | node: FdtNode<'a>, |
| 434 | compatible: &'a CStr, |
| 435 | } |
| 436 | |
| 437 | impl<'a> CompatibleIterator<'a> { |
| 438 | fn new(fdt: &'a Fdt, compatible: &'a CStr) -> Result<Self> { |
| 439 | let node = fdt.root()?; |
| 440 | Ok(Self { node, compatible }) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | impl<'a> Iterator for CompatibleIterator<'a> { |
| 445 | type Item = FdtNode<'a>; |
| 446 | |
| 447 | fn next(&mut self) -> Option<Self::Item> { |
| 448 | let next = self.node.next_compatible(self.compatible).ok()?; |
| 449 | |
| 450 | if let Some(node) = next { |
| 451 | self.node = node; |
| 452 | } |
| 453 | |
| 454 | next |
| 455 | } |
| 456 | } |
| 457 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 458 | /// Wrapper around low-level libfdt functions. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 459 | #[repr(transparent)] |
| 460 | pub struct Fdt { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 461 | buffer: [u8], |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 462 | } |
| 463 | |
| 464 | impl Fdt { |
| 465 | /// Wraps a slice containing a Flattened Device Tree. |
| 466 | /// |
| 467 | /// Fails if the FDT does not pass validation. |
| 468 | pub fn from_slice(fdt: &[u8]) -> Result<&Self> { |
| 469 | // SAFETY - The FDT will be validated before it is returned. |
| 470 | let fdt = unsafe { Self::unchecked_from_slice(fdt) }; |
| 471 | fdt.check_full()?; |
| 472 | Ok(fdt) |
| 473 | } |
| 474 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 475 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 476 | /// |
| 477 | /// Fails if the FDT does not pass validation. |
| 478 | pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> { |
| 479 | // SAFETY - The FDT will be validated before it is returned. |
| 480 | let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) }; |
| 481 | fdt.check_full()?; |
| 482 | Ok(fdt) |
| 483 | } |
| 484 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 485 | /// Wraps a slice containing a Flattened Device Tree. |
| 486 | /// |
| 487 | /// # Safety |
| 488 | /// |
| 489 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 490 | pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self { |
| 491 | mem::transmute::<&[u8], &Self>(fdt) |
| 492 | } |
| 493 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 494 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 495 | /// |
| 496 | /// # Safety |
| 497 | /// |
| 498 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 499 | pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self { |
| 500 | mem::transmute::<&mut [u8], &mut Self>(fdt) |
| 501 | } |
| 502 | |
| 503 | /// Make the whole slice containing the DT available to libfdt. |
| 504 | pub fn unpack(&mut self) -> Result<()> { |
| 505 | // SAFETY - "Opens" the DT in-place (supported use-case) by updating its header and |
| 506 | // internal structures to make use of the whole self.fdt slice but performs no accesses |
| 507 | // outside of it and leaves the DT in a state that will be detected by other functions. |
| 508 | let ret = unsafe { |
| 509 | libfdt_bindgen::fdt_open_into( |
| 510 | self.as_ptr(), |
| 511 | self.as_mut_ptr(), |
| 512 | self.capacity().try_into().map_err(|_| FdtError::Internal)?, |
| 513 | ) |
| 514 | }; |
| 515 | fdt_err_expect_zero(ret) |
| 516 | } |
| 517 | |
| 518 | /// Pack the DT to take a minimum amount of memory. |
| 519 | /// |
| 520 | /// Doesn't shrink the underlying memory slice. |
| 521 | pub fn pack(&mut self) -> Result<()> { |
| 522 | // SAFETY - "Closes" the DT in-place by updating its header and relocating its structs. |
| 523 | let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) }; |
| 524 | fdt_err_expect_zero(ret) |
| 525 | } |
| 526 | |
Pierre-Clément Tosi | 90e1935 | 2022-11-21 17:11:48 +0000 | [diff] [blame] | 527 | /// Applies a DT overlay on the base DT. |
| 528 | /// |
| 529 | /// # Safety |
| 530 | /// |
| 531 | /// On failure, the library corrupts the DT and overlay so both must be discarded. |
| 532 | pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> { |
| 533 | fdt_err_expect_zero(libfdt_bindgen::fdt_overlay_apply( |
| 534 | self.as_mut_ptr(), |
| 535 | overlay.as_mut_ptr(), |
| 536 | ))?; |
| 537 | Ok(self) |
| 538 | } |
| 539 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 540 | /// Return an iterator of memory banks specified the "/memory" node. |
| 541 | /// |
| 542 | /// NOTE: This does not support individual "/memory@XXXX" banks. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 543 | pub fn memory(&self) -> Result<Option<MemRegIterator>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 544 | let memory = CStr::from_bytes_with_nul(b"/memory\0").unwrap(); |
| 545 | let device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap(); |
| 546 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 547 | if let Some(node) = self.node(memory)? { |
| 548 | if node.device_type()? != Some(device_type) { |
| 549 | return Err(FdtError::BadValue); |
| 550 | } |
| 551 | let reg = node.reg()?.ok_or(FdtError::BadValue)?; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 552 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 553 | Ok(Some(MemRegIterator::new(reg))) |
| 554 | } else { |
| 555 | Ok(None) |
| 556 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 557 | } |
| 558 | |
| 559 | /// Retrieve the standard /chosen node. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 560 | pub fn chosen(&self) -> Result<Option<FdtNode>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 561 | self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap()) |
| 562 | } |
| 563 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 564 | /// Get the root node of the tree. |
| 565 | pub fn root(&self) -> Result<FdtNode> { |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 566 | self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal) |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 567 | } |
| 568 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 569 | /// Find a tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 570 | pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> { |
| 571 | Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset })) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 572 | } |
| 573 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 574 | /// Iterate over nodes with a given compatible string. |
| 575 | pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> { |
| 576 | CompatibleIterator::new(self, compatible) |
| 577 | } |
| 578 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 579 | /// Get the mutable root node of the tree. |
| 580 | pub fn root_mut(&mut self) -> Result<FdtNodeMut> { |
| 581 | self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal) |
| 582 | } |
| 583 | |
| 584 | /// Find a mutable tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 585 | pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> { |
| 586 | Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset })) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 587 | } |
| 588 | |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 589 | /// Return the device tree as a slice (may be smaller than the containing buffer). |
| 590 | pub fn as_slice(&self) -> &[u8] { |
| 591 | &self.buffer[..self.totalsize()] |
| 592 | } |
| 593 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 594 | fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 595 | let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?; |
| 596 | // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) and the |
| 597 | // function respects the passed number of characters. |
| 598 | let ret = unsafe { |
| 599 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 600 | libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len) |
| 601 | }; |
| 602 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 603 | fdt_err_or_option(ret) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 604 | } |
| 605 | |
| 606 | fn check_full(&self) -> Result<()> { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 607 | let len = self.buffer.len(); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 608 | // SAFETY - Only performs read accesses within the limits of the slice. If successful, this |
| 609 | // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t. |
| 610 | // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds |
| 611 | // checking. The library doesn't maintain an internal state (such as pointers) between |
| 612 | // calls as it expects the client code to keep track of the objects (DT, nodes, ...). |
| 613 | let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) }; |
| 614 | fdt_err_expect_zero(ret) |
| 615 | } |
| 616 | |
Pierre-Clément Tosi | 8036b4f | 2023-02-17 10:31:31 +0000 | [diff] [blame^] | 617 | /// Return a shared pointer to the device tree. |
| 618 | pub fn as_ptr(&self) -> *const c_void { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 619 | self as *const _ as *const c_void |
| 620 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 621 | |
| 622 | fn as_mut_ptr(&mut self) -> *mut c_void { |
| 623 | self as *mut _ as *mut c_void |
| 624 | } |
| 625 | |
| 626 | fn capacity(&self) -> usize { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 627 | self.buffer.len() |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 628 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 629 | |
| 630 | fn header(&self) -> &libfdt_bindgen::fdt_header { |
| 631 | // SAFETY - A valid FDT (verified by constructor) must contain a valid fdt_header. |
| 632 | unsafe { &*(&self as *const _ as *const libfdt_bindgen::fdt_header) } |
| 633 | } |
| 634 | |
| 635 | fn totalsize(&self) -> usize { |
| 636 | u32::from_be(self.header().totalsize) as usize |
| 637 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 638 | } |