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