blob: d800c13f5e3c133508b1ba7ee3272b160a8a87f1 [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 Kim72d10902023-10-12 21:59:26 +090023 AddressRange, CellIterator, CompatibleIterator, MemRegIterator, PropertyIterator,
24 RangesIterator, Reg, RegIterator, SubnodeIterator,
Jaewan Kimfe06c852023-10-05 23:40:06 +090025};
Andrew Walbran55ad01b2022-12-05 17:00:40 +000026
Jiyong Parke9d87e82023-03-21 19:28:40 +090027use core::cmp::max;
David Brazdil1baa9a92022-06-28 14:47:50 +010028use core::ffi::{c_int, c_void, CStr};
29use core::fmt;
30use core::mem;
Alice Wang2422bdc2023-06-12 08:37:55 +000031use core::ops::Range;
Jaewan Kim5b057772023-10-19 01:02:17 +090032use core::ptr;
David Brazdil1baa9a92022-06-28 14:47:50 +010033use core::result;
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000034use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010035
36/// Error type corresponding to libfdt error codes.
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum FdtError {
39 /// FDT_ERR_NOTFOUND
40 NotFound,
41 /// FDT_ERR_EXISTS
42 Exists,
43 /// FDT_ERR_NOSPACE
44 NoSpace,
45 /// FDT_ERR_BADOFFSET
46 BadOffset,
47 /// FDT_ERR_BADPATH
48 BadPath,
49 /// FDT_ERR_BADPHANDLE
50 BadPhandle,
51 /// FDT_ERR_BADSTATE
52 BadState,
53 /// FDT_ERR_TRUNCATED
54 Truncated,
55 /// FDT_ERR_BADMAGIC
56 BadMagic,
57 /// FDT_ERR_BADVERSION
58 BadVersion,
59 /// FDT_ERR_BADSTRUCTURE
60 BadStructure,
61 /// FDT_ERR_BADLAYOUT
62 BadLayout,
63 /// FDT_ERR_INTERNAL
64 Internal,
65 /// FDT_ERR_BADNCELLS
66 BadNCells,
67 /// FDT_ERR_BADVALUE
68 BadValue,
69 /// FDT_ERR_BADOVERLAY
70 BadOverlay,
71 /// FDT_ERR_NOPHANDLES
72 NoPhandles,
73 /// FDT_ERR_BADFLAGS
74 BadFlags,
75 /// FDT_ERR_ALIGNMENT
76 Alignment,
77 /// Unexpected error code
78 Unknown(i32),
79}
80
81impl fmt::Display for FdtError {
82 /// Prints error messages from libfdt.h documentation.
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 match self {
85 Self::NotFound => write!(f, "The requested node or property does not exist"),
86 Self::Exists => write!(f, "Attempted to create an existing node or property"),
87 Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"),
88 Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"),
89 Self::BadPath => write!(f, "Badly formatted path"),
90 Self::BadPhandle => write!(f, "Invalid phandle length or value"),
91 Self::BadState => write!(f, "Received incomplete device tree"),
92 Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"),
93 Self::BadMagic => write!(f, "Device tree header missing its magic number"),
94 Self::BadVersion => write!(f, "Device tree has a version which can't be handled"),
95 Self::BadStructure => write!(f, "Device tree has a corrupt structure block"),
96 Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"),
97 Self::Internal => write!(f, "libfdt has failed an internal assertion"),
98 Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"),
99 Self::BadValue => write!(f, "Unexpected property value"),
100 Self::BadOverlay => write!(f, "Overlay cannot be applied"),
101 Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"),
102 Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"),
103 Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"),
104 Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"),
105 }
106 }
107}
108
109/// Result type with FdtError enum.
110pub type Result<T> = result::Result<T, FdtError>;
111
112fn fdt_err(val: c_int) -> Result<c_int> {
113 if val >= 0 {
114 Ok(val)
115 } else {
116 Err(match -val as _ {
117 libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound,
118 libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists,
119 libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace,
120 libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset,
121 libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath,
122 libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle,
123 libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState,
124 libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated,
125 libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic,
126 libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion,
127 libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure,
128 libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout,
129 libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal,
130 libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells,
131 libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue,
132 libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay,
133 libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles,
134 libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags,
135 libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment,
136 _ => FdtError::Unknown(val),
137 })
138 }
139}
140
141fn fdt_err_expect_zero(val: c_int) -> Result<()> {
142 match fdt_err(val)? {
143 0 => Ok(()),
144 _ => Err(FdtError::Unknown(val)),
145 }
146}
147
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000148fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> {
149 match fdt_err(val) {
150 Ok(val) => Ok(Some(val)),
151 Err(FdtError::NotFound) => Ok(None),
152 Err(e) => Err(e),
153 }
154}
155
David Brazdil1baa9a92022-06-28 14:47:50 +0100156/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000157#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100158enum AddrCells {
159 Single = 1,
160 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000161 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100162}
163
164impl TryFrom<c_int> for AddrCells {
165 type Error = FdtError;
166
167 fn try_from(res: c_int) -> Result<Self> {
168 match fdt_err(res)? {
169 x if x == Self::Single as c_int => Ok(Self::Single),
170 x if x == Self::Double as c_int => Ok(Self::Double),
Andrew Walbranb39e6922022-12-05 17:01:20 +0000171 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100172 _ => Err(FdtError::BadNCells),
173 }
174 }
175}
176
177/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000178#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100179enum SizeCells {
180 None = 0,
181 Single = 1,
182 Double = 2,
183}
184
185impl TryFrom<c_int> for SizeCells {
186 type Error = FdtError;
187
188 fn try_from(res: c_int) -> Result<Self> {
189 match fdt_err(res)? {
190 x if x == Self::None as c_int => Ok(Self::None),
191 x if x == Self::Single as c_int => Ok(Self::Single),
192 x if x == Self::Double as c_int => Ok(Self::Double),
193 _ => Err(FdtError::BadNCells),
194 }
195 }
196}
197
Jaewan Kim72d10902023-10-12 21:59:26 +0900198/// DT property wrapper to abstract endianess changes
199#[repr(transparent)]
200#[derive(Debug)]
201struct FdtPropertyStruct(libfdt_bindgen::fdt_property);
202
203impl FdtPropertyStruct {
204 fn from_offset(fdt: &Fdt, offset: c_int) -> Result<&Self> {
205 let mut len = 0;
206 let prop =
207 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
208 unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt.as_ptr(), offset, &mut len) };
209 if prop.is_null() {
210 fdt_err(len)?;
211 return Err(FdtError::Internal); // shouldn't happen.
212 }
213 // SAFETY: prop is only returned when it points to valid libfdt_bindgen.
214 Ok(unsafe { &*prop.cast::<FdtPropertyStruct>() })
215 }
216
217 fn name_offset(&self) -> c_int {
218 u32::from_be(self.0.nameoff).try_into().unwrap()
219 }
220
221 fn data_len(&self) -> usize {
222 u32::from_be(self.0.len).try_into().unwrap()
223 }
224
225 fn data_ptr(&self) -> *const c_void {
226 self.0.data.as_ptr().cast::<_>()
227 }
228}
229
230/// DT property.
231#[derive(Clone, Copy, Debug)]
232pub struct FdtProperty<'a> {
233 fdt: &'a Fdt,
234 offset: c_int,
235 property: &'a FdtPropertyStruct,
236}
237
238impl<'a> FdtProperty<'a> {
239 fn new(fdt: &'a Fdt, offset: c_int) -> Result<Self> {
240 let property = FdtPropertyStruct::from_offset(fdt, offset)?;
241 Ok(Self { fdt, offset, property })
242 }
243
244 /// Returns the property name
245 pub fn name(&self) -> Result<&'a CStr> {
246 self.fdt.string(self.property.name_offset())
247 }
248
249 /// Returns the property value
250 pub fn value(&self) -> Result<&'a [u8]> {
251 self.fdt.get_from_ptr(self.property.data_ptr(), self.property.data_len())
252 }
253
254 fn next_property(&self) -> Result<Option<Self>> {
255 let ret =
256 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
257 unsafe { libfdt_bindgen::fdt_next_property_offset(self.fdt.as_ptr(), self.offset) };
258
259 fdt_err_or_option(ret)?.map(|offset| Self::new(self.fdt, offset)).transpose()
260 }
261}
262
David Brazdil1baa9a92022-06-28 14:47:50 +0100263/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000264#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100265pub struct FdtNode<'a> {
266 fdt: &'a Fdt,
267 offset: c_int,
268}
269
270impl<'a> FdtNode<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900271 /// Creates immutable node from a mutable node at the same offset.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900272 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
273 FdtNode { fdt: other.fdt, offset: other.offset }
274 }
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900275 /// Returns parent node.
David Brazdil1baa9a92022-06-28 14:47:50 +0100276 pub fn parent(&self) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000277 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100278 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
279
280 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
281 }
282
Jaewan Kim5b057772023-10-19 01:02:17 +0900283 /// Returns supernode with depth. Note that root is at depth 0.
284 pub fn supernode_at_depth(&self, depth: usize) -> Result<Self> {
285 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
286 let ret = unsafe {
287 libfdt_bindgen::fdt_supernode_atdepth_offset(
288 self.fdt.as_ptr(),
289 self.offset,
290 depth.try_into().unwrap(),
291 ptr::null_mut(),
292 )
293 };
294
295 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
296 }
297
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900298 /// Returns the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000299 pub fn device_type(&self) -> Result<Option<&CStr>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100300 self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap())
301 }
302
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900303 /// Returns the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000304 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
305 let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100306
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000307 if let Some(cells) = self.getprop_cells(reg)? {
308 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100309
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000310 let addr_cells = parent.address_cells()?;
311 let size_cells = parent.size_cells()?;
312
313 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
314 } else {
315 Ok(None)
316 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100317 }
318
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900319 /// Returns the standard ranges property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000320 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
321 let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap();
322 if let Some(cells) = self.getprop_cells(ranges)? {
323 let parent = self.parent()?;
324 let addr_cells = self.address_cells()?;
325 let parent_addr_cells = parent.address_cells()?;
326 let size_cells = self.size_cells()?;
327 Ok(Some(RangesIterator::<A, P, S>::new(
328 cells,
329 addr_cells,
330 parent_addr_cells,
331 size_cells,
332 )))
333 } else {
334 Ok(None)
335 }
336 }
337
Jaewan Kimaa638702023-09-19 13:34:01 +0900338 /// Returns the node name.
339 pub fn name(&self) -> Result<&'a CStr> {
340 let mut len: c_int = 0;
341 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
342 // function returns valid null terminating string and otherwise returned values are dropped.
343 let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
344 as *const c_void;
345 let len = usize::try_from(fdt_err(len)?).unwrap();
346 let name = self.fdt.get_from_ptr(name, len + 1)?;
347 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
348 }
349
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900350 /// Returns the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000351 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
352 let value = if let Some(bytes) = self.getprop(name)? {
353 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
354 } else {
355 None
356 };
357 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100358 }
359
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900360 /// Returns the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000361 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
362 if let Some(cells) = self.getprop(name)? {
363 Ok(Some(CellIterator::new(cells)))
364 } else {
365 Ok(None)
366 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100367 }
368
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900369 /// Returns the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000370 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
371 let value = if let Some(bytes) = self.getprop(name)? {
372 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
373 } else {
374 None
375 };
376 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100377 }
378
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900379 /// Returns the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000380 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
381 let value = if let Some(bytes) = self.getprop(name)? {
382 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
383 } else {
384 None
385 };
386 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100387 }
388
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900389 /// Returns the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000390 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900391 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900392 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900393 } else {
394 Ok(None) // property was not found
395 }
396 }
397
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900398 /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in
Jiyong Park9c63cd12023-03-21 17:53:07 +0900399 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
400 fn getprop_internal(
401 fdt: &'a Fdt,
402 offset: c_int,
403 name: &CStr,
404 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100405 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000406 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100407 // function respects the passed number of characters.
408 let prop = unsafe {
409 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900410 fdt.as_ptr(),
411 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100412 name.as_ptr(),
413 // *_namelen functions don't include the trailing nul terminator in 'len'.
414 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
415 &mut len as *mut i32,
416 )
417 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000418
419 let Some(len) = fdt_err_or_option(len)? else {
420 return Ok(None); // Property was not found.
421 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900422 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000423
David Brazdil1baa9a92022-06-28 14:47:50 +0100424 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000425 // We expected an error code in len but still received a valid value?!
426 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100427 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900428 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100429 }
430
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900431 /// Returns reference to the containing device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100432 pub fn fdt(&self) -> &Fdt {
433 self.fdt
434 }
435
Alice Wang474c0ee2023-09-14 12:52:33 +0000436 /// Returns the compatible node of the given name that is next after this node.
437 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000438 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000439 let ret = unsafe {
440 libfdt_bindgen::fdt_node_offset_by_compatible(
441 self.fdt.as_ptr(),
442 self.offset,
443 compatible.as_ptr(),
444 )
445 };
446
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000447 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000448 }
449
Alice Wang474c0ee2023-09-14 12:52:33 +0000450 /// Returns the first range of `reg` in this node.
451 pub fn first_reg(&self) -> Result<Reg<u64>> {
452 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
453 }
454
David Brazdil1baa9a92022-06-28 14:47:50 +0100455 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000456 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100457 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
458 .try_into()
459 .map_err(|_| FdtError::Internal)
460 }
461
462 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000463 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100464 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
465 .try_into()
466 .map_err(|_| FdtError::Internal)
467 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900468
469 /// Returns an iterator of subnodes
470 pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> {
471 SubnodeIterator::new(self)
472 }
473
474 fn first_subnode(&self) -> Result<Option<Self>> {
475 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
476 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) };
477
478 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
479 }
480
481 fn next_subnode(&self) -> Result<Option<Self>> {
482 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
483 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) };
484
485 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
486 }
Jaewan Kim72d10902023-10-12 21:59:26 +0900487
488 /// Returns an iterator of properties
489 pub fn properties(&'a self) -> Result<PropertyIterator<'a>> {
490 PropertyIterator::new(self)
491 }
492
493 fn first_property(&self) -> Result<Option<FdtProperty<'a>>> {
494 let ret =
495 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
496 unsafe { libfdt_bindgen::fdt_first_property_offset(self.fdt.as_ptr(), self.offset) };
497
498 fdt_err_or_option(ret)?.map(|offset| FdtProperty::new(self.fdt, offset)).transpose()
499 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100500}
501
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900502/// Phandle of a FDT node
503#[repr(transparent)]
504#[derive(Debug, Copy, Clone, PartialEq)]
505pub struct Phandle(u32);
506
507impl Phandle {
508 /// Creates a new Phandle
509 pub fn new(value: u32) -> Result<Self> {
510 if value == 0 || value > libfdt_bindgen::FDT_MAX_PHANDLE {
511 return Err(FdtError::BadPhandle);
512 }
513 Ok(Self(value))
514 }
515}
516
517impl From<Phandle> for u32 {
518 fn from(phandle: Phandle) -> u32 {
519 phandle.0
520 }
521}
522
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000523/// Mutable FDT node.
524pub struct FdtNodeMut<'a> {
525 fdt: &'a mut Fdt,
526 offset: c_int,
527}
528
529impl<'a> FdtNodeMut<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900530 /// Appends a property name-value (possibly empty) pair to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000531 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000532 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000533 let ret = unsafe {
534 libfdt_bindgen::fdt_appendprop(
535 self.fdt.as_mut_ptr(),
536 self.offset,
537 name.as_ptr(),
538 value.as_ref().as_ptr().cast::<c_void>(),
539 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
540 )
541 };
542
543 fdt_err_expect_zero(ret)
544 }
545
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900546 /// Appends a (address, size) pair property to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000547 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000548 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000549 let ret = unsafe {
550 libfdt_bindgen::fdt_appendprop_addrrange(
551 self.fdt.as_mut_ptr(),
552 self.parent()?.offset,
553 self.offset,
554 name.as_ptr(),
555 addr,
556 size,
557 )
558 };
559
560 fdt_err_expect_zero(ret)
561 }
562
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900563 /// Sets a property name-value pair to the given node.
564 ///
565 /// This may create a new prop or replace existing value.
Jaewan Kimba8929b2023-01-13 11:13:29 +0900566 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000567 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900568 // (validated by underlying libfdt).
569 let ret = unsafe {
570 libfdt_bindgen::fdt_setprop(
571 self.fdt.as_mut_ptr(),
572 self.offset,
573 name.as_ptr(),
574 value.as_ptr().cast::<c_void>(),
575 value.len().try_into().map_err(|_| FdtError::BadValue)?,
576 )
577 };
578
579 fdt_err_expect_zero(ret)
580 }
581
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900582 /// Sets the value of the given property with the given value, and ensure that the given
583 /// value has the same length as the current value length.
584 ///
585 /// This can only be used to replace existing value.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900586 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000587 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900588 let ret = unsafe {
589 libfdt_bindgen::fdt_setprop_inplace(
590 self.fdt.as_mut_ptr(),
591 self.offset,
592 name.as_ptr(),
593 value.as_ptr().cast::<c_void>(),
594 value.len().try_into().map_err(|_| FdtError::BadValue)?,
595 )
596 };
597
598 fdt_err_expect_zero(ret)
599 }
600
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900601 /// Sets the value of the given (address, size) pair property with the given value, and
602 /// ensure that the given value has the same length as the current value length.
603 ///
604 /// This can only be used to replace existing value.
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000605 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
606 let pair = [addr.to_be(), size.to_be()];
607 self.setprop_inplace(name, pair.as_bytes())
608 }
609
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900610 /// Sets a flag-like empty property.
611 ///
612 /// This may create a new prop or replace existing value.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000613 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
614 self.setprop(name, &[])
615 }
616
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900617 /// Deletes the given property.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000618 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000619 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000620 // library locates the node's property. Removing the property may shift the offsets of
621 // other nodes and properties but the borrow checker should prevent this function from
622 // being called when FdtNode instances are in use.
623 let ret = unsafe {
624 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
625 };
626
627 fdt_err_expect_zero(ret)
628 }
629
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900630 /// Deletes the given property effectively from DT, by setting it with FDT_NOP.
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000631 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000632 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000633 // library locates the node's property.
634 let ret = unsafe {
635 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
636 };
637
638 fdt_err_expect_zero(ret)
639 }
640
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900641 /// Trims the size of the given property to new_size.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900642 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
643 let (prop, len) =
644 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
645 if len == new_size {
646 return Ok(());
647 }
648 if new_size > len {
649 return Err(FdtError::NoSpace);
650 }
651
Andrew Walbran84b9a232023-07-05 14:01:40 +0000652 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900653 let ret = unsafe {
654 libfdt_bindgen::fdt_setprop(
655 self.fdt.as_mut_ptr(),
656 self.offset,
657 name.as_ptr(),
658 prop.cast::<c_void>(),
659 new_size.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 /// Returns reference to the containing device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000667 pub fn fdt(&mut self) -> &mut Fdt {
668 self.fdt
669 }
670
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900671 /// 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 +0000672 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900673 let offset = self.add_subnode_offset(name.to_bytes())?;
674 Ok(Self { fdt: self.fdt, offset })
675 }
676
677 /// Adds a new subnode to the given node with name and namelen, and returns it as a FdtNodeMut
678 /// on success.
679 pub fn add_subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Self> {
680 let offset = { self.add_subnode_offset(&name.to_bytes()[..namelen])? };
681 Ok(Self { fdt: self.fdt, offset })
682 }
683
684 fn add_subnode_offset(&mut self, name: &[u8]) -> Result<c_int> {
685 let namelen = name.len().try_into().unwrap();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000686 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000687 let ret = unsafe {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900688 libfdt_bindgen::fdt_add_subnode_namelen(
689 self.fdt.as_mut_ptr(),
690 self.offset,
691 name.as_ptr().cast::<_>(),
692 namelen,
693 )
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000694 };
Jaewan Kim5ab13582023-10-20 20:56:27 +0900695 fdt_err(ret)
696 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000697
Jaewan Kim5ab13582023-10-20 20:56:27 +0900698 /// Returns the subnode of the given name with len.
699 pub fn subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Option<Self>> {
700 let offset = self.subnode_offset(&name.to_bytes()[..namelen])?;
701 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
702 }
703
704 fn subnode_offset(&self, name: &[u8]) -> Result<Option<c_int>> {
705 let namelen = name.len().try_into().unwrap();
706 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
707 let ret = unsafe {
708 libfdt_bindgen::fdt_subnode_offset_namelen(
709 self.fdt.as_ptr(),
710 self.offset,
711 name.as_ptr().cast::<_>(),
712 namelen,
713 )
714 };
715 fdt_err_or_option(ret)
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000716 }
717
718 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000719 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000720 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
721
722 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
723 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900724
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900725 /// Returns the compatible node of the given name that is next after this node.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900726 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000727 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900728 let ret = unsafe {
729 libfdt_bindgen::fdt_node_offset_by_compatible(
730 self.fdt.as_ptr(),
731 self.offset,
732 compatible.as_ptr(),
733 )
734 };
735
736 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
737 }
738
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900739 /// Deletes the node effectively by overwriting this node and its subtree with nop tags.
740 /// Returns the next compatible node of the given name.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900741 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
742 // The reason is that libfdt ensures that the node from where the search for the next
743 // compatible node is started is always a valid one -- except for the special case of offset =
744 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
745 // next compatible node from it.
746 //
747 // We can't do in the opposite direction either. If we call next_compatible to find the next
748 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
749 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
750 // DT).
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900751 pub fn delete_and_next_compatible(mut self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000752 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900753 let ret = unsafe {
754 libfdt_bindgen::fdt_node_offset_by_compatible(
755 self.fdt.as_ptr(),
756 self.offset,
757 compatible.as_ptr(),
758 )
759 };
760 let next_offset = fdt_err_or_option(ret)?;
761
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900762 if Some(self.offset) == next_offset {
763 return Err(FdtError::Internal);
764 }
765
766 // SAFETY: nop_self() only touches bytes of the self and its properties and subnodes, and
767 // doesn't alter any other blob in the tree. self.fdt and next_offset would remain valid.
768 unsafe { self.nop_self()? };
Jiyong Park9c63cd12023-03-21 17:53:07 +0900769
770 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
771 }
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900772
773 /// Deletes this node effectively from DT, by setting it with FDT_NOP
774 pub fn nop(mut self) -> Result<()> {
775 // SAFETY: This consumes self, so invalid node wouldn't be used any further
776 unsafe { self.nop_self() }
777 }
778
779 /// Deletes this node effectively from DT, by setting it with FDT_NOP.
780 /// This only changes bytes of the node and its properties and subnodes, and doesn't alter or
781 /// move any other part of the tree.
782 /// SAFETY: This node is no longer valid.
783 unsafe fn nop_self(&mut self) -> Result<()> {
784 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
785 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
786
787 fdt_err_expect_zero(ret)
788 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000789}
790
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000791/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000792#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100793#[repr(transparent)]
794pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000795 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100796}
797
798impl Fdt {
799 /// Wraps a slice containing a Flattened Device Tree.
800 ///
801 /// Fails if the FDT does not pass validation.
802 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000803 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100804 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
805 fdt.check_full()?;
806 Ok(fdt)
807 }
808
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000809 /// Wraps a mutable slice containing a Flattened Device Tree.
810 ///
811 /// Fails if the FDT does not pass validation.
812 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000813 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000814 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
815 fdt.check_full()?;
816 Ok(fdt)
817 }
818
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900819 /// Creates an empty Flattened Device Tree with a mutable slice.
820 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000821 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900822 // and returns error if buffer was insufficient.
823 // There will be no memory write outside of the given fdt.
824 let ret = unsafe {
825 libfdt_bindgen::fdt_create_empty_tree(
826 fdt.as_mut_ptr().cast::<c_void>(),
827 fdt.len() as i32,
828 )
829 };
830 fdt_err_expect_zero(ret)?;
831
Andrew Walbran84b9a232023-07-05 14:01:40 +0000832 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900833 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
834 fdt.check_full()?;
835
836 Ok(fdt)
837 }
838
David Brazdil1baa9a92022-06-28 14:47:50 +0100839 /// Wraps a slice containing a Flattened Device Tree.
840 ///
841 /// # Safety
842 ///
843 /// The returned FDT might be invalid, only use on slices containing a valid DT.
844 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000845 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
846 // responsible for ensuring that it is actually a valid FDT.
847 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100848 }
849
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000850 /// Wraps a mutable slice containing a Flattened Device Tree.
851 ///
852 /// # Safety
853 ///
854 /// The returned FDT might be invalid, only use on slices containing a valid DT.
855 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000856 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
857 // responsible for ensuring that it is actually a valid FDT.
858 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000859 }
860
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900861 /// Updates this FDT from a slice containing another FDT.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900862 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
863 if self.buffer.len() < new_fdt.len() {
864 Err(FdtError::NoSpace)
865 } else {
866 let totalsize = self.totalsize();
867 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
868 // Zeroize the remaining part. We zeroize up to the size of the original DT because
869 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
870 // time.
871 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
872 Ok(())
873 }
874 }
875
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900876 /// Unpacks the DT to cover the whole slice it is contained in.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000877 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000878 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000879 // internal structures to make use of the whole self.fdt slice but performs no accesses
880 // outside of it and leaves the DT in a state that will be detected by other functions.
881 let ret = unsafe {
882 libfdt_bindgen::fdt_open_into(
883 self.as_ptr(),
884 self.as_mut_ptr(),
885 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
886 )
887 };
888 fdt_err_expect_zero(ret)
889 }
890
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900891 /// Packs the DT to take a minimum amount of memory.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000892 ///
893 /// Doesn't shrink the underlying memory slice.
894 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000895 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000896 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
897 fdt_err_expect_zero(ret)
898 }
899
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000900 /// Applies a DT overlay on the base DT.
901 ///
902 /// # Safety
903 ///
904 /// On failure, the library corrupts the DT and overlay so both must be discarded.
905 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000906 let ret =
907 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
908 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
909 // but that's our caller's responsibility.
910 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
911 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000912 Ok(self)
913 }
914
Alice Wang2422bdc2023-06-12 08:37:55 +0000915 /// Returns an iterator of memory banks specified the "/memory" node.
916 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100917 ///
918 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000919 pub fn memory(&self) -> Result<MemRegIterator> {
920 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
921 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100922
Alice Wang2422bdc2023-06-12 08:37:55 +0000923 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
924 if node.device_type()? != Some(memory_device_type) {
925 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000926 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000927 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
928 }
929
930 /// Returns the first memory range in the `/memory` node.
931 pub fn first_memory_range(&self) -> Result<Range<usize>> {
932 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100933 }
934
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900935 /// Returns the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000936 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100937 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
938 }
939
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900940 /// Returns the standard /chosen node as mutable.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000941 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
942 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
943 }
944
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900945 /// Returns the root node of the tree.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000946 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000947 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000948 }
949
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900950 /// Returns a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000951 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
Jaewan Kimbab42592023-10-13 15:47:19 +0900952 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100953 }
954
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000955 /// Iterate over nodes with a given compatible string.
956 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
957 CompatibleIterator::new(self, compatible)
958 }
959
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900960 /// Returns max phandle in the tree.
961 pub fn max_phandle(&self) -> Result<Phandle> {
962 let mut phandle: u32 = 0;
963 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
964 let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(self.as_ptr(), &mut phandle) };
965
966 fdt_err_expect_zero(ret)?;
967 Phandle::new(phandle)
968 }
969
970 /// Returns a node with the phandle
971 pub fn node_with_phandle(&self, phandle: Phandle) -> Result<Option<FdtNode>> {
972 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
973 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(self.as_ptr(), phandle.0) };
974 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self, offset }))
975 }
976
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900977 /// Returns the mutable root node of the tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000978 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
979 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
980 }
981
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900982 /// Returns a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000983 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
Jaewan Kimbab42592023-10-13 15:47:19 +0900984 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000985 }
986
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900987 /// Returns the device tree as a slice (may be smaller than the containing buffer).
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000988 pub fn as_slice(&self) -> &[u8] {
989 &self.buffer[..self.totalsize()]
990 }
991
Jaewan Kimbab42592023-10-13 15:47:19 +0900992 fn path_offset(&self, path: &[u8]) -> Result<Option<c_int>> {
993 let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000994 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100995 // function respects the passed number of characters.
996 let ret = unsafe {
997 // *_namelen functions don't include the trailing nul terminator in 'len'.
Jaewan Kimbab42592023-10-13 15:47:19 +0900998 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr().cast::<_>(), len)
David Brazdil1baa9a92022-06-28 14:47:50 +0100999 };
1000
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001001 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +01001002 }
1003
1004 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +00001005 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +01001006 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
1007 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
1008 // checking. The library doesn't maintain an internal state (such as pointers) between
1009 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
Pierre-Clément Tosi02017da2023-09-26 17:57:04 +01001010 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +01001011 fdt_err_expect_zero(ret)
1012 }
1013
Jaewan Kimaa638702023-09-19 13:34:01 +09001014 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
1015 let ptr = ptr as usize;
1016 let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
1017 self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
1018 }
1019
Jaewan Kim72d10902023-10-12 21:59:26 +09001020 fn string(&self, offset: c_int) -> Result<&CStr> {
1021 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
1022 let res = unsafe { libfdt_bindgen::fdt_string(self.as_ptr(), offset) };
1023 if res.is_null() {
1024 return Err(FdtError::Internal);
1025 }
1026
1027 // SAFETY: Non-null return from fdt_string() is valid null-terminating string within FDT.
1028 Ok(unsafe { CStr::from_ptr(res) })
1029 }
1030
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001031 /// Returns a shared pointer to the device tree.
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +00001032 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001033 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +01001034 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001035
1036 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001037 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001038 }
1039
1040 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +00001041 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001042 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001043
1044 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001045 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +00001046 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001047 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001048 }
1049
1050 fn totalsize(&self) -> usize {
1051 u32::from_be(self.header().totalsize) as usize
1052 }
David Brazdil1baa9a92022-06-28 14:47:50 +01001053}