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 | |
Jaewan Kim | fe06c85 | 2023-10-05 23:40:06 +0900 | [diff] [blame] | 22 | pub use iterators::{ |
Jaewan Kim | c9e1411 | 2023-12-04 17:05:27 +0900 | [diff] [blame^] | 23 | AddressRange, CellIterator, CompatibleIterator, DescendantsIterator, MemRegIterator, |
| 24 | PropertyIterator, RangesIterator, Reg, RegIterator, SubnodeIterator, |
Jaewan Kim | fe06c85 | 2023-10-05 23:40:06 +0900 | [diff] [blame] | 25 | }; |
Andrew Walbran | 55ad01b | 2022-12-05 17:00:40 +0000 | [diff] [blame] | 26 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 27 | use core::cmp::max; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 28 | use core::ffi::{c_int, c_void, CStr}; |
| 29 | use core::fmt; |
| 30 | use core::mem; |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 31 | use core::ops::Range; |
Jaewan Kim | 5b05777 | 2023-10-19 01:02:17 +0900 | [diff] [blame] | 32 | use core::ptr; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 33 | use core::result; |
Pierre-Clément Tosi | 1bf532b | 2023-11-13 11:06:20 +0000 | [diff] [blame] | 34 | use cstr::cstr; |
Pierre-Clément Tosi | c27c427 | 2023-05-19 15:46:26 +0000 | [diff] [blame] | 35 | use zerocopy::AsBytes as _; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 36 | |
| 37 | /// Error type corresponding to libfdt error codes. |
| 38 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 39 | pub enum FdtError { |
| 40 | /// FDT_ERR_NOTFOUND |
| 41 | NotFound, |
| 42 | /// FDT_ERR_EXISTS |
| 43 | Exists, |
| 44 | /// FDT_ERR_NOSPACE |
| 45 | NoSpace, |
| 46 | /// FDT_ERR_BADOFFSET |
| 47 | BadOffset, |
| 48 | /// FDT_ERR_BADPATH |
| 49 | BadPath, |
| 50 | /// FDT_ERR_BADPHANDLE |
| 51 | BadPhandle, |
| 52 | /// FDT_ERR_BADSTATE |
| 53 | BadState, |
| 54 | /// FDT_ERR_TRUNCATED |
| 55 | Truncated, |
| 56 | /// FDT_ERR_BADMAGIC |
| 57 | BadMagic, |
| 58 | /// FDT_ERR_BADVERSION |
| 59 | BadVersion, |
| 60 | /// FDT_ERR_BADSTRUCTURE |
| 61 | BadStructure, |
| 62 | /// FDT_ERR_BADLAYOUT |
| 63 | BadLayout, |
| 64 | /// FDT_ERR_INTERNAL |
| 65 | Internal, |
| 66 | /// FDT_ERR_BADNCELLS |
| 67 | BadNCells, |
| 68 | /// FDT_ERR_BADVALUE |
| 69 | BadValue, |
| 70 | /// FDT_ERR_BADOVERLAY |
| 71 | BadOverlay, |
| 72 | /// FDT_ERR_NOPHANDLES |
| 73 | NoPhandles, |
| 74 | /// FDT_ERR_BADFLAGS |
| 75 | BadFlags, |
| 76 | /// FDT_ERR_ALIGNMENT |
| 77 | Alignment, |
| 78 | /// Unexpected error code |
| 79 | Unknown(i32), |
| 80 | } |
| 81 | |
| 82 | impl fmt::Display for FdtError { |
| 83 | /// Prints error messages from libfdt.h documentation. |
| 84 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 85 | match self { |
| 86 | Self::NotFound => write!(f, "The requested node or property does not exist"), |
| 87 | Self::Exists => write!(f, "Attempted to create an existing node or property"), |
| 88 | Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"), |
| 89 | Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"), |
| 90 | Self::BadPath => write!(f, "Badly formatted path"), |
| 91 | Self::BadPhandle => write!(f, "Invalid phandle length or value"), |
| 92 | Self::BadState => write!(f, "Received incomplete device tree"), |
| 93 | Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"), |
| 94 | Self::BadMagic => write!(f, "Device tree header missing its magic number"), |
| 95 | Self::BadVersion => write!(f, "Device tree has a version which can't be handled"), |
| 96 | Self::BadStructure => write!(f, "Device tree has a corrupt structure block"), |
| 97 | Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"), |
| 98 | Self::Internal => write!(f, "libfdt has failed an internal assertion"), |
| 99 | Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"), |
| 100 | Self::BadValue => write!(f, "Unexpected property value"), |
| 101 | Self::BadOverlay => write!(f, "Overlay cannot be applied"), |
| 102 | Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"), |
| 103 | Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"), |
| 104 | Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"), |
| 105 | Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"), |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// Result type with FdtError enum. |
| 111 | pub type Result<T> = result::Result<T, FdtError>; |
| 112 | |
| 113 | fn fdt_err(val: c_int) -> Result<c_int> { |
| 114 | if val >= 0 { |
| 115 | Ok(val) |
| 116 | } else { |
| 117 | Err(match -val as _ { |
| 118 | libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound, |
| 119 | libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists, |
| 120 | libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace, |
| 121 | libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset, |
| 122 | libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath, |
| 123 | libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle, |
| 124 | libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState, |
| 125 | libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated, |
| 126 | libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic, |
| 127 | libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion, |
| 128 | libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure, |
| 129 | libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout, |
| 130 | libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal, |
| 131 | libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells, |
| 132 | libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue, |
| 133 | libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay, |
| 134 | libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles, |
| 135 | libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags, |
| 136 | libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment, |
| 137 | _ => FdtError::Unknown(val), |
| 138 | }) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn fdt_err_expect_zero(val: c_int) -> Result<()> { |
| 143 | match fdt_err(val)? { |
| 144 | 0 => Ok(()), |
| 145 | _ => Err(FdtError::Unknown(val)), |
| 146 | } |
| 147 | } |
| 148 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 149 | fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> { |
| 150 | match fdt_err(val) { |
| 151 | Ok(val) => Ok(Some(val)), |
| 152 | Err(FdtError::NotFound) => Ok(None), |
| 153 | Err(e) => Err(e), |
| 154 | } |
| 155 | } |
| 156 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 157 | /// Value of a #address-cells property. |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 158 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 159 | enum AddrCells { |
| 160 | Single = 1, |
| 161 | Double = 2, |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 162 | Triple = 3, |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 163 | } |
| 164 | |
| 165 | impl TryFrom<c_int> for AddrCells { |
| 166 | type Error = FdtError; |
| 167 | |
| 168 | fn try_from(res: c_int) -> Result<Self> { |
| 169 | match fdt_err(res)? { |
| 170 | x if x == Self::Single as c_int => Ok(Self::Single), |
| 171 | x if x == Self::Double as c_int => Ok(Self::Double), |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 172 | x if x == Self::Triple as c_int => Ok(Self::Triple), |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 173 | _ => Err(FdtError::BadNCells), |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// Value of a #size-cells property. |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 179 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 180 | enum SizeCells { |
| 181 | None = 0, |
| 182 | Single = 1, |
| 183 | Double = 2, |
| 184 | } |
| 185 | |
| 186 | impl TryFrom<c_int> for SizeCells { |
| 187 | type Error = FdtError; |
| 188 | |
| 189 | fn try_from(res: c_int) -> Result<Self> { |
| 190 | match fdt_err(res)? { |
| 191 | x if x == Self::None as c_int => Ok(Self::None), |
| 192 | x if x == Self::Single as c_int => Ok(Self::Single), |
| 193 | x if x == Self::Double as c_int => Ok(Self::Double), |
| 194 | _ => Err(FdtError::BadNCells), |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | |
Jaewan Kim | 72d1090 | 2023-10-12 21:59:26 +0900 | [diff] [blame] | 199 | /// DT property wrapper to abstract endianess changes |
| 200 | #[repr(transparent)] |
| 201 | #[derive(Debug)] |
| 202 | struct FdtPropertyStruct(libfdt_bindgen::fdt_property); |
| 203 | |
| 204 | impl FdtPropertyStruct { |
| 205 | fn from_offset(fdt: &Fdt, offset: c_int) -> Result<&Self> { |
| 206 | let mut len = 0; |
| 207 | let prop = |
| 208 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 209 | unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt.as_ptr(), offset, &mut len) }; |
| 210 | if prop.is_null() { |
| 211 | fdt_err(len)?; |
| 212 | return Err(FdtError::Internal); // shouldn't happen. |
| 213 | } |
| 214 | // SAFETY: prop is only returned when it points to valid libfdt_bindgen. |
| 215 | Ok(unsafe { &*prop.cast::<FdtPropertyStruct>() }) |
| 216 | } |
| 217 | |
| 218 | fn name_offset(&self) -> c_int { |
| 219 | u32::from_be(self.0.nameoff).try_into().unwrap() |
| 220 | } |
| 221 | |
| 222 | fn data_len(&self) -> usize { |
| 223 | u32::from_be(self.0.len).try_into().unwrap() |
| 224 | } |
| 225 | |
| 226 | fn data_ptr(&self) -> *const c_void { |
| 227 | self.0.data.as_ptr().cast::<_>() |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// DT property. |
| 232 | #[derive(Clone, Copy, Debug)] |
| 233 | pub struct FdtProperty<'a> { |
| 234 | fdt: &'a Fdt, |
| 235 | offset: c_int, |
| 236 | property: &'a FdtPropertyStruct, |
| 237 | } |
| 238 | |
| 239 | impl<'a> FdtProperty<'a> { |
| 240 | fn new(fdt: &'a Fdt, offset: c_int) -> Result<Self> { |
| 241 | let property = FdtPropertyStruct::from_offset(fdt, offset)?; |
| 242 | Ok(Self { fdt, offset, property }) |
| 243 | } |
| 244 | |
| 245 | /// Returns the property name |
| 246 | pub fn name(&self) -> Result<&'a CStr> { |
| 247 | self.fdt.string(self.property.name_offset()) |
| 248 | } |
| 249 | |
| 250 | /// Returns the property value |
| 251 | pub fn value(&self) -> Result<&'a [u8]> { |
| 252 | self.fdt.get_from_ptr(self.property.data_ptr(), self.property.data_len()) |
| 253 | } |
| 254 | |
| 255 | fn next_property(&self) -> Result<Option<Self>> { |
| 256 | let ret = |
| 257 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 258 | unsafe { libfdt_bindgen::fdt_next_property_offset(self.fdt.as_ptr(), self.offset) }; |
| 259 | |
| 260 | fdt_err_or_option(ret)?.map(|offset| Self::new(self.fdt, offset)).transpose() |
| 261 | } |
| 262 | } |
| 263 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 264 | /// DT node. |
Alice Wang | 9d4df70 | 2023-05-25 14:14:12 +0000 | [diff] [blame] | 265 | #[derive(Clone, Copy, Debug)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 266 | pub struct FdtNode<'a> { |
| 267 | fdt: &'a Fdt, |
| 268 | offset: c_int, |
| 269 | } |
| 270 | |
| 271 | impl<'a> FdtNode<'a> { |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 272 | /// Creates immutable node from a mutable node at the same offset. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 273 | pub fn from_mut(other: &'a FdtNodeMut) -> Self { |
| 274 | FdtNode { fdt: other.fdt, offset: other.offset } |
| 275 | } |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 276 | /// Returns parent node. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 277 | pub fn parent(&self) -> Result<Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 278 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 279 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 280 | |
| 281 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 282 | } |
| 283 | |
Jaewan Kim | 5b05777 | 2023-10-19 01:02:17 +0900 | [diff] [blame] | 284 | /// Returns supernode with depth. Note that root is at depth 0. |
| 285 | pub fn supernode_at_depth(&self, depth: usize) -> Result<Self> { |
| 286 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 287 | let ret = unsafe { |
| 288 | libfdt_bindgen::fdt_supernode_atdepth_offset( |
| 289 | self.fdt.as_ptr(), |
| 290 | self.offset, |
| 291 | depth.try_into().unwrap(), |
| 292 | ptr::null_mut(), |
| 293 | ) |
| 294 | }; |
| 295 | |
| 296 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 297 | } |
| 298 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 299 | /// Returns the standard (deprecated) device_type <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 300 | pub fn device_type(&self) -> Result<Option<&CStr>> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 301 | self.getprop_str(cstr!("device_type")) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 302 | } |
| 303 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 304 | /// Returns the standard reg <prop-encoded-array> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 305 | pub fn reg(&self) -> Result<Option<RegIterator<'a>>> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 306 | let reg = cstr!("reg"); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 307 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 308 | if let Some(cells) = self.getprop_cells(reg)? { |
| 309 | let parent = self.parent()?; |
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 | let addr_cells = parent.address_cells()?; |
| 312 | let size_cells = parent.size_cells()?; |
| 313 | |
| 314 | Ok(Some(RegIterator::new(cells, addr_cells, size_cells))) |
| 315 | } else { |
| 316 | Ok(None) |
| 317 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 318 | } |
| 319 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 320 | /// Returns the standard ranges property. |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 321 | pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 322 | let ranges = cstr!("ranges"); |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 323 | if let Some(cells) = self.getprop_cells(ranges)? { |
| 324 | let parent = self.parent()?; |
| 325 | let addr_cells = self.address_cells()?; |
| 326 | let parent_addr_cells = parent.address_cells()?; |
| 327 | let size_cells = self.size_cells()?; |
| 328 | Ok(Some(RangesIterator::<A, P, S>::new( |
| 329 | cells, |
| 330 | addr_cells, |
| 331 | parent_addr_cells, |
| 332 | size_cells, |
| 333 | ))) |
| 334 | } else { |
| 335 | Ok(None) |
| 336 | } |
| 337 | } |
| 338 | |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 339 | /// Returns the node name. |
| 340 | pub fn name(&self) -> Result<&'a CStr> { |
| 341 | let mut len: c_int = 0; |
| 342 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the |
| 343 | // function returns valid null terminating string and otherwise returned values are dropped. |
| 344 | let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) } |
| 345 | as *const c_void; |
| 346 | let len = usize::try_from(fdt_err(len)?).unwrap(); |
| 347 | let name = self.fdt.get_from_ptr(name, len + 1)?; |
| 348 | CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal) |
| 349 | } |
| 350 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 351 | /// Returns the value of a given <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 352 | pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> { |
| 353 | let value = if let Some(bytes) = self.getprop(name)? { |
| 354 | Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?) |
| 355 | } else { |
| 356 | None |
| 357 | }; |
| 358 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 359 | } |
| 360 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 361 | /// Returns 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] | 362 | pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> { |
| 363 | if let Some(cells) = self.getprop(name)? { |
| 364 | Ok(Some(CellIterator::new(cells))) |
| 365 | } else { |
| 366 | Ok(None) |
| 367 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 368 | } |
| 369 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 370 | /// Returns the value of a given <u32> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 371 | pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> { |
| 372 | let value = if let Some(bytes) = self.getprop(name)? { |
| 373 | Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 374 | } else { |
| 375 | None |
| 376 | }; |
| 377 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 378 | } |
| 379 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 380 | /// Returns the value of a given <u64> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 381 | pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> { |
| 382 | let value = if let Some(bytes) = self.getprop(name)? { |
| 383 | Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 384 | } else { |
| 385 | None |
| 386 | }; |
| 387 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 388 | } |
| 389 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 390 | /// Returns the value of a given property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 391 | pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 392 | if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? { |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 393 | Ok(Some(self.fdt.get_from_ptr(prop, len)?)) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 394 | } else { |
| 395 | Ok(None) // property was not found |
| 396 | } |
| 397 | } |
| 398 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 399 | /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 400 | /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns. |
| 401 | fn getprop_internal( |
| 402 | fdt: &'a Fdt, |
| 403 | offset: c_int, |
| 404 | name: &CStr, |
| 405 | ) -> Result<Option<(*const c_void, usize)>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 406 | let mut len: i32 = 0; |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 407 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 408 | // function respects the passed number of characters. |
| 409 | let prop = unsafe { |
| 410 | libfdt_bindgen::fdt_getprop_namelen( |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 411 | fdt.as_ptr(), |
| 412 | offset, |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 413 | name.as_ptr(), |
| 414 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 415 | name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?, |
| 416 | &mut len as *mut i32, |
| 417 | ) |
| 418 | } as *const u8; |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 419 | |
| 420 | let Some(len) = fdt_err_or_option(len)? else { |
| 421 | return Ok(None); // Property was not found. |
| 422 | }; |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 423 | let len = usize::try_from(len).unwrap(); |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 424 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 425 | if prop.is_null() { |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 426 | // We expected an error code in len but still received a valid value?! |
| 427 | return Err(FdtError::Internal); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 428 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 429 | Ok(Some((prop.cast::<c_void>(), len))) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 430 | } |
| 431 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 432 | /// Returns reference to the containing device tree. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 433 | pub fn fdt(&self) -> &Fdt { |
| 434 | self.fdt |
| 435 | } |
| 436 | |
Alice Wang | 474c0ee | 2023-09-14 12:52:33 +0000 | [diff] [blame] | 437 | /// Returns the compatible node of the given name that is next after this node. |
| 438 | pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 439 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 440 | let ret = unsafe { |
| 441 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 442 | self.fdt.as_ptr(), |
| 443 | self.offset, |
| 444 | compatible.as_ptr(), |
| 445 | ) |
| 446 | }; |
| 447 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 448 | 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] | 449 | } |
| 450 | |
Alice Wang | 474c0ee | 2023-09-14 12:52:33 +0000 | [diff] [blame] | 451 | /// Returns the first range of `reg` in this node. |
| 452 | pub fn first_reg(&self) -> Result<Reg<u64>> { |
| 453 | self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound) |
| 454 | } |
| 455 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 456 | fn address_cells(&self) -> Result<AddrCells> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 457 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 458 | unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) } |
| 459 | .try_into() |
| 460 | .map_err(|_| FdtError::Internal) |
| 461 | } |
| 462 | |
| 463 | fn size_cells(&self) -> Result<SizeCells> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 464 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 465 | unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) } |
| 466 | .try_into() |
| 467 | .map_err(|_| FdtError::Internal) |
| 468 | } |
Jaewan Kim | bc828d7 | 2023-09-19 15:52:08 +0900 | [diff] [blame] | 469 | |
| 470 | /// Returns an iterator of subnodes |
| 471 | pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> { |
| 472 | SubnodeIterator::new(self) |
| 473 | } |
| 474 | |
| 475 | fn first_subnode(&self) -> Result<Option<Self>> { |
| 476 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 477 | let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) }; |
| 478 | |
| 479 | Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset })) |
| 480 | } |
| 481 | |
| 482 | fn next_subnode(&self) -> Result<Option<Self>> { |
| 483 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 484 | let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) }; |
| 485 | |
| 486 | Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset })) |
| 487 | } |
Jaewan Kim | 72d1090 | 2023-10-12 21:59:26 +0900 | [diff] [blame] | 488 | |
Jaewan Kim | c9e1411 | 2023-12-04 17:05:27 +0900 | [diff] [blame^] | 489 | /// Returns an iterator of descendants |
| 490 | pub fn descendants(&'a self) -> DescendantsIterator<'a> { |
| 491 | DescendantsIterator::new(self) |
| 492 | } |
| 493 | |
| 494 | fn next_node(&self, depth: usize) -> Result<Option<(Self, usize)>> { |
| 495 | let mut next_depth: c_int = depth.try_into().unwrap(); |
| 496 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 497 | let ret = unsafe { |
| 498 | libfdt_bindgen::fdt_next_node(self.fdt.as_ptr(), self.offset, &mut next_depth) |
| 499 | }; |
| 500 | let Ok(next_depth) = usize::try_from(next_depth) else { |
| 501 | return Ok(None); |
| 502 | }; |
| 503 | Ok(fdt_err_or_option(ret)?.map(|offset| (FdtNode { fdt: self.fdt, offset }, next_depth))) |
| 504 | } |
| 505 | |
Jaewan Kim | 72d1090 | 2023-10-12 21:59:26 +0900 | [diff] [blame] | 506 | /// Returns an iterator of properties |
| 507 | pub fn properties(&'a self) -> Result<PropertyIterator<'a>> { |
| 508 | PropertyIterator::new(self) |
| 509 | } |
| 510 | |
| 511 | fn first_property(&self) -> Result<Option<FdtProperty<'a>>> { |
| 512 | let ret = |
| 513 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 514 | unsafe { libfdt_bindgen::fdt_first_property_offset(self.fdt.as_ptr(), self.offset) }; |
| 515 | |
| 516 | fdt_err_or_option(ret)?.map(|offset| FdtProperty::new(self.fdt, offset)).transpose() |
| 517 | } |
Jaewan Kim | f34f4b8 | 2023-11-03 19:38:38 +0900 | [diff] [blame] | 518 | |
| 519 | /// Returns the phandle |
| 520 | pub fn get_phandle(&self) -> Result<Option<Phandle>> { |
| 521 | // This rewrites the fdt_get_phandle() because it doesn't return error code. |
| 522 | if let Some(prop) = self.getprop_u32(cstr!("phandle"))? { |
| 523 | Ok(Some(prop.try_into()?)) |
| 524 | } else if let Some(prop) = self.getprop_u32(cstr!("linux,phandle"))? { |
| 525 | Ok(Some(prop.try_into()?)) |
| 526 | } else { |
| 527 | Ok(None) |
| 528 | } |
| 529 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 530 | } |
| 531 | |
Pierre-Clément Tosi | 504b430 | 2023-10-30 12:22:50 +0000 | [diff] [blame] | 532 | impl<'a> PartialEq for FdtNode<'a> { |
| 533 | fn eq(&self, other: &Self) -> bool { |
| 534 | self.fdt.as_ptr() == other.fdt.as_ptr() && self.offset == other.offset |
| 535 | } |
| 536 | } |
| 537 | |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 538 | /// Phandle of a FDT node |
| 539 | #[repr(transparent)] |
Jaewan Kim | 55f438c | 2023-11-15 01:24:36 +0900 | [diff] [blame] | 540 | #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 541 | pub struct Phandle(u32); |
| 542 | |
| 543 | impl Phandle { |
Pierre-Clément Tosi | eba2779 | 2023-10-30 12:04:12 +0000 | [diff] [blame] | 544 | /// Minimum valid value for device tree phandles. |
| 545 | pub const MIN: Self = Self(1); |
| 546 | /// Maximum valid value for device tree phandles. |
| 547 | pub const MAX: Self = Self(libfdt_bindgen::FDT_MAX_PHANDLE); |
| 548 | |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 549 | /// Creates a new Phandle |
Pierre-Clément Tosi | eba2779 | 2023-10-30 12:04:12 +0000 | [diff] [blame] | 550 | pub const fn new(value: u32) -> Option<Self> { |
| 551 | if Self::MIN.0 <= value && value <= Self::MAX.0 { |
| 552 | Some(Self(value)) |
| 553 | } else { |
| 554 | None |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 555 | } |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 556 | } |
| 557 | } |
| 558 | |
| 559 | impl From<Phandle> for u32 { |
| 560 | fn from(phandle: Phandle) -> u32 { |
| 561 | phandle.0 |
| 562 | } |
| 563 | } |
| 564 | |
Pierre-Clément Tosi | eba2779 | 2023-10-30 12:04:12 +0000 | [diff] [blame] | 565 | impl TryFrom<u32> for Phandle { |
| 566 | type Error = FdtError; |
| 567 | |
| 568 | fn try_from(value: u32) -> Result<Self> { |
| 569 | Self::new(value).ok_or(FdtError::BadPhandle) |
| 570 | } |
| 571 | } |
| 572 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 573 | /// Mutable FDT node. |
Pierre-Clément Tosi | 504b430 | 2023-10-30 12:22:50 +0000 | [diff] [blame] | 574 | #[derive(Debug)] |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 575 | pub struct FdtNodeMut<'a> { |
| 576 | fdt: &'a mut Fdt, |
| 577 | offset: c_int, |
| 578 | } |
| 579 | |
| 580 | impl<'a> FdtNodeMut<'a> { |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 581 | /// Appends a property name-value (possibly empty) pair to the given node. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 582 | pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 583 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 584 | let ret = unsafe { |
| 585 | libfdt_bindgen::fdt_appendprop( |
| 586 | self.fdt.as_mut_ptr(), |
| 587 | self.offset, |
| 588 | name.as_ptr(), |
| 589 | value.as_ref().as_ptr().cast::<c_void>(), |
| 590 | value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?, |
| 591 | ) |
| 592 | }; |
| 593 | |
| 594 | fdt_err_expect_zero(ret) |
| 595 | } |
| 596 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 597 | /// Appends a (address, size) pair property to the given node. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 598 | pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 599 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 600 | let ret = unsafe { |
| 601 | libfdt_bindgen::fdt_appendprop_addrrange( |
| 602 | self.fdt.as_mut_ptr(), |
| 603 | self.parent()?.offset, |
| 604 | self.offset, |
| 605 | name.as_ptr(), |
| 606 | addr, |
| 607 | size, |
| 608 | ) |
| 609 | }; |
| 610 | |
| 611 | fdt_err_expect_zero(ret) |
| 612 | } |
| 613 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 614 | /// Sets a property name-value pair to the given node. |
| 615 | /// |
| 616 | /// This may create a new prop or replace existing value. |
Jaewan Kim | ba8929b | 2023-01-13 11:13:29 +0900 | [diff] [blame] | 617 | pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 618 | // SAFETY: New value size is constrained to the DT totalsize |
Jaewan Kim | ba8929b | 2023-01-13 11:13:29 +0900 | [diff] [blame] | 619 | // (validated by underlying libfdt). |
| 620 | let ret = unsafe { |
| 621 | libfdt_bindgen::fdt_setprop( |
| 622 | self.fdt.as_mut_ptr(), |
| 623 | self.offset, |
| 624 | name.as_ptr(), |
| 625 | value.as_ptr().cast::<c_void>(), |
| 626 | value.len().try_into().map_err(|_| FdtError::BadValue)?, |
| 627 | ) |
| 628 | }; |
| 629 | |
| 630 | fdt_err_expect_zero(ret) |
| 631 | } |
| 632 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 633 | /// Sets the value of the given property with the given value, and ensure that the given |
| 634 | /// value has the same length as the current value length. |
| 635 | /// |
| 636 | /// This can only be used to replace existing value. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 637 | pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 638 | // SAFETY: fdt size is not altered |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 639 | let ret = unsafe { |
| 640 | libfdt_bindgen::fdt_setprop_inplace( |
| 641 | self.fdt.as_mut_ptr(), |
| 642 | self.offset, |
| 643 | name.as_ptr(), |
| 644 | value.as_ptr().cast::<c_void>(), |
| 645 | value.len().try_into().map_err(|_| FdtError::BadValue)?, |
| 646 | ) |
| 647 | }; |
| 648 | |
| 649 | fdt_err_expect_zero(ret) |
| 650 | } |
| 651 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 652 | /// Sets the value of the given (address, size) pair property with the given value, and |
| 653 | /// ensure that the given value has the same length as the current value length. |
| 654 | /// |
| 655 | /// This can only be used to replace existing value. |
Pierre-Clément Tosi | c27c427 | 2023-05-19 15:46:26 +0000 | [diff] [blame] | 656 | pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> { |
| 657 | let pair = [addr.to_be(), size.to_be()]; |
| 658 | self.setprop_inplace(name, pair.as_bytes()) |
| 659 | } |
| 660 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 661 | /// Sets a flag-like empty property. |
| 662 | /// |
| 663 | /// This may create a new prop or replace existing value. |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 664 | pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> { |
| 665 | self.setprop(name, &[]) |
| 666 | } |
| 667 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 668 | /// Deletes the given property. |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 669 | pub fn delprop(&mut self, name: &CStr) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 670 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 671 | // library locates the node's property. Removing the property may shift the offsets of |
| 672 | // other nodes and properties but the borrow checker should prevent this function from |
| 673 | // being called when FdtNode instances are in use. |
| 674 | let ret = unsafe { |
| 675 | libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 676 | }; |
| 677 | |
| 678 | fdt_err_expect_zero(ret) |
| 679 | } |
| 680 | |
Jaewan Kim | 4ae0e71 | 2023-10-19 14:16:17 +0900 | [diff] [blame] | 681 | /// Deletes the given property effectively from DT, by setting it with FDT_NOP. |
Pierre-Clément Tosi | be3a97b | 2023-05-19 14:56:23 +0000 | [diff] [blame] | 682 | pub fn nop_property(&mut self, name: &CStr) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 683 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the |
Pierre-Clément Tosi | be3a97b | 2023-05-19 14:56:23 +0000 | [diff] [blame] | 684 | // library locates the node's property. |
| 685 | let ret = unsafe { |
| 686 | libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 687 | }; |
| 688 | |
| 689 | fdt_err_expect_zero(ret) |
| 690 | } |
| 691 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 692 | /// Trims the size of the given property to new_size. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 693 | pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> { |
| 694 | let (prop, len) = |
| 695 | FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?; |
| 696 | if len == new_size { |
| 697 | return Ok(()); |
| 698 | } |
| 699 | if new_size > len { |
| 700 | return Err(FdtError::NoSpace); |
| 701 | } |
| 702 | |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 703 | // SAFETY: new_size is smaller than the old size |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 704 | let ret = unsafe { |
| 705 | libfdt_bindgen::fdt_setprop( |
| 706 | self.fdt.as_mut_ptr(), |
| 707 | self.offset, |
| 708 | name.as_ptr(), |
| 709 | prop.cast::<c_void>(), |
| 710 | new_size.try_into().map_err(|_| FdtError::BadValue)?, |
| 711 | ) |
| 712 | }; |
| 713 | |
| 714 | fdt_err_expect_zero(ret) |
| 715 | } |
| 716 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 717 | /// Returns reference to the containing device tree. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 718 | pub fn fdt(&mut self) -> &mut Fdt { |
| 719 | self.fdt |
| 720 | } |
| 721 | |
Jaewan Kim | f72f4f2 | 2023-11-03 19:21:34 +0900 | [diff] [blame] | 722 | /// Returns immutable FdtNode of this node. |
| 723 | pub fn as_node(&self) -> FdtNode { |
| 724 | FdtNode { fdt: self.fdt, offset: self.offset } |
| 725 | } |
| 726 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 727 | /// Adds a new subnode to the given node and return it as a FdtNodeMut on success. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 728 | pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> { |
Jaewan Kim | 5ab1358 | 2023-10-20 20:56:27 +0900 | [diff] [blame] | 729 | let offset = self.add_subnode_offset(name.to_bytes())?; |
| 730 | Ok(Self { fdt: self.fdt, offset }) |
| 731 | } |
| 732 | |
| 733 | /// Adds a new subnode to the given node with name and namelen, and returns it as a FdtNodeMut |
| 734 | /// on success. |
| 735 | pub fn add_subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Self> { |
| 736 | let offset = { self.add_subnode_offset(&name.to_bytes()[..namelen])? }; |
| 737 | Ok(Self { fdt: self.fdt, offset }) |
| 738 | } |
| 739 | |
| 740 | fn add_subnode_offset(&mut self, name: &[u8]) -> Result<c_int> { |
| 741 | let namelen = name.len().try_into().unwrap(); |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 742 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 743 | let ret = unsafe { |
Jaewan Kim | 5ab1358 | 2023-10-20 20:56:27 +0900 | [diff] [blame] | 744 | libfdt_bindgen::fdt_add_subnode_namelen( |
| 745 | self.fdt.as_mut_ptr(), |
| 746 | self.offset, |
| 747 | name.as_ptr().cast::<_>(), |
| 748 | namelen, |
| 749 | ) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 750 | }; |
Jaewan Kim | 5ab1358 | 2023-10-20 20:56:27 +0900 | [diff] [blame] | 751 | fdt_err(ret) |
| 752 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 753 | |
Jaewan Kim | 5ab1358 | 2023-10-20 20:56:27 +0900 | [diff] [blame] | 754 | /// Returns the subnode of the given name with len. |
| 755 | pub fn subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Option<Self>> { |
| 756 | let offset = self.subnode_offset(&name.to_bytes()[..namelen])?; |
| 757 | Ok(offset.map(|offset| Self { fdt: self.fdt, offset })) |
| 758 | } |
| 759 | |
| 760 | fn subnode_offset(&self, name: &[u8]) -> Result<Option<c_int>> { |
| 761 | let namelen = name.len().try_into().unwrap(); |
| 762 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
| 763 | let ret = unsafe { |
| 764 | libfdt_bindgen::fdt_subnode_offset_namelen( |
| 765 | self.fdt.as_ptr(), |
| 766 | self.offset, |
| 767 | name.as_ptr().cast::<_>(), |
| 768 | namelen, |
| 769 | ) |
| 770 | }; |
| 771 | fdt_err_or_option(ret) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 772 | } |
| 773 | |
| 774 | fn parent(&'a self) -> Result<FdtNode<'a>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 775 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 776 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 777 | |
| 778 | Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? }) |
| 779 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 780 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 781 | /// Returns the compatible node of the given name that is next after this node. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 782 | pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 783 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 784 | let ret = unsafe { |
| 785 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 786 | self.fdt.as_ptr(), |
| 787 | self.offset, |
| 788 | compatible.as_ptr(), |
| 789 | ) |
| 790 | }; |
| 791 | |
| 792 | Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset })) |
| 793 | } |
| 794 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 795 | /// Deletes the node effectively by overwriting this node and its subtree with nop tags. |
| 796 | /// Returns the next compatible node of the given name. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 797 | // Side note: without this, filterint out excessive compatible nodes from the DT is impossible. |
| 798 | // The reason is that libfdt ensures that the node from where the search for the next |
| 799 | // compatible node is started is always a valid one -- except for the special case of offset = |
| 800 | // -1 which is to find the first compatible node. So, we can't delete a node and then find the |
| 801 | // next compatible node from it. |
| 802 | // |
| 803 | // We can't do in the opposite direction either. If we call next_compatible to find the next |
| 804 | // node, and delete the current node, the Rust borrow checker kicks in. The next node has a |
| 805 | // mutable reference to DT, so we can't use current node (which also has a mutable reference to |
| 806 | // DT). |
Jaewan Kim | 4ae0e71 | 2023-10-19 14:16:17 +0900 | [diff] [blame] | 807 | pub fn delete_and_next_compatible(mut self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 808 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 809 | let ret = unsafe { |
| 810 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 811 | self.fdt.as_ptr(), |
| 812 | self.offset, |
| 813 | compatible.as_ptr(), |
| 814 | ) |
| 815 | }; |
| 816 | let next_offset = fdt_err_or_option(ret)?; |
| 817 | |
Jaewan Kim | 4ae0e71 | 2023-10-19 14:16:17 +0900 | [diff] [blame] | 818 | if Some(self.offset) == next_offset { |
| 819 | return Err(FdtError::Internal); |
| 820 | } |
| 821 | |
| 822 | // SAFETY: nop_self() only touches bytes of the self and its properties and subnodes, and |
| 823 | // doesn't alter any other blob in the tree. self.fdt and next_offset would remain valid. |
| 824 | unsafe { self.nop_self()? }; |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 825 | |
| 826 | Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset })) |
| 827 | } |
Jaewan Kim | 4ae0e71 | 2023-10-19 14:16:17 +0900 | [diff] [blame] | 828 | |
| 829 | /// Deletes this node effectively from DT, by setting it with FDT_NOP |
| 830 | pub fn nop(mut self) -> Result<()> { |
| 831 | // SAFETY: This consumes self, so invalid node wouldn't be used any further |
| 832 | unsafe { self.nop_self() } |
| 833 | } |
| 834 | |
| 835 | /// Deletes this node effectively from DT, by setting it with FDT_NOP. |
| 836 | /// This only changes bytes of the node and its properties and subnodes, and doesn't alter or |
| 837 | /// move any other part of the tree. |
| 838 | /// SAFETY: This node is no longer valid. |
| 839 | unsafe fn nop_self(&mut self) -> Result<()> { |
| 840 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
| 841 | let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) }; |
| 842 | |
| 843 | fdt_err_expect_zero(ret) |
| 844 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 845 | } |
| 846 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 847 | /// Wrapper around low-level libfdt functions. |
Alice Wang | 9d4df70 | 2023-05-25 14:14:12 +0000 | [diff] [blame] | 848 | #[derive(Debug)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 849 | #[repr(transparent)] |
| 850 | pub struct Fdt { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 851 | buffer: [u8], |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 852 | } |
| 853 | |
| 854 | impl Fdt { |
| 855 | /// Wraps a slice containing a Flattened Device Tree. |
| 856 | /// |
| 857 | /// Fails if the FDT does not pass validation. |
| 858 | pub fn from_slice(fdt: &[u8]) -> Result<&Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 859 | // SAFETY: The FDT will be validated before it is returned. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 860 | let fdt = unsafe { Self::unchecked_from_slice(fdt) }; |
| 861 | fdt.check_full()?; |
| 862 | Ok(fdt) |
| 863 | } |
| 864 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 865 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 866 | /// |
| 867 | /// Fails if the FDT does not pass validation. |
| 868 | pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 869 | // SAFETY: The FDT will be validated before it is returned. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 870 | let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) }; |
| 871 | fdt.check_full()?; |
| 872 | Ok(fdt) |
| 873 | } |
| 874 | |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 875 | /// Creates an empty Flattened Device Tree with a mutable slice. |
| 876 | pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 877 | // SAFETY: fdt_create_empty_tree() only write within the specified length, |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 878 | // and returns error if buffer was insufficient. |
| 879 | // There will be no memory write outside of the given fdt. |
| 880 | let ret = unsafe { |
| 881 | libfdt_bindgen::fdt_create_empty_tree( |
| 882 | fdt.as_mut_ptr().cast::<c_void>(), |
| 883 | fdt.len() as i32, |
| 884 | ) |
| 885 | }; |
| 886 | fdt_err_expect_zero(ret)?; |
| 887 | |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 888 | // SAFETY: The FDT will be validated before it is returned. |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 889 | let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) }; |
| 890 | fdt.check_full()?; |
| 891 | |
| 892 | Ok(fdt) |
| 893 | } |
| 894 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 895 | /// Wraps a slice containing a Flattened Device Tree. |
| 896 | /// |
| 897 | /// # Safety |
| 898 | /// |
| 899 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 900 | pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 901 | // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is |
| 902 | // responsible for ensuring that it is actually a valid FDT. |
| 903 | unsafe { mem::transmute::<&[u8], &Self>(fdt) } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 904 | } |
| 905 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 906 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 907 | /// |
| 908 | /// # Safety |
| 909 | /// |
| 910 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 911 | pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 912 | // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is |
| 913 | // responsible for ensuring that it is actually a valid FDT. |
| 914 | unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 915 | } |
| 916 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 917 | /// Updates this FDT from a slice containing another FDT. |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 918 | pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> { |
| 919 | if self.buffer.len() < new_fdt.len() { |
| 920 | Err(FdtError::NoSpace) |
| 921 | } else { |
| 922 | let totalsize = self.totalsize(); |
| 923 | self.buffer[..new_fdt.len()].clone_from_slice(new_fdt); |
| 924 | // Zeroize the remaining part. We zeroize up to the size of the original DT because |
| 925 | // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot |
| 926 | // time. |
| 927 | self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8); |
| 928 | Ok(()) |
| 929 | } |
| 930 | } |
| 931 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 932 | /// Unpacks the DT to cover the whole slice it is contained in. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 933 | pub fn unpack(&mut self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 934 | // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 935 | // internal structures to make use of the whole self.fdt slice but performs no accesses |
| 936 | // outside of it and leaves the DT in a state that will be detected by other functions. |
| 937 | let ret = unsafe { |
| 938 | libfdt_bindgen::fdt_open_into( |
| 939 | self.as_ptr(), |
| 940 | self.as_mut_ptr(), |
| 941 | self.capacity().try_into().map_err(|_| FdtError::Internal)?, |
| 942 | ) |
| 943 | }; |
| 944 | fdt_err_expect_zero(ret) |
| 945 | } |
| 946 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 947 | /// Packs the DT to take a minimum amount of memory. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 948 | /// |
| 949 | /// Doesn't shrink the underlying memory slice. |
| 950 | pub fn pack(&mut self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 951 | // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 952 | let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) }; |
| 953 | fdt_err_expect_zero(ret) |
| 954 | } |
| 955 | |
Pierre-Clément Tosi | 90e1935 | 2022-11-21 17:11:48 +0000 | [diff] [blame] | 956 | /// Applies a DT overlay on the base DT. |
| 957 | /// |
| 958 | /// # Safety |
| 959 | /// |
| 960 | /// On failure, the library corrupts the DT and overlay so both must be discarded. |
| 961 | pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 962 | let ret = |
| 963 | // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply |
| 964 | // doesn't keep them after it returns. It may corrupt their contents if there is an error, |
| 965 | // but that's our caller's responsibility. |
| 966 | unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) }; |
| 967 | fdt_err_expect_zero(ret)?; |
Pierre-Clément Tosi | 90e1935 | 2022-11-21 17:11:48 +0000 | [diff] [blame] | 968 | Ok(self) |
| 969 | } |
| 970 | |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 971 | /// Returns an iterator of memory banks specified the "/memory" node. |
| 972 | /// Throws an error when the "/memory" is not found in the device tree. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 973 | /// |
| 974 | /// NOTE: This does not support individual "/memory@XXXX" banks. |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 975 | pub fn memory(&self) -> Result<MemRegIterator> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 976 | let memory_node_name = cstr!("/memory"); |
| 977 | let memory_device_type = cstr!("memory"); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 978 | |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 979 | let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?; |
| 980 | if node.device_type()? != Some(memory_device_type) { |
| 981 | return Err(FdtError::BadValue); |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 982 | } |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 983 | node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new) |
| 984 | } |
| 985 | |
| 986 | /// Returns the first memory range in the `/memory` node. |
| 987 | pub fn first_memory_range(&self) -> Result<Range<usize>> { |
| 988 | self.memory()?.next().ok_or(FdtError::NotFound) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 989 | } |
| 990 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 991 | /// Returns the standard /chosen node. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 992 | pub fn chosen(&self) -> Result<Option<FdtNode>> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 993 | self.node(cstr!("/chosen")) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 994 | } |
| 995 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 996 | /// Returns the standard /chosen node as mutable. |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 997 | pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 998 | self.node_mut(cstr!("/chosen")) |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 999 | } |
| 1000 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1001 | /// Returns the root node of the tree. |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 1002 | pub fn root(&self) -> Result<FdtNode> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 1003 | self.node(cstr!("/"))?.ok_or(FdtError::Internal) |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 1004 | } |
| 1005 | |
Jaewan Kim | f163d76 | 2023-11-01 13:12:50 +0900 | [diff] [blame] | 1006 | /// Returns the standard /__symbols__ node. |
| 1007 | pub fn symbols(&self) -> Result<Option<FdtNode>> { |
| 1008 | self.node(cstr!("/__symbols__")) |
| 1009 | } |
| 1010 | |
| 1011 | /// Returns the standard /__symbols__ node as mutable |
| 1012 | pub fn symbols_mut(&mut self) -> Result<Option<FdtNodeMut>> { |
| 1013 | self.node_mut(cstr!("/__symbols__")) |
| 1014 | } |
| 1015 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1016 | /// Returns a tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 1017 | pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> { |
Jaewan Kim | bab4259 | 2023-10-13 15:47:19 +0900 | [diff] [blame] | 1018 | Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNode { fdt: self, offset })) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1019 | } |
| 1020 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 1021 | /// Iterate over nodes with a given compatible string. |
| 1022 | pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> { |
| 1023 | CompatibleIterator::new(self, compatible) |
| 1024 | } |
| 1025 | |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 1026 | /// Returns max phandle in the tree. |
| 1027 | pub fn max_phandle(&self) -> Result<Phandle> { |
| 1028 | let mut phandle: u32 = 0; |
| 1029 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 1030 | let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(self.as_ptr(), &mut phandle) }; |
| 1031 | |
| 1032 | fdt_err_expect_zero(ret)?; |
Pierre-Clément Tosi | eba2779 | 2023-10-30 12:04:12 +0000 | [diff] [blame] | 1033 | phandle.try_into() |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 1034 | } |
| 1035 | |
| 1036 | /// Returns a node with the phandle |
| 1037 | pub fn node_with_phandle(&self, phandle: Phandle) -> Result<Option<FdtNode>> { |
Jaewan Kim | c63246d | 2023-11-09 15:41:01 +0900 | [diff] [blame] | 1038 | let offset = self.node_offset_with_phandle(phandle)?; |
| 1039 | Ok(offset.map(|offset| FdtNode { fdt: self, offset })) |
| 1040 | } |
| 1041 | |
| 1042 | /// Returns a mutable node with the phandle |
| 1043 | pub fn node_mut_with_phandle(&mut self, phandle: Phandle) -> Result<Option<FdtNodeMut>> { |
| 1044 | let offset = self.node_offset_with_phandle(phandle)?; |
| 1045 | Ok(offset.map(|offset| FdtNodeMut { fdt: self, offset })) |
| 1046 | } |
| 1047 | |
| 1048 | fn node_offset_with_phandle(&self, phandle: Phandle) -> Result<Option<c_int>> { |
| 1049 | // SAFETY: Accesses are constrained to the DT totalsize. |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 1050 | let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(self.as_ptr(), phandle.0) }; |
Jaewan Kim | c63246d | 2023-11-09 15:41:01 +0900 | [diff] [blame] | 1051 | fdt_err_or_option(ret) |
Jaewan Kim | 17ba7a3 | 2023-10-19 13:25:15 +0900 | [diff] [blame] | 1052 | } |
| 1053 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1054 | /// Returns the mutable root node of the tree. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1055 | pub fn root_mut(&mut self) -> Result<FdtNodeMut> { |
Jaewan Kim | b635bb0 | 2023-11-01 13:00:34 +0900 | [diff] [blame] | 1056 | self.node_mut(cstr!("/"))?.ok_or(FdtError::Internal) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1057 | } |
| 1058 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1059 | /// Returns a mutable tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 1060 | pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> { |
Jaewan Kim | bab4259 | 2023-10-13 15:47:19 +0900 | [diff] [blame] | 1061 | Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNodeMut { fdt: self, offset })) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1062 | } |
| 1063 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1064 | /// Returns the device tree as a slice (may be smaller than the containing buffer). |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 1065 | pub fn as_slice(&self) -> &[u8] { |
| 1066 | &self.buffer[..self.totalsize()] |
| 1067 | } |
| 1068 | |
Jaewan Kim | bab4259 | 2023-10-13 15:47:19 +0900 | [diff] [blame] | 1069 | fn path_offset(&self, path: &[u8]) -> Result<Option<c_int>> { |
| 1070 | let len = path.len().try_into().map_err(|_| FdtError::BadPath)?; |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 1071 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1072 | // function respects the passed number of characters. |
| 1073 | let ret = unsafe { |
| 1074 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
Jaewan Kim | bab4259 | 2023-10-13 15:47:19 +0900 | [diff] [blame] | 1075 | libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr().cast::<_>(), len) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1076 | }; |
| 1077 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 1078 | fdt_err_or_option(ret) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1079 | } |
| 1080 | |
| 1081 | fn check_full(&self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 1082 | // SAFETY: Only performs read accesses within the limits of the slice. If successful, this |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1083 | // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t. |
| 1084 | // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds |
| 1085 | // checking. The library doesn't maintain an internal state (such as pointers) between |
| 1086 | // calls as it expects the client code to keep track of the objects (DT, nodes, ...). |
Pierre-Clément Tosi | 02017da | 2023-09-26 17:57:04 +0100 | [diff] [blame] | 1087 | let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) }; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1088 | fdt_err_expect_zero(ret) |
| 1089 | } |
| 1090 | |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 1091 | fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> { |
| 1092 | let ptr = ptr as usize; |
| 1093 | let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?; |
| 1094 | self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal) |
| 1095 | } |
| 1096 | |
Jaewan Kim | 72d1090 | 2023-10-12 21:59:26 +0900 | [diff] [blame] | 1097 | fn string(&self, offset: c_int) -> Result<&CStr> { |
| 1098 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 1099 | let res = unsafe { libfdt_bindgen::fdt_string(self.as_ptr(), offset) }; |
| 1100 | if res.is_null() { |
| 1101 | return Err(FdtError::Internal); |
| 1102 | } |
| 1103 | |
| 1104 | // SAFETY: Non-null return from fdt_string() is valid null-terminating string within FDT. |
| 1105 | Ok(unsafe { CStr::from_ptr(res) }) |
| 1106 | } |
| 1107 | |
Jaewan Kim | b3dcfc2 | 2023-09-20 10:20:52 +0900 | [diff] [blame] | 1108 | /// Returns a shared pointer to the device tree. |
Pierre-Clément Tosi | 8036b4f | 2023-02-17 10:31:31 +0000 | [diff] [blame] | 1109 | pub fn as_ptr(&self) -> *const c_void { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 1110 | self.buffer.as_ptr().cast::<_>() |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1111 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1112 | |
| 1113 | fn as_mut_ptr(&mut self) -> *mut c_void { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 1114 | self.buffer.as_mut_ptr().cast::<_>() |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1115 | } |
| 1116 | |
| 1117 | fn capacity(&self) -> usize { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 1118 | self.buffer.len() |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 1119 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 1120 | |
| 1121 | fn header(&self) -> &libfdt_bindgen::fdt_header { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 1122 | let p = self.as_ptr().cast::<_>(); |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 1123 | // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header. |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 1124 | unsafe { &*p } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 1125 | } |
| 1126 | |
| 1127 | fn totalsize(&self) -> usize { |
| 1128 | u32::from_be(self.header().totalsize) as usize |
| 1129 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 1130 | } |