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