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::{ |
| 23 | AddressRange, CellIterator, CompatibleIterator, MemRegIterator, RangesIterator, Reg, |
Jaewan Kim | bc828d7 | 2023-09-19 15:52:08 +0900 | [diff] [blame^] | 24 | 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; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 32 | use core::result; |
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 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 197 | /// DT node. |
Alice Wang | 9d4df70 | 2023-05-25 14:14:12 +0000 | [diff] [blame] | 198 | #[derive(Clone, Copy, Debug)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 199 | pub struct FdtNode<'a> { |
| 200 | fdt: &'a Fdt, |
| 201 | offset: c_int, |
| 202 | } |
| 203 | |
| 204 | impl<'a> FdtNode<'a> { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 205 | /// Create immutable node from a mutable node at the same offset |
| 206 | pub fn from_mut(other: &'a FdtNodeMut) -> Self { |
| 207 | FdtNode { fdt: other.fdt, offset: other.offset } |
| 208 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 209 | /// Find parent node. |
| 210 | pub fn parent(&self) -> Result<Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 211 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 212 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 213 | |
| 214 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 215 | } |
| 216 | |
| 217 | /// Retrieve the standard (deprecated) device_type <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 218 | pub fn device_type(&self) -> Result<Option<&CStr>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 219 | self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap()) |
| 220 | } |
| 221 | |
| 222 | /// Retrieve the standard reg <prop-encoded-array> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 223 | pub fn reg(&self) -> Result<Option<RegIterator<'a>>> { |
| 224 | let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap(); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 225 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 226 | if let Some(cells) = self.getprop_cells(reg)? { |
| 227 | let parent = self.parent()?; |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 228 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 229 | let addr_cells = parent.address_cells()?; |
| 230 | let size_cells = parent.size_cells()?; |
| 231 | |
| 232 | Ok(Some(RegIterator::new(cells, addr_cells, size_cells))) |
| 233 | } else { |
| 234 | Ok(None) |
| 235 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 236 | } |
| 237 | |
Andrew Walbran | b39e692 | 2022-12-05 17:01:20 +0000 | [diff] [blame] | 238 | /// Retrieves the standard ranges property. |
| 239 | pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> { |
| 240 | let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap(); |
| 241 | if let Some(cells) = self.getprop_cells(ranges)? { |
| 242 | let parent = self.parent()?; |
| 243 | let addr_cells = self.address_cells()?; |
| 244 | let parent_addr_cells = parent.address_cells()?; |
| 245 | let size_cells = self.size_cells()?; |
| 246 | Ok(Some(RangesIterator::<A, P, S>::new( |
| 247 | cells, |
| 248 | addr_cells, |
| 249 | parent_addr_cells, |
| 250 | size_cells, |
| 251 | ))) |
| 252 | } else { |
| 253 | Ok(None) |
| 254 | } |
| 255 | } |
| 256 | |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 257 | /// Returns the node name. |
| 258 | pub fn name(&self) -> Result<&'a CStr> { |
| 259 | let mut len: c_int = 0; |
| 260 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the |
| 261 | // function returns valid null terminating string and otherwise returned values are dropped. |
| 262 | let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) } |
| 263 | as *const c_void; |
| 264 | let len = usize::try_from(fdt_err(len)?).unwrap(); |
| 265 | let name = self.fdt.get_from_ptr(name, len + 1)?; |
| 266 | CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal) |
| 267 | } |
| 268 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 269 | /// Retrieve the value of a given <string> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 270 | pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> { |
| 271 | let value = if let Some(bytes) = self.getprop(name)? { |
| 272 | Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?) |
| 273 | } else { |
| 274 | None |
| 275 | }; |
| 276 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 277 | } |
| 278 | |
| 279 | /// Retrieve the value of a given property as an array of cells. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 280 | pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> { |
| 281 | if let Some(cells) = self.getprop(name)? { |
| 282 | Ok(Some(CellIterator::new(cells))) |
| 283 | } else { |
| 284 | Ok(None) |
| 285 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 286 | } |
| 287 | |
| 288 | /// Retrieve the value of a given <u32> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 289 | pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> { |
| 290 | let value = if let Some(bytes) = self.getprop(name)? { |
| 291 | Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 292 | } else { |
| 293 | None |
| 294 | }; |
| 295 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 296 | } |
| 297 | |
| 298 | /// Retrieve the value of a given <u64> property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 299 | pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> { |
| 300 | let value = if let Some(bytes) = self.getprop(name)? { |
| 301 | Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)) |
| 302 | } else { |
| 303 | None |
| 304 | }; |
| 305 | Ok(value) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 306 | } |
| 307 | |
| 308 | /// Retrieve the value of a given property. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 309 | pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> { |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 310 | 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] | 311 | Ok(Some(self.fdt.get_from_ptr(prop, len)?)) |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 312 | } else { |
| 313 | Ok(None) // property was not found |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// Return the pointer and size of the property named `name`, in a node at offset `offset`, in |
| 318 | /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns. |
| 319 | fn getprop_internal( |
| 320 | fdt: &'a Fdt, |
| 321 | offset: c_int, |
| 322 | name: &CStr, |
| 323 | ) -> Result<Option<(*const c_void, usize)>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 324 | let mut len: i32 = 0; |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 325 | // 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] | 326 | // function respects the passed number of characters. |
| 327 | let prop = unsafe { |
| 328 | libfdt_bindgen::fdt_getprop_namelen( |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 329 | fdt.as_ptr(), |
| 330 | offset, |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 331 | name.as_ptr(), |
| 332 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 333 | name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?, |
| 334 | &mut len as *mut i32, |
| 335 | ) |
| 336 | } as *const u8; |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 337 | |
| 338 | let Some(len) = fdt_err_or_option(len)? else { |
| 339 | return Ok(None); // Property was not found. |
| 340 | }; |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 341 | let len = usize::try_from(len).unwrap(); |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 342 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 343 | if prop.is_null() { |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 344 | // We expected an error code in len but still received a valid value?! |
| 345 | return Err(FdtError::Internal); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 346 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 347 | Ok(Some((prop.cast::<c_void>(), len))) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 348 | } |
| 349 | |
| 350 | /// Get reference to the containing device tree. |
| 351 | pub fn fdt(&self) -> &Fdt { |
| 352 | self.fdt |
| 353 | } |
| 354 | |
Alice Wang | 474c0ee | 2023-09-14 12:52:33 +0000 | [diff] [blame] | 355 | /// Returns the compatible node of the given name that is next after this node. |
| 356 | pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 357 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 358 | let ret = unsafe { |
| 359 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 360 | self.fdt.as_ptr(), |
| 361 | self.offset, |
| 362 | compatible.as_ptr(), |
| 363 | ) |
| 364 | }; |
| 365 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 366 | 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] | 367 | } |
| 368 | |
Alice Wang | 474c0ee | 2023-09-14 12:52:33 +0000 | [diff] [blame] | 369 | /// Returns the first range of `reg` in this node. |
| 370 | pub fn first_reg(&self) -> Result<Reg<u64>> { |
| 371 | self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound) |
| 372 | } |
| 373 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 374 | fn address_cells(&self) -> Result<AddrCells> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 375 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 376 | unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) } |
| 377 | .try_into() |
| 378 | .map_err(|_| FdtError::Internal) |
| 379 | } |
| 380 | |
| 381 | fn size_cells(&self) -> Result<SizeCells> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 382 | // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 383 | unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) } |
| 384 | .try_into() |
| 385 | .map_err(|_| FdtError::Internal) |
| 386 | } |
Jaewan Kim | bc828d7 | 2023-09-19 15:52:08 +0900 | [diff] [blame^] | 387 | |
| 388 | /// Returns an iterator of subnodes |
| 389 | pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> { |
| 390 | SubnodeIterator::new(self) |
| 391 | } |
| 392 | |
| 393 | fn first_subnode(&self) -> Result<Option<Self>> { |
| 394 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 395 | let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) }; |
| 396 | |
| 397 | Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset })) |
| 398 | } |
| 399 | |
| 400 | fn next_subnode(&self) -> Result<Option<Self>> { |
| 401 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
| 402 | let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) }; |
| 403 | |
| 404 | Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset })) |
| 405 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 406 | } |
| 407 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 408 | /// Mutable FDT node. |
| 409 | pub struct FdtNodeMut<'a> { |
| 410 | fdt: &'a mut Fdt, |
| 411 | offset: c_int, |
| 412 | } |
| 413 | |
| 414 | impl<'a> FdtNodeMut<'a> { |
| 415 | /// Append a property name-value (possibly empty) pair to the given node. |
| 416 | 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] | 417 | // 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] | 418 | let ret = unsafe { |
| 419 | libfdt_bindgen::fdt_appendprop( |
| 420 | self.fdt.as_mut_ptr(), |
| 421 | self.offset, |
| 422 | name.as_ptr(), |
| 423 | value.as_ref().as_ptr().cast::<c_void>(), |
| 424 | value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?, |
| 425 | ) |
| 426 | }; |
| 427 | |
| 428 | fdt_err_expect_zero(ret) |
| 429 | } |
| 430 | |
| 431 | /// Append a (address, size) pair property to the given node. |
| 432 | 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] | 433 | // 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] | 434 | let ret = unsafe { |
| 435 | libfdt_bindgen::fdt_appendprop_addrrange( |
| 436 | self.fdt.as_mut_ptr(), |
| 437 | self.parent()?.offset, |
| 438 | self.offset, |
| 439 | name.as_ptr(), |
| 440 | addr, |
| 441 | size, |
| 442 | ) |
| 443 | }; |
| 444 | |
| 445 | fdt_err_expect_zero(ret) |
| 446 | } |
| 447 | |
Jaewan Kim | ba8929b | 2023-01-13 11:13:29 +0900 | [diff] [blame] | 448 | /// Create or change a property name-value pair to the given node. |
| 449 | pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 450 | // SAFETY: New value size is constrained to the DT totalsize |
Jaewan Kim | ba8929b | 2023-01-13 11:13:29 +0900 | [diff] [blame] | 451 | // (validated by underlying libfdt). |
| 452 | let ret = unsafe { |
| 453 | libfdt_bindgen::fdt_setprop( |
| 454 | self.fdt.as_mut_ptr(), |
| 455 | self.offset, |
| 456 | name.as_ptr(), |
| 457 | value.as_ptr().cast::<c_void>(), |
| 458 | value.len().try_into().map_err(|_| FdtError::BadValue)?, |
| 459 | ) |
| 460 | }; |
| 461 | |
| 462 | fdt_err_expect_zero(ret) |
| 463 | } |
| 464 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 465 | /// Replace the value of the given property with the given value, and ensure that the given |
| 466 | /// value has the same length as the current value length |
| 467 | pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 468 | // SAFETY: fdt size is not altered |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 469 | let ret = unsafe { |
| 470 | libfdt_bindgen::fdt_setprop_inplace( |
| 471 | self.fdt.as_mut_ptr(), |
| 472 | self.offset, |
| 473 | name.as_ptr(), |
| 474 | value.as_ptr().cast::<c_void>(), |
| 475 | value.len().try_into().map_err(|_| FdtError::BadValue)?, |
| 476 | ) |
| 477 | }; |
| 478 | |
| 479 | fdt_err_expect_zero(ret) |
| 480 | } |
| 481 | |
Pierre-Clément Tosi | c27c427 | 2023-05-19 15:46:26 +0000 | [diff] [blame] | 482 | /// Replace the value of the given (address, size) pair property with the given value, and |
| 483 | /// ensure that the given value has the same length as the current value length |
| 484 | pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> { |
| 485 | let pair = [addr.to_be(), size.to_be()]; |
| 486 | self.setprop_inplace(name, pair.as_bytes()) |
| 487 | } |
| 488 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 489 | /// Create or change a flag-like empty property. |
| 490 | pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> { |
| 491 | self.setprop(name, &[]) |
| 492 | } |
| 493 | |
| 494 | /// Delete the given property. |
| 495 | pub fn delprop(&mut self, name: &CStr) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 496 | // 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] | 497 | // library locates the node's property. Removing the property may shift the offsets of |
| 498 | // other nodes and properties but the borrow checker should prevent this function from |
| 499 | // being called when FdtNode instances are in use. |
| 500 | let ret = unsafe { |
| 501 | libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 502 | }; |
| 503 | |
| 504 | fdt_err_expect_zero(ret) |
| 505 | } |
| 506 | |
Pierre-Clément Tosi | be3a97b | 2023-05-19 14:56:23 +0000 | [diff] [blame] | 507 | /// Overwrite the given property with FDT_NOP, effectively removing it from the DT. |
| 508 | pub fn nop_property(&mut self, name: &CStr) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 509 | // 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] | 510 | // library locates the node's property. |
| 511 | let ret = unsafe { |
| 512 | libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 513 | }; |
| 514 | |
| 515 | fdt_err_expect_zero(ret) |
| 516 | } |
| 517 | |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 518 | /// Reduce the size of the given property to new_size |
| 519 | pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> { |
| 520 | let (prop, len) = |
| 521 | FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?; |
| 522 | if len == new_size { |
| 523 | return Ok(()); |
| 524 | } |
| 525 | if new_size > len { |
| 526 | return Err(FdtError::NoSpace); |
| 527 | } |
| 528 | |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 529 | // SAFETY: new_size is smaller than the old size |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 530 | let ret = unsafe { |
| 531 | libfdt_bindgen::fdt_setprop( |
| 532 | self.fdt.as_mut_ptr(), |
| 533 | self.offset, |
| 534 | name.as_ptr(), |
| 535 | prop.cast::<c_void>(), |
| 536 | new_size.try_into().map_err(|_| FdtError::BadValue)?, |
| 537 | ) |
| 538 | }; |
| 539 | |
| 540 | fdt_err_expect_zero(ret) |
| 541 | } |
| 542 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 543 | /// Get reference to the containing device tree. |
| 544 | pub fn fdt(&mut self) -> &mut Fdt { |
| 545 | self.fdt |
| 546 | } |
| 547 | |
| 548 | /// Add a new subnode to the given node and return it as a FdtNodeMut on success. |
| 549 | pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 550 | // 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] | 551 | let ret = unsafe { |
| 552 | libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr()) |
| 553 | }; |
| 554 | |
| 555 | Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? }) |
| 556 | } |
| 557 | |
| 558 | fn parent(&'a self) -> Result<FdtNode<'a>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 559 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 560 | let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) }; |
| 561 | |
| 562 | Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? }) |
| 563 | } |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 564 | |
Alice Wang | 474c0ee | 2023-09-14 12:52:33 +0000 | [diff] [blame] | 565 | /// 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] | 566 | pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 567 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 568 | let ret = unsafe { |
| 569 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 570 | self.fdt.as_ptr(), |
| 571 | self.offset, |
| 572 | compatible.as_ptr(), |
| 573 | ) |
| 574 | }; |
| 575 | |
| 576 | Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset })) |
| 577 | } |
| 578 | |
| 579 | /// Replace this node and its subtree with nop tags, effectively removing it from the tree, and |
| 580 | /// then return the next compatible node of the given name. |
| 581 | // Side note: without this, filterint out excessive compatible nodes from the DT is impossible. |
| 582 | // The reason is that libfdt ensures that the node from where the search for the next |
| 583 | // compatible node is started is always a valid one -- except for the special case of offset = |
| 584 | // -1 which is to find the first compatible node. So, we can't delete a node and then find the |
| 585 | // next compatible node from it. |
| 586 | // |
| 587 | // We can't do in the opposite direction either. If we call next_compatible to find the next |
| 588 | // node, and delete the current node, the Rust borrow checker kicks in. The next node has a |
| 589 | // mutable reference to DT, so we can't use current node (which also has a mutable reference to |
| 590 | // DT). |
| 591 | pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 592 | // SAFETY: Accesses (read-only) are constrained to the DT totalsize. |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 593 | let ret = unsafe { |
| 594 | libfdt_bindgen::fdt_node_offset_by_compatible( |
| 595 | self.fdt.as_ptr(), |
| 596 | self.offset, |
| 597 | compatible.as_ptr(), |
| 598 | ) |
| 599 | }; |
| 600 | let next_offset = fdt_err_or_option(ret)?; |
| 601 | |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 602 | // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its |
Jiyong Park | 9c63cd1 | 2023-03-21 17:53:07 +0900 | [diff] [blame] | 603 | // properties and subnodes, and will not alter or move any other part of the tree. |
| 604 | let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) }; |
| 605 | fdt_err_expect_zero(ret)?; |
| 606 | |
| 607 | Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset })) |
| 608 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 609 | } |
| 610 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 611 | /// Wrapper around low-level libfdt functions. |
Alice Wang | 9d4df70 | 2023-05-25 14:14:12 +0000 | [diff] [blame] | 612 | #[derive(Debug)] |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 613 | #[repr(transparent)] |
| 614 | pub struct Fdt { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 615 | buffer: [u8], |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 616 | } |
| 617 | |
| 618 | impl Fdt { |
| 619 | /// Wraps a slice containing a Flattened Device Tree. |
| 620 | /// |
| 621 | /// Fails if the FDT does not pass validation. |
| 622 | pub fn from_slice(fdt: &[u8]) -> Result<&Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 623 | // SAFETY: The FDT will be validated before it is returned. |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 624 | let fdt = unsafe { Self::unchecked_from_slice(fdt) }; |
| 625 | fdt.check_full()?; |
| 626 | Ok(fdt) |
| 627 | } |
| 628 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 629 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 630 | /// |
| 631 | /// Fails if the FDT does not pass validation. |
| 632 | pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 633 | // SAFETY: The FDT will be validated before it is returned. |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 634 | let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) }; |
| 635 | fdt.check_full()?; |
| 636 | Ok(fdt) |
| 637 | } |
| 638 | |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 639 | /// Creates an empty Flattened Device Tree with a mutable slice. |
| 640 | pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 641 | // SAFETY: fdt_create_empty_tree() only write within the specified length, |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 642 | // and returns error if buffer was insufficient. |
| 643 | // There will be no memory write outside of the given fdt. |
| 644 | let ret = unsafe { |
| 645 | libfdt_bindgen::fdt_create_empty_tree( |
| 646 | fdt.as_mut_ptr().cast::<c_void>(), |
| 647 | fdt.len() as i32, |
| 648 | ) |
| 649 | }; |
| 650 | fdt_err_expect_zero(ret)?; |
| 651 | |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 652 | // SAFETY: The FDT will be validated before it is returned. |
Jaewan Kim | 4cf20aa | 2023-04-03 10:25:38 +0900 | [diff] [blame] | 653 | let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) }; |
| 654 | fdt.check_full()?; |
| 655 | |
| 656 | Ok(fdt) |
| 657 | } |
| 658 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 659 | /// Wraps a slice containing a Flattened Device Tree. |
| 660 | /// |
| 661 | /// # Safety |
| 662 | /// |
| 663 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 664 | pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 665 | // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is |
| 666 | // responsible for ensuring that it is actually a valid FDT. |
| 667 | unsafe { mem::transmute::<&[u8], &Self>(fdt) } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 668 | } |
| 669 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 670 | /// Wraps a mutable slice containing a Flattened Device Tree. |
| 671 | /// |
| 672 | /// # Safety |
| 673 | /// |
| 674 | /// The returned FDT might be invalid, only use on slices containing a valid DT. |
| 675 | pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 676 | // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is |
| 677 | // responsible for ensuring that it is actually a valid FDT. |
| 678 | unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 679 | } |
| 680 | |
Jiyong Park | e9d87e8 | 2023-03-21 19:28:40 +0900 | [diff] [blame] | 681 | /// Update this FDT from a slice containing another FDT |
| 682 | pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> { |
| 683 | if self.buffer.len() < new_fdt.len() { |
| 684 | Err(FdtError::NoSpace) |
| 685 | } else { |
| 686 | let totalsize = self.totalsize(); |
| 687 | self.buffer[..new_fdt.len()].clone_from_slice(new_fdt); |
| 688 | // Zeroize the remaining part. We zeroize up to the size of the original DT because |
| 689 | // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot |
| 690 | // time. |
| 691 | self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8); |
| 692 | Ok(()) |
| 693 | } |
| 694 | } |
| 695 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 696 | /// Make the whole slice containing the DT available to libfdt. |
| 697 | pub fn unpack(&mut self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 698 | // 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] | 699 | // internal structures to make use of the whole self.fdt slice but performs no accesses |
| 700 | // outside of it and leaves the DT in a state that will be detected by other functions. |
| 701 | let ret = unsafe { |
| 702 | libfdt_bindgen::fdt_open_into( |
| 703 | self.as_ptr(), |
| 704 | self.as_mut_ptr(), |
| 705 | self.capacity().try_into().map_err(|_| FdtError::Internal)?, |
| 706 | ) |
| 707 | }; |
| 708 | fdt_err_expect_zero(ret) |
| 709 | } |
| 710 | |
| 711 | /// Pack the DT to take a minimum amount of memory. |
| 712 | /// |
| 713 | /// Doesn't shrink the underlying memory slice. |
| 714 | pub fn pack(&mut self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 715 | // 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] | 716 | let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) }; |
| 717 | fdt_err_expect_zero(ret) |
| 718 | } |
| 719 | |
Pierre-Clément Tosi | 90e1935 | 2022-11-21 17:11:48 +0000 | [diff] [blame] | 720 | /// Applies a DT overlay on the base DT. |
| 721 | /// |
| 722 | /// # Safety |
| 723 | /// |
| 724 | /// On failure, the library corrupts the DT and overlay so both must be discarded. |
| 725 | 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] | 726 | let ret = |
| 727 | // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply |
| 728 | // doesn't keep them after it returns. It may corrupt their contents if there is an error, |
| 729 | // but that's our caller's responsibility. |
| 730 | unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) }; |
| 731 | fdt_err_expect_zero(ret)?; |
Pierre-Clément Tosi | 90e1935 | 2022-11-21 17:11:48 +0000 | [diff] [blame] | 732 | Ok(self) |
| 733 | } |
| 734 | |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 735 | /// Returns an iterator of memory banks specified the "/memory" node. |
| 736 | /// 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] | 737 | /// |
| 738 | /// NOTE: This does not support individual "/memory@XXXX" banks. |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 739 | pub fn memory(&self) -> Result<MemRegIterator> { |
| 740 | let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap(); |
| 741 | let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap(); |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 742 | |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 743 | let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?; |
| 744 | if node.device_type()? != Some(memory_device_type) { |
| 745 | return Err(FdtError::BadValue); |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 746 | } |
Alice Wang | 2422bdc | 2023-06-12 08:37:55 +0000 | [diff] [blame] | 747 | node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new) |
| 748 | } |
| 749 | |
| 750 | /// Returns the first memory range in the `/memory` node. |
| 751 | pub fn first_memory_range(&self) -> Result<Range<usize>> { |
| 752 | self.memory()?.next().ok_or(FdtError::NotFound) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 753 | } |
| 754 | |
| 755 | /// Retrieve the standard /chosen node. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 756 | pub fn chosen(&self) -> Result<Option<FdtNode>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 757 | self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap()) |
| 758 | } |
| 759 | |
Pierre-Clément Tosi | 4ba7966 | 2023-02-13 11:22:41 +0000 | [diff] [blame] | 760 | /// Retrieve the standard /chosen node as mutable. |
| 761 | pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> { |
| 762 | self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap()) |
| 763 | } |
| 764 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 765 | /// Get the root node of the tree. |
| 766 | pub fn root(&self) -> Result<FdtNode> { |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 767 | self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal) |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 768 | } |
| 769 | |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 770 | /// Find a tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 771 | pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> { |
| 772 | Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset })) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 773 | } |
| 774 | |
Pierre-Clément Tosi | 41c158e | 2022-11-21 19:16:25 +0000 | [diff] [blame] | 775 | /// Iterate over nodes with a given compatible string. |
| 776 | pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> { |
| 777 | CompatibleIterator::new(self, compatible) |
| 778 | } |
| 779 | |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 780 | /// Get the mutable root node of the tree. |
| 781 | pub fn root_mut(&mut self) -> Result<FdtNodeMut> { |
| 782 | self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal) |
| 783 | } |
| 784 | |
| 785 | /// Find a mutable tree node by its full path. |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 786 | pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> { |
| 787 | Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset })) |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 788 | } |
| 789 | |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 790 | /// Return the device tree as a slice (may be smaller than the containing buffer). |
| 791 | pub fn as_slice(&self) -> &[u8] { |
| 792 | &self.buffer[..self.totalsize()] |
| 793 | } |
| 794 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 795 | fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> { |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 796 | let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?; |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 797 | // 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] | 798 | // function respects the passed number of characters. |
| 799 | let ret = unsafe { |
| 800 | // *_namelen functions don't include the trailing nul terminator in 'len'. |
| 801 | libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len) |
| 802 | }; |
| 803 | |
Pierre-Clément Tosi | b244d93 | 2022-11-24 16:45:53 +0000 | [diff] [blame] | 804 | fdt_err_or_option(ret) |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 805 | } |
| 806 | |
| 807 | fn check_full(&self) -> Result<()> { |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 808 | // 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] | 809 | // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t. |
| 810 | // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds |
| 811 | // checking. The library doesn't maintain an internal state (such as pointers) between |
| 812 | // 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] | 813 | 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] | 814 | fdt_err_expect_zero(ret) |
| 815 | } |
| 816 | |
Jaewan Kim | aa63870 | 2023-09-19 13:34:01 +0900 | [diff] [blame] | 817 | fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> { |
| 818 | let ptr = ptr as usize; |
| 819 | let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?; |
| 820 | self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal) |
| 821 | } |
| 822 | |
Pierre-Clément Tosi | 8036b4f | 2023-02-17 10:31:31 +0000 | [diff] [blame] | 823 | /// Return a shared pointer to the device tree. |
| 824 | pub fn as_ptr(&self) -> *const c_void { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 825 | self.buffer.as_ptr().cast::<_>() |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 826 | } |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 827 | |
| 828 | fn as_mut_ptr(&mut self) -> *mut c_void { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 829 | self.buffer.as_mut_ptr().cast::<_>() |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 830 | } |
| 831 | |
| 832 | fn capacity(&self) -> usize { |
Pierre-Clément Tosi | ef2030e | 2022-11-28 11:21:20 +0000 | [diff] [blame] | 833 | self.buffer.len() |
Pierre-Clément Tosi | 1b0d890 | 2022-11-21 18:16:59 +0000 | [diff] [blame] | 834 | } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 835 | |
| 836 | fn header(&self) -> &libfdt_bindgen::fdt_header { |
Pierre-Clément Tosi | 0dcc75e | 2023-05-02 13:43:55 +0000 | [diff] [blame] | 837 | let p = self.as_ptr().cast::<_>(); |
Andrew Walbran | 84b9a23 | 2023-07-05 14:01:40 +0000 | [diff] [blame] | 838 | // 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] | 839 | unsafe { &*p } |
Pierre-Clément Tosi | db74cb1 | 2022-12-08 13:56:25 +0000 | [diff] [blame] | 840 | } |
| 841 | |
| 842 | fn totalsize(&self) -> usize { |
| 843 | u32::from_be(self.header().totalsize) as usize |
| 844 | } |
David Brazdil | 1baa9a9 | 2022-06-28 14:47:50 +0100 | [diff] [blame] | 845 | } |