blob: 1d295ebcbc4ff206e381acccf563e6ce236f2838 [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
Jaewan Kimba8929b2023-01-13 11:13:29 +0900391 /// Create or change a property name-value pair to the given node.
392 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
393 // SAFETY - New value size is constrained to the DT totalsize
394 // (validated by underlying libfdt).
395 let ret = unsafe {
396 libfdt_bindgen::fdt_setprop(
397 self.fdt.as_mut_ptr(),
398 self.offset,
399 name.as_ptr(),
400 value.as_ptr().cast::<c_void>(),
401 value.len().try_into().map_err(|_| FdtError::BadValue)?,
402 )
403 };
404
405 fdt_err_expect_zero(ret)
406 }
407
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000408 /// Create or change a flag-like empty property.
409 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
410 self.setprop(name, &[])
411 }
412
413 /// Delete the given property.
414 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
415 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) when the
416 // library locates the node's property. Removing the property may shift the offsets of
417 // other nodes and properties but the borrow checker should prevent this function from
418 // being called when FdtNode instances are in use.
419 let ret = unsafe {
420 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
421 };
422
423 fdt_err_expect_zero(ret)
424 }
425
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000426 /// Get reference to the containing device tree.
427 pub fn fdt(&mut self) -> &mut Fdt {
428 self.fdt
429 }
430
431 /// Add a new subnode to the given node and return it as a FdtNodeMut on success.
432 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
433 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
434 let ret = unsafe {
435 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
436 };
437
438 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
439 }
440
441 fn parent(&'a self) -> Result<FdtNode<'a>> {
442 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
443 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
444
445 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
446 }
447}
448
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000449/// Iterator over nodes sharing a same compatible string.
450pub struct CompatibleIterator<'a> {
451 node: FdtNode<'a>,
452 compatible: &'a CStr,
453}
454
455impl<'a> CompatibleIterator<'a> {
456 fn new(fdt: &'a Fdt, compatible: &'a CStr) -> Result<Self> {
457 let node = fdt.root()?;
458 Ok(Self { node, compatible })
459 }
460}
461
462impl<'a> Iterator for CompatibleIterator<'a> {
463 type Item = FdtNode<'a>;
464
465 fn next(&mut self) -> Option<Self::Item> {
466 let next = self.node.next_compatible(self.compatible).ok()?;
467
468 if let Some(node) = next {
469 self.node = node;
470 }
471
472 next
473 }
474}
475
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000476/// Wrapper around low-level libfdt functions.
David Brazdil1baa9a92022-06-28 14:47:50 +0100477#[repr(transparent)]
478pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000479 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100480}
481
482impl Fdt {
483 /// Wraps a slice containing a Flattened Device Tree.
484 ///
485 /// Fails if the FDT does not pass validation.
486 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
487 // SAFETY - The FDT will be validated before it is returned.
488 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
489 fdt.check_full()?;
490 Ok(fdt)
491 }
492
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000493 /// Wraps a mutable slice containing a Flattened Device Tree.
494 ///
495 /// Fails if the FDT does not pass validation.
496 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
497 // SAFETY - The FDT will be validated before it is returned.
498 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
499 fdt.check_full()?;
500 Ok(fdt)
501 }
502
David Brazdil1baa9a92022-06-28 14:47:50 +0100503 /// Wraps a slice containing a Flattened Device Tree.
504 ///
505 /// # Safety
506 ///
507 /// The returned FDT might be invalid, only use on slices containing a valid DT.
508 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
509 mem::transmute::<&[u8], &Self>(fdt)
510 }
511
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000512 /// Wraps a mutable slice containing a Flattened Device Tree.
513 ///
514 /// # Safety
515 ///
516 /// The returned FDT might be invalid, only use on slices containing a valid DT.
517 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
518 mem::transmute::<&mut [u8], &mut Self>(fdt)
519 }
520
521 /// Make the whole slice containing the DT available to libfdt.
522 pub fn unpack(&mut self) -> Result<()> {
523 // SAFETY - "Opens" the DT in-place (supported use-case) by updating its header and
524 // internal structures to make use of the whole self.fdt slice but performs no accesses
525 // outside of it and leaves the DT in a state that will be detected by other functions.
526 let ret = unsafe {
527 libfdt_bindgen::fdt_open_into(
528 self.as_ptr(),
529 self.as_mut_ptr(),
530 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
531 )
532 };
533 fdt_err_expect_zero(ret)
534 }
535
536 /// Pack the DT to take a minimum amount of memory.
537 ///
538 /// Doesn't shrink the underlying memory slice.
539 pub fn pack(&mut self) -> Result<()> {
540 // SAFETY - "Closes" the DT in-place by updating its header and relocating its structs.
541 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
542 fdt_err_expect_zero(ret)
543 }
544
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000545 /// Applies a DT overlay on the base DT.
546 ///
547 /// # Safety
548 ///
549 /// On failure, the library corrupts the DT and overlay so both must be discarded.
550 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
551 fdt_err_expect_zero(libfdt_bindgen::fdt_overlay_apply(
552 self.as_mut_ptr(),
553 overlay.as_mut_ptr(),
554 ))?;
555 Ok(self)
556 }
557
David Brazdil1baa9a92022-06-28 14:47:50 +0100558 /// Return an iterator of memory banks specified the "/memory" node.
559 ///
560 /// NOTE: This does not support individual "/memory@XXXX" banks.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000561 pub fn memory(&self) -> Result<Option<MemRegIterator>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100562 let memory = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
563 let device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
564
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000565 if let Some(node) = self.node(memory)? {
566 if node.device_type()? != Some(device_type) {
567 return Err(FdtError::BadValue);
568 }
569 let reg = node.reg()?.ok_or(FdtError::BadValue)?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100570
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000571 Ok(Some(MemRegIterator::new(reg)))
572 } else {
573 Ok(None)
574 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100575 }
576
577 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000578 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100579 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
580 }
581
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000582 /// Retrieve the standard /chosen node as mutable.
583 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
584 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
585 }
586
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000587 /// Get the root node of the tree.
588 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000589 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000590 }
591
David Brazdil1baa9a92022-06-28 14:47:50 +0100592 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000593 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
594 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100595 }
596
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000597 /// Iterate over nodes with a given compatible string.
598 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
599 CompatibleIterator::new(self, compatible)
600 }
601
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000602 /// Get the mutable root node of the tree.
603 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
604 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
605 }
606
607 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000608 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
609 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000610 }
611
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000612 /// Return the device tree as a slice (may be smaller than the containing buffer).
613 pub fn as_slice(&self) -> &[u8] {
614 &self.buffer[..self.totalsize()]
615 }
616
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000617 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100618 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
619 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) and the
620 // function respects the passed number of characters.
621 let ret = unsafe {
622 // *_namelen functions don't include the trailing nul terminator in 'len'.
623 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
624 };
625
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000626 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100627 }
628
629 fn check_full(&self) -> Result<()> {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000630 let len = self.buffer.len();
David Brazdil1baa9a92022-06-28 14:47:50 +0100631 // SAFETY - Only performs read accesses within the limits of the slice. If successful, this
632 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
633 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
634 // checking. The library doesn't maintain an internal state (such as pointers) between
635 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
636 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) };
637 fdt_err_expect_zero(ret)
638 }
639
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000640 /// Return a shared pointer to the device tree.
641 pub fn as_ptr(&self) -> *const c_void {
David Brazdil1baa9a92022-06-28 14:47:50 +0100642 self as *const _ as *const c_void
643 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000644
645 fn as_mut_ptr(&mut self) -> *mut c_void {
646 self as *mut _ as *mut c_void
647 }
648
649 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000650 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000651 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000652
653 fn header(&self) -> &libfdt_bindgen::fdt_header {
654 // SAFETY - A valid FDT (verified by constructor) must contain a valid fdt_header.
655 unsafe { &*(&self as *const _ as *const libfdt_bindgen::fdt_header) }
656 }
657
658 fn totalsize(&self) -> usize {
659 u32::from_be(self.header().totalsize) as usize
660 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100661}