blob: 39749f0f8bac095ffb860530e1259f8e11f92290 [file] [log] [blame]
David Brazdil1baa9a92022-06-28 14:47:50 +01001// 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 Walbran55ad01b2022-12-05 17:00:40 +000020mod iterators;
21
Jaewan Kimfe06c852023-10-05 23:40:06 +090022pub use iterators::{
Jaewan Kimc9e14112023-12-04 17:05:27 +090023 AddressRange, CellIterator, CompatibleIterator, DescendantsIterator, MemRegIterator,
24 PropertyIterator, RangesIterator, Reg, RegIterator, SubnodeIterator,
Jaewan Kimfe06c852023-10-05 23:40:06 +090025};
Andrew Walbran55ad01b2022-12-05 17:00:40 +000026
David Brazdil1baa9a92022-06-28 14:47:50 +010027use core::ffi::{c_int, c_void, CStr};
28use core::fmt;
Alice Wang2422bdc2023-06-12 08:37:55 +000029use core::ops::Range;
Jaewan Kim5b057772023-10-19 01:02:17 +090030use core::ptr;
David Brazdil1baa9a92022-06-28 14:47:50 +010031use core::result;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000032use cstr::cstr;
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000033use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010034
35/// Error type corresponding to libfdt error codes.
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub 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
80impl 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.
109pub type Result<T> = result::Result<T, FdtError>;
110
111fn 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
140fn 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 Tosib244d932022-11-24 16:45:53 +0000147fn 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 Brazdil1baa9a92022-06-28 14:47:50 +0100155/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000156#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100157enum AddrCells {
158 Single = 1,
159 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000160 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100161}
162
163impl 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 Walbranb39e6922022-12-05 17:01:20 +0000170 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100171 _ => Err(FdtError::BadNCells),
172 }
173 }
174}
175
176/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000177#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100178enum SizeCells {
179 None = 0,
180 Single = 1,
181 Double = 2,
182}
183
184impl 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 Kim72d10902023-10-12 21:59:26 +0900197/// DT property wrapper to abstract endianess changes
198#[repr(transparent)]
199#[derive(Debug)]
200struct FdtPropertyStruct(libfdt_bindgen::fdt_property);
201
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000202impl 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 Kim72d10902023-10-12 21:59:26 +0900210impl 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 Tosidf3037f2024-01-22 15:41:43 +0000221 let prop = unsafe { &*prop };
222 Ok(prop.as_ref())
Jaewan Kim72d10902023-10-12 21:59:26 +0900223 }
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)]
240pub struct FdtProperty<'a> {
241 fdt: &'a Fdt,
242 offset: c_int,
243 property: &'a FdtPropertyStruct,
244}
245
246impl<'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 Brazdil1baa9a92022-06-28 14:47:50 +0100271/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000272#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100273pub struct FdtNode<'a> {
274 fdt: &'a Fdt,
275 offset: c_int,
276}
277
278impl<'a> FdtNode<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900279 /// Creates immutable node from a mutable node at the same offset.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900280 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
281 FdtNode { fdt: other.fdt, offset: other.offset }
282 }
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900283 /// Returns parent node.
David Brazdil1baa9a92022-06-28 14:47:50 +0100284 pub fn parent(&self) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000285 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100286 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 Kim5b057772023-10-19 01:02:17 +0900291 /// 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 Kimb3dcfc22023-09-20 10:20:52 +0900306 /// Returns the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000307 pub fn device_type(&self) -> Result<Option<&CStr>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900308 self.getprop_str(cstr!("device_type"))
David Brazdil1baa9a92022-06-28 14:47:50 +0100309 }
310
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900311 /// Returns the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000312 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900313 let reg = cstr!("reg");
David Brazdil1baa9a92022-06-28 14:47:50 +0100314
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000315 if let Some(cells) = self.getprop_cells(reg)? {
316 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100317
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000318 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 Brazdil1baa9a92022-06-28 14:47:50 +0100325 }
326
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900327 /// Returns the standard ranges property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000328 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900329 let ranges = cstr!("ranges");
Andrew Walbranb39e6922022-12-05 17:01:20 +0000330 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 Kimaa638702023-09-19 13:34:01 +0900346 /// 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 Kimb3dcfc22023-09-20 10:20:52 +0900358 /// Returns the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000359 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 Brazdil1baa9a92022-06-28 14:47:50 +0100366 }
367
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900368 /// Returns the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000369 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 Brazdil1baa9a92022-06-28 14:47:50 +0100375 }
376
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900377 /// Returns the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000378 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 Brazdil1baa9a92022-06-28 14:47:50 +0100385 }
386
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900387 /// Returns the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000388 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 Brazdil1baa9a92022-06-28 14:47:50 +0100395 }
396
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900397 /// Returns the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000398 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900399 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900400 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900401 } else {
402 Ok(None) // property was not found
403 }
404 }
405
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900406 /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in
Jiyong Park9c63cd12023-03-21 17:53:07 +0900407 /// 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 Brazdil1baa9a92022-06-28 14:47:50 +0100413 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000414 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100415 // function respects the passed number of characters.
416 let prop = unsafe {
417 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900418 fdt.as_ptr(),
419 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100420 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 Tosib244d932022-11-24 16:45:53 +0000426
427 let Some(len) = fdt_err_or_option(len)? else {
428 return Ok(None); // Property was not found.
429 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900430 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000431
David Brazdil1baa9a92022-06-28 14:47:50 +0100432 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000433 // We expected an error code in len but still received a valid value?!
434 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100435 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900436 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100437 }
438
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900439 /// Returns reference to the containing device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100440 pub fn fdt(&self) -> &Fdt {
441 self.fdt
442 }
443
Alice Wang474c0ee2023-09-14 12:52:33 +0000444 /// 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 Walbran84b9a232023-07-05 14:01:40 +0000446 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000447 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 Tosib244d932022-11-24 16:45:53 +0000455 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000456 }
457
Alice Wang474c0ee2023-09-14 12:52:33 +0000458 /// 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 Brazdil1baa9a92022-06-28 14:47:50 +0100463 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000464 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100465 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 Walbran84b9a232023-07-05 14:01:40 +0000471 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100472 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
473 .try_into()
474 .map_err(|_| FdtError::Internal)
475 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900476
477 /// Returns an iterator of subnodes
Jaewan Kim4a34b0d2024-01-19 13:17:47 +0900478 pub fn subnodes(&self) -> Result<SubnodeIterator<'a>> {
Jaewan Kimbc828d72023-09-19 15:52:08 +0900479 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 Kim72d10902023-10-12 21:59:26 +0900495
Jaewan Kimc9e14112023-12-04 17:05:27 +0900496 /// Returns an iterator of descendants
Jaewan Kim1eab7232024-01-04 09:46:16 +0900497 pub fn descendants(&self) -> DescendantsIterator<'a> {
Jaewan Kimc9e14112023-12-04 17:05:27 +0900498 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 Kim72d10902023-10-12 21:59:26 +0900513 /// 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 Kimf34f4b82023-11-03 19:38:38 +0900525
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 Kim52026012023-12-13 13:49:28 +0900537
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 Brazdil1baa9a92022-06-28 14:47:50 +0100563}
564
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000565impl<'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 Kim17ba7a32023-10-19 13:25:15 +0900571/// Phandle of a FDT node
572#[repr(transparent)]
Jaewan Kim55f438c2023-11-15 01:24:36 +0900573#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900574pub struct Phandle(u32);
575
576impl Phandle {
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000577 /// 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 Kim17ba7a32023-10-19 13:25:15 +0900582 /// Creates a new Phandle
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000583 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 Kim17ba7a32023-10-19 13:25:15 +0900588 }
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900589 }
590}
591
592impl From<Phandle> for u32 {
593 fn from(phandle: Phandle) -> u32 {
594 phandle.0
595 }
596}
597
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000598impl 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 Tosi1b0d8902022-11-21 18:16:59 +0000606/// Mutable FDT node.
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000607#[derive(Debug)]
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000608pub struct FdtNodeMut<'a> {
609 fdt: &'a mut Fdt,
610 offset: c_int,
611}
612
613impl<'a> FdtNodeMut<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900614 /// Appends a property name-value (possibly empty) pair to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000615 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000616 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000617 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 Kimb3dcfc22023-09-20 10:20:52 +0900630 /// Appends a (address, size) pair property to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000631 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000632 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000633 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 Kimb3dcfc22023-09-20 10:20:52 +0900647 /// Sets a property name-value pair to the given node.
648 ///
649 /// This may create a new prop or replace existing value.
Jaewan Kimba8929b2023-01-13 11:13:29 +0900650 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000651 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900652 // (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 Kimb3dcfc22023-09-20 10:20:52 +0900666 /// 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 Park9c63cd12023-03-21 17:53:07 +0900670 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000671 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900672 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 Kimb3dcfc22023-09-20 10:20:52 +0900685 /// 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 Tosic27c4272023-05-19 15:46:26 +0000689 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 Kimb3dcfc22023-09-20 10:20:52 +0900694 /// Sets a flag-like empty property.
695 ///
696 /// This may create a new prop or replace existing value.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000697 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
698 self.setprop(name, &[])
699 }
700
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900701 /// Deletes the given property.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000702 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000703 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000704 // 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 Kim4ae0e712023-10-19 14:16:17 +0900714 /// Deletes the given property effectively from DT, by setting it with FDT_NOP.
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000715 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000716 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000717 // 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 Kimb3dcfc22023-09-20 10:20:52 +0900725 /// Trims the size of the given property to new_size.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900726 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 Walbran84b9a232023-07-05 14:01:40 +0000736 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900737 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 Kimb3dcfc22023-09-20 10:20:52 +0900750 /// Returns reference to the containing device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000751 pub fn fdt(&mut self) -> &mut Fdt {
752 self.fdt
753 }
754
Jaewan Kimf72f4f22023-11-03 19:21:34 +0900755 /// Returns immutable FdtNode of this node.
756 pub fn as_node(&self) -> FdtNode {
757 FdtNode { fdt: self.fdt, offset: self.offset }
758 }
759
Jaewan Kime6363422024-01-19 14:00:00 +0900760 /// 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 Kimb3dcfc22023-09-20 10:20:52 +0900768 /// Adds a new subnode to the given node and return it as a FdtNodeMut on success.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000769 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900770 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 Walbran84b9a232023-07-05 14:01:40 +0000783 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000784 let ret = unsafe {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900785 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 Tosi1b0d8902022-11-21 18:16:59 +0000791 };
Jaewan Kim5ab13582023-10-20 20:56:27 +0900792 fdt_err(ret)
793 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000794
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900795 /// 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 Kim28a13ea2024-01-04 09:22:40 +0900829 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 Tosi1b0d8902022-11-21 18:16:59 +0000864 fn parent(&'a self) -> Result<FdtNode<'a>> {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000865 self.as_node().parent()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000866 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900867
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900868 /// Returns the compatible node of the given name that is next after this node.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900869 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000870 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900871 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 Kimb3dcfc22023-09-20 10:20:52 +0900882 /// 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 Park9c63cd12023-03-21 17:53:07 +0900884 // 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 Kim4ae0e712023-10-19 14:16:17 +0900894 pub fn delete_and_next_compatible(mut self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000895 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900896 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 Kim4ae0e712023-10-19 14:16:17 +0900905 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 Park9c63cd12023-03-21 17:53:07 +0900912
913 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
914 }
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900915
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 Tosi1b0d8902022-11-21 18:16:59 +0000932}
933
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000934/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000935#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100936#[repr(transparent)]
937pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000938 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100939}
940
941impl 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 Walbran84b9a232023-07-05 14:01:40 +0000946 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100947 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
948 fdt.check_full()?;
949 Ok(fdt)
950 }
951
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000952 /// 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 Walbran84b9a232023-07-05 14:01:40 +0000956 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000957 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
958 fdt.check_full()?;
959 Ok(fdt)
960 }
961
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900962 /// Creates an empty Flattened Device Tree with a mutable slice.
963 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000964 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900965 // 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 Walbran84b9a232023-07-05 14:01:40 +0000975 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900976 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
977 fdt.check_full()?;
978
979 Ok(fdt)
980 }
981
David Brazdil1baa9a92022-06-28 14:47:50 +0100982 /// Wraps a slice containing a Flattened Device Tree.
983 ///
984 /// # Safety
985 ///
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000986 /// It is undefined to call this function on a slice that does not contain a valid device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100987 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000988 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 Brazdil1baa9a92022-06-28 14:47:50 +0100991 }
992
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000993 /// Wraps a mutable slice containing a Flattened Device Tree.
994 ///
995 /// # Safety
996 ///
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000997 /// It is undefined to call this function on a slice that does not contain a valid device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000998 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000999 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 Tosi1b0d8902022-11-21 18:16:59 +00001002 }
1003
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001004 /// 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 Parke9d87e82023-03-21 19:28:40 +09001009 }
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +00001010
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 Parke9d87e82023-03-21 19:28:40 +09001020 }
1021
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001022 /// Unpacks the DT to cover the whole slice it is contained in.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001023 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +00001024 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001025 // 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 Kimb3dcfc22023-09-20 10:20:52 +09001037 /// Packs the DT to take a minimum amount of memory.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001038 ///
1039 /// Doesn't shrink the underlying memory slice.
1040 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +00001041 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001042 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
1043 fdt_err_expect_zero(ret)
1044 }
1045
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +00001046 /// 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 Walbran84b9a232023-07-05 14:01:40 +00001052 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 Tosi90e19352022-11-21 17:11:48 +00001058 Ok(self)
1059 }
1060
Alice Wang2422bdc2023-06-12 08:37:55 +00001061 /// 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 Brazdil1baa9a92022-06-28 14:47:50 +01001063 ///
1064 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +00001065 pub fn memory(&self) -> Result<MemRegIterator> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001066 let memory_node_name = cstr!("/memory");
1067 let memory_device_type = cstr!("memory");
David Brazdil1baa9a92022-06-28 14:47:50 +01001068
Alice Wang2422bdc2023-06-12 08:37:55 +00001069 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 Tosib244d932022-11-24 16:45:53 +00001072 }
Alice Wang2422bdc2023-06-12 08:37:55 +00001073 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 Brazdil1baa9a92022-06-28 14:47:50 +01001079 }
1080
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001081 /// Returns the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001082 pub fn chosen(&self) -> Result<Option<FdtNode>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001083 self.node(cstr!("/chosen"))
David Brazdil1baa9a92022-06-28 14:47:50 +01001084 }
1085
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001086 /// Returns the standard /chosen node as mutable.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001087 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001088 self.node_mut(cstr!("/chosen"))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +00001089 }
1090
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001091 /// Returns the root node of the tree.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +00001092 pub fn root(&self) -> Result<FdtNode> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001093 self.node(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +00001094 }
1095
Jaewan Kimf163d762023-11-01 13:12:50 +09001096 /// 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 Kimb3dcfc22023-09-20 10:20:52 +09001106 /// Returns a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001107 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
Jaewan Kimbab42592023-10-13 15:47:19 +09001108 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +01001109 }
1110
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +00001111 /// 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 Kim17ba7a32023-10-19 13:25:15 +09001116 /// 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 Tosieba27792023-10-30 12:04:12 +00001123 phandle.try_into()
Jaewan Kim17ba7a32023-10-19 13:25:15 +09001124 }
1125
1126 /// Returns a node with the phandle
1127 pub fn node_with_phandle(&self, phandle: Phandle) -> Result<Option<FdtNode>> {
Jaewan Kimc63246d2023-11-09 15:41:01 +09001128 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 Kim17ba7a32023-10-19 13:25:15 +09001140 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(self.as_ptr(), phandle.0) };
Jaewan Kimc63246d2023-11-09 15:41:01 +09001141 fdt_err_or_option(ret)
Jaewan Kim17ba7a32023-10-19 13:25:15 +09001142 }
1143
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001144 /// Returns the mutable root node of the tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001145 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001146 self.node_mut(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001147 }
1148
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001149 /// Returns a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001150 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
Jaewan Kimbab42592023-10-13 15:47:19 +09001151 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001152 }
1153
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001154 /// Returns the device tree as a slice (may be smaller than the containing buffer).
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001155 pub fn as_slice(&self) -> &[u8] {
1156 &self.buffer[..self.totalsize()]
1157 }
1158
Jaewan Kimbab42592023-10-13 15:47:19 +09001159 fn path_offset(&self, path: &[u8]) -> Result<Option<c_int>> {
1160 let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +00001161 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +01001162 // function respects the passed number of characters.
1163 let ret = unsafe {
1164 // *_namelen functions don't include the trailing nul terminator in 'len'.
Jaewan Kimbab42592023-10-13 15:47:19 +09001165 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr().cast::<_>(), len)
David Brazdil1baa9a92022-06-28 14:47:50 +01001166 };
1167
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001168 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +01001169 }
1170
1171 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +00001172 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +01001173 // 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 Tosi02017da2023-09-26 17:57:04 +01001177 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +01001178 fdt_err_expect_zero(ret)
1179 }
1180
Jaewan Kimaa638702023-09-19 13:34:01 +09001181 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 Kim72d10902023-10-12 21:59:26 +09001187 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 Kimb3dcfc22023-09-20 10:20:52 +09001198 /// Returns a shared pointer to the device tree.
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +00001199 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001200 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +01001201 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001202
1203 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001204 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001205 }
1206
1207 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +00001208 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001209 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001210
1211 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001212 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +00001213 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001214 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001215 }
1216
1217 fn totalsize(&self) -> usize {
1218 u32::from_be(self.header().totalsize) as usize
1219 }
David Brazdil1baa9a92022-06-28 14:47:50 +01001220}