blob: b811730744c0db0cdc73cfe78cc8b168e4eef408 [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
Jaewan Kimb635bb02023-11-01 13:00:34 +090036// TODO(b/308694211): Use cstr!() from vmbase
37macro_rules! cstr {
38 ($str:literal) => {{
39 core::ffi::CStr::from_bytes_with_nul(concat!($str, "\0").as_bytes()).unwrap()
40 }};
41}
42
David Brazdil1baa9a92022-06-28 14:47:50 +010043/// Error type corresponding to libfdt error codes.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum FdtError {
46 /// FDT_ERR_NOTFOUND
47 NotFound,
48 /// FDT_ERR_EXISTS
49 Exists,
50 /// FDT_ERR_NOSPACE
51 NoSpace,
52 /// FDT_ERR_BADOFFSET
53 BadOffset,
54 /// FDT_ERR_BADPATH
55 BadPath,
56 /// FDT_ERR_BADPHANDLE
57 BadPhandle,
58 /// FDT_ERR_BADSTATE
59 BadState,
60 /// FDT_ERR_TRUNCATED
61 Truncated,
62 /// FDT_ERR_BADMAGIC
63 BadMagic,
64 /// FDT_ERR_BADVERSION
65 BadVersion,
66 /// FDT_ERR_BADSTRUCTURE
67 BadStructure,
68 /// FDT_ERR_BADLAYOUT
69 BadLayout,
70 /// FDT_ERR_INTERNAL
71 Internal,
72 /// FDT_ERR_BADNCELLS
73 BadNCells,
74 /// FDT_ERR_BADVALUE
75 BadValue,
76 /// FDT_ERR_BADOVERLAY
77 BadOverlay,
78 /// FDT_ERR_NOPHANDLES
79 NoPhandles,
80 /// FDT_ERR_BADFLAGS
81 BadFlags,
82 /// FDT_ERR_ALIGNMENT
83 Alignment,
84 /// Unexpected error code
85 Unknown(i32),
86}
87
88impl fmt::Display for FdtError {
89 /// Prints error messages from libfdt.h documentation.
90 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91 match self {
92 Self::NotFound => write!(f, "The requested node or property does not exist"),
93 Self::Exists => write!(f, "Attempted to create an existing node or property"),
94 Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"),
95 Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"),
96 Self::BadPath => write!(f, "Badly formatted path"),
97 Self::BadPhandle => write!(f, "Invalid phandle length or value"),
98 Self::BadState => write!(f, "Received incomplete device tree"),
99 Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"),
100 Self::BadMagic => write!(f, "Device tree header missing its magic number"),
101 Self::BadVersion => write!(f, "Device tree has a version which can't be handled"),
102 Self::BadStructure => write!(f, "Device tree has a corrupt structure block"),
103 Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"),
104 Self::Internal => write!(f, "libfdt has failed an internal assertion"),
105 Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"),
106 Self::BadValue => write!(f, "Unexpected property value"),
107 Self::BadOverlay => write!(f, "Overlay cannot be applied"),
108 Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"),
109 Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"),
110 Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"),
111 Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"),
112 }
113 }
114}
115
116/// Result type with FdtError enum.
117pub type Result<T> = result::Result<T, FdtError>;
118
119fn fdt_err(val: c_int) -> Result<c_int> {
120 if val >= 0 {
121 Ok(val)
122 } else {
123 Err(match -val as _ {
124 libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound,
125 libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists,
126 libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace,
127 libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset,
128 libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath,
129 libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle,
130 libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState,
131 libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated,
132 libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic,
133 libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion,
134 libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure,
135 libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout,
136 libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal,
137 libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells,
138 libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue,
139 libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay,
140 libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles,
141 libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags,
142 libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment,
143 _ => FdtError::Unknown(val),
144 })
145 }
146}
147
148fn fdt_err_expect_zero(val: c_int) -> Result<()> {
149 match fdt_err(val)? {
150 0 => Ok(()),
151 _ => Err(FdtError::Unknown(val)),
152 }
153}
154
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000155fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> {
156 match fdt_err(val) {
157 Ok(val) => Ok(Some(val)),
158 Err(FdtError::NotFound) => Ok(None),
159 Err(e) => Err(e),
160 }
161}
162
David Brazdil1baa9a92022-06-28 14:47:50 +0100163/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000164#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100165enum AddrCells {
166 Single = 1,
167 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000168 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100169}
170
171impl TryFrom<c_int> for AddrCells {
172 type Error = FdtError;
173
174 fn try_from(res: c_int) -> Result<Self> {
175 match fdt_err(res)? {
176 x if x == Self::Single as c_int => Ok(Self::Single),
177 x if x == Self::Double as c_int => Ok(Self::Double),
Andrew Walbranb39e6922022-12-05 17:01:20 +0000178 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100179 _ => Err(FdtError::BadNCells),
180 }
181 }
182}
183
184/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000185#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100186enum SizeCells {
187 None = 0,
188 Single = 1,
189 Double = 2,
190}
191
192impl TryFrom<c_int> for SizeCells {
193 type Error = FdtError;
194
195 fn try_from(res: c_int) -> Result<Self> {
196 match fdt_err(res)? {
197 x if x == Self::None as c_int => Ok(Self::None),
198 x if x == Self::Single as c_int => Ok(Self::Single),
199 x if x == Self::Double as c_int => Ok(Self::Double),
200 _ => Err(FdtError::BadNCells),
201 }
202 }
203}
204
Jaewan Kim72d10902023-10-12 21:59:26 +0900205/// DT property wrapper to abstract endianess changes
206#[repr(transparent)]
207#[derive(Debug)]
208struct FdtPropertyStruct(libfdt_bindgen::fdt_property);
209
210impl FdtPropertyStruct {
211 fn from_offset(fdt: &Fdt, offset: c_int) -> Result<&Self> {
212 let mut len = 0;
213 let prop =
214 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
215 unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt.as_ptr(), offset, &mut len) };
216 if prop.is_null() {
217 fdt_err(len)?;
218 return Err(FdtError::Internal); // shouldn't happen.
219 }
220 // SAFETY: prop is only returned when it points to valid libfdt_bindgen.
221 Ok(unsafe { &*prop.cast::<FdtPropertyStruct>() })
222 }
223
224 fn name_offset(&self) -> c_int {
225 u32::from_be(self.0.nameoff).try_into().unwrap()
226 }
227
228 fn data_len(&self) -> usize {
229 u32::from_be(self.0.len).try_into().unwrap()
230 }
231
232 fn data_ptr(&self) -> *const c_void {
233 self.0.data.as_ptr().cast::<_>()
234 }
235}
236
237/// DT property.
238#[derive(Clone, Copy, Debug)]
239pub struct FdtProperty<'a> {
240 fdt: &'a Fdt,
241 offset: c_int,
242 property: &'a FdtPropertyStruct,
243}
244
245impl<'a> FdtProperty<'a> {
246 fn new(fdt: &'a Fdt, offset: c_int) -> Result<Self> {
247 let property = FdtPropertyStruct::from_offset(fdt, offset)?;
248 Ok(Self { fdt, offset, property })
249 }
250
251 /// Returns the property name
252 pub fn name(&self) -> Result<&'a CStr> {
253 self.fdt.string(self.property.name_offset())
254 }
255
256 /// Returns the property value
257 pub fn value(&self) -> Result<&'a [u8]> {
258 self.fdt.get_from_ptr(self.property.data_ptr(), self.property.data_len())
259 }
260
261 fn next_property(&self) -> Result<Option<Self>> {
262 let ret =
263 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
264 unsafe { libfdt_bindgen::fdt_next_property_offset(self.fdt.as_ptr(), self.offset) };
265
266 fdt_err_or_option(ret)?.map(|offset| Self::new(self.fdt, offset)).transpose()
267 }
268}
269
David Brazdil1baa9a92022-06-28 14:47:50 +0100270/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000271#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100272pub struct FdtNode<'a> {
273 fdt: &'a Fdt,
274 offset: c_int,
275}
276
277impl<'a> FdtNode<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900278 /// Creates immutable node from a mutable node at the same offset.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900279 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
280 FdtNode { fdt: other.fdt, offset: other.offset }
281 }
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900282 /// Returns parent node.
David Brazdil1baa9a92022-06-28 14:47:50 +0100283 pub fn parent(&self) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000284 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100285 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
286
287 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
288 }
289
Jaewan Kim5b057772023-10-19 01:02:17 +0900290 /// Returns supernode with depth. Note that root is at depth 0.
291 pub fn supernode_at_depth(&self, depth: usize) -> Result<Self> {
292 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
293 let ret = unsafe {
294 libfdt_bindgen::fdt_supernode_atdepth_offset(
295 self.fdt.as_ptr(),
296 self.offset,
297 depth.try_into().unwrap(),
298 ptr::null_mut(),
299 )
300 };
301
302 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
303 }
304
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900305 /// Returns the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000306 pub fn device_type(&self) -> Result<Option<&CStr>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900307 self.getprop_str(cstr!("device_type"))
David Brazdil1baa9a92022-06-28 14:47:50 +0100308 }
309
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900310 /// Returns the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000311 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900312 let reg = cstr!("reg");
David Brazdil1baa9a92022-06-28 14:47:50 +0100313
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000314 if let Some(cells) = self.getprop_cells(reg)? {
315 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100316
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000317 let addr_cells = parent.address_cells()?;
318 let size_cells = parent.size_cells()?;
319
320 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
321 } else {
322 Ok(None)
323 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100324 }
325
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900326 /// Returns the standard ranges property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000327 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900328 let ranges = cstr!("ranges");
Andrew Walbranb39e6922022-12-05 17:01:20 +0000329 if let Some(cells) = self.getprop_cells(ranges)? {
330 let parent = self.parent()?;
331 let addr_cells = self.address_cells()?;
332 let parent_addr_cells = parent.address_cells()?;
333 let size_cells = self.size_cells()?;
334 Ok(Some(RangesIterator::<A, P, S>::new(
335 cells,
336 addr_cells,
337 parent_addr_cells,
338 size_cells,
339 )))
340 } else {
341 Ok(None)
342 }
343 }
344
Jaewan Kimaa638702023-09-19 13:34:01 +0900345 /// Returns the node name.
346 pub fn name(&self) -> Result<&'a CStr> {
347 let mut len: c_int = 0;
348 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
349 // function returns valid null terminating string and otherwise returned values are dropped.
350 let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
351 as *const c_void;
352 let len = usize::try_from(fdt_err(len)?).unwrap();
353 let name = self.fdt.get_from_ptr(name, len + 1)?;
354 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
355 }
356
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900357 /// Returns the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000358 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
359 let value = if let Some(bytes) = self.getprop(name)? {
360 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
361 } else {
362 None
363 };
364 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100365 }
366
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900367 /// Returns the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000368 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
369 if let Some(cells) = self.getprop(name)? {
370 Ok(Some(CellIterator::new(cells)))
371 } else {
372 Ok(None)
373 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100374 }
375
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900376 /// Returns the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000377 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
378 let value = if let Some(bytes) = self.getprop(name)? {
379 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
380 } else {
381 None
382 };
383 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100384 }
385
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900386 /// Returns the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000387 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
388 let value = if let Some(bytes) = self.getprop(name)? {
389 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
390 } else {
391 None
392 };
393 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100394 }
395
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900396 /// Returns the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000397 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900398 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900399 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900400 } else {
401 Ok(None) // property was not found
402 }
403 }
404
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900405 /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in
Jiyong Park9c63cd12023-03-21 17:53:07 +0900406 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
407 fn getprop_internal(
408 fdt: &'a Fdt,
409 offset: c_int,
410 name: &CStr,
411 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100412 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000413 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100414 // function respects the passed number of characters.
415 let prop = unsafe {
416 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900417 fdt.as_ptr(),
418 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100419 name.as_ptr(),
420 // *_namelen functions don't include the trailing nul terminator in 'len'.
421 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
422 &mut len as *mut i32,
423 )
424 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000425
426 let Some(len) = fdt_err_or_option(len)? else {
427 return Ok(None); // Property was not found.
428 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900429 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000430
David Brazdil1baa9a92022-06-28 14:47:50 +0100431 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000432 // We expected an error code in len but still received a valid value?!
433 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100434 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900435 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100436 }
437
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900438 /// Returns reference to the containing device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100439 pub fn fdt(&self) -> &Fdt {
440 self.fdt
441 }
442
Alice Wang474c0ee2023-09-14 12:52:33 +0000443 /// Returns the compatible node of the given name that is next after this node.
444 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000445 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000446 let ret = unsafe {
447 libfdt_bindgen::fdt_node_offset_by_compatible(
448 self.fdt.as_ptr(),
449 self.offset,
450 compatible.as_ptr(),
451 )
452 };
453
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000454 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000455 }
456
Alice Wang474c0ee2023-09-14 12:52:33 +0000457 /// Returns the first range of `reg` in this node.
458 pub fn first_reg(&self) -> Result<Reg<u64>> {
459 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
460 }
461
David Brazdil1baa9a92022-06-28 14:47:50 +0100462 fn address_cells(&self) -> Result<AddrCells> {
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_address_cells(self.fdt.as_ptr(), self.offset) }
465 .try_into()
466 .map_err(|_| FdtError::Internal)
467 }
468
469 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000470 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100471 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
472 .try_into()
473 .map_err(|_| FdtError::Internal)
474 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900475
476 /// Returns an iterator of subnodes
477 pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> {
478 SubnodeIterator::new(self)
479 }
480
481 fn first_subnode(&self) -> Result<Option<Self>> {
482 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
483 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) };
484
485 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
486 }
487
488 fn next_subnode(&self) -> Result<Option<Self>> {
489 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
490 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) };
491
492 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
493 }
Jaewan Kim72d10902023-10-12 21:59:26 +0900494
495 /// Returns an iterator of properties
496 pub fn properties(&'a self) -> Result<PropertyIterator<'a>> {
497 PropertyIterator::new(self)
498 }
499
500 fn first_property(&self) -> Result<Option<FdtProperty<'a>>> {
501 let ret =
502 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
503 unsafe { libfdt_bindgen::fdt_first_property_offset(self.fdt.as_ptr(), self.offset) };
504
505 fdt_err_or_option(ret)?.map(|offset| FdtProperty::new(self.fdt, offset)).transpose()
506 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100507}
508
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000509impl<'a> PartialEq for FdtNode<'a> {
510 fn eq(&self, other: &Self) -> bool {
511 self.fdt.as_ptr() == other.fdt.as_ptr() && self.offset == other.offset
512 }
513}
514
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900515/// Phandle of a FDT node
516#[repr(transparent)]
517#[derive(Debug, Copy, Clone, PartialEq)]
518pub struct Phandle(u32);
519
520impl Phandle {
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000521 /// Minimum valid value for device tree phandles.
522 pub const MIN: Self = Self(1);
523 /// Maximum valid value for device tree phandles.
524 pub const MAX: Self = Self(libfdt_bindgen::FDT_MAX_PHANDLE);
525
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900526 /// Creates a new Phandle
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000527 pub const fn new(value: u32) -> Option<Self> {
528 if Self::MIN.0 <= value && value <= Self::MAX.0 {
529 Some(Self(value))
530 } else {
531 None
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900532 }
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900533 }
534}
535
536impl From<Phandle> for u32 {
537 fn from(phandle: Phandle) -> u32 {
538 phandle.0
539 }
540}
541
Pierre-Clément Tosieba27792023-10-30 12:04:12 +0000542impl TryFrom<u32> for Phandle {
543 type Error = FdtError;
544
545 fn try_from(value: u32) -> Result<Self> {
546 Self::new(value).ok_or(FdtError::BadPhandle)
547 }
548}
549
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000550/// Mutable FDT node.
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000551#[derive(Debug)]
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000552pub struct FdtNodeMut<'a> {
553 fdt: &'a mut Fdt,
554 offset: c_int,
555}
556
557impl<'a> FdtNodeMut<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900558 /// Appends a property name-value (possibly empty) pair to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000559 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000560 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000561 let ret = unsafe {
562 libfdt_bindgen::fdt_appendprop(
563 self.fdt.as_mut_ptr(),
564 self.offset,
565 name.as_ptr(),
566 value.as_ref().as_ptr().cast::<c_void>(),
567 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
568 )
569 };
570
571 fdt_err_expect_zero(ret)
572 }
573
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900574 /// Appends a (address, size) pair property to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000575 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000576 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000577 let ret = unsafe {
578 libfdt_bindgen::fdt_appendprop_addrrange(
579 self.fdt.as_mut_ptr(),
580 self.parent()?.offset,
581 self.offset,
582 name.as_ptr(),
583 addr,
584 size,
585 )
586 };
587
588 fdt_err_expect_zero(ret)
589 }
590
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900591 /// Sets a property name-value pair to the given node.
592 ///
593 /// This may create a new prop or replace existing value.
Jaewan Kimba8929b2023-01-13 11:13:29 +0900594 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000595 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900596 // (validated by underlying libfdt).
597 let ret = unsafe {
598 libfdt_bindgen::fdt_setprop(
599 self.fdt.as_mut_ptr(),
600 self.offset,
601 name.as_ptr(),
602 value.as_ptr().cast::<c_void>(),
603 value.len().try_into().map_err(|_| FdtError::BadValue)?,
604 )
605 };
606
607 fdt_err_expect_zero(ret)
608 }
609
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900610 /// Sets the value of the given property with the given value, and ensure that the given
611 /// value has the same length as the current value length.
612 ///
613 /// This can only be used to replace existing value.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900614 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000615 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900616 let ret = unsafe {
617 libfdt_bindgen::fdt_setprop_inplace(
618 self.fdt.as_mut_ptr(),
619 self.offset,
620 name.as_ptr(),
621 value.as_ptr().cast::<c_void>(),
622 value.len().try_into().map_err(|_| FdtError::BadValue)?,
623 )
624 };
625
626 fdt_err_expect_zero(ret)
627 }
628
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900629 /// Sets the value of the given (address, size) pair property with the given value, and
630 /// ensure that the given value has the same length as the current value length.
631 ///
632 /// This can only be used to replace existing value.
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000633 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
634 let pair = [addr.to_be(), size.to_be()];
635 self.setprop_inplace(name, pair.as_bytes())
636 }
637
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900638 /// Sets a flag-like empty property.
639 ///
640 /// This may create a new prop or replace existing value.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000641 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
642 self.setprop(name, &[])
643 }
644
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900645 /// Deletes the given property.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000646 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000647 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000648 // library locates the node's property. Removing the property may shift the offsets of
649 // other nodes and properties but the borrow checker should prevent this function from
650 // being called when FdtNode instances are in use.
651 let ret = unsafe {
652 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
653 };
654
655 fdt_err_expect_zero(ret)
656 }
657
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900658 /// Deletes the given property effectively from DT, by setting it with FDT_NOP.
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000659 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000660 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000661 // library locates the node's property.
662 let ret = unsafe {
663 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
664 };
665
666 fdt_err_expect_zero(ret)
667 }
668
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900669 /// Trims the size of the given property to new_size.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900670 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
671 let (prop, len) =
672 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
673 if len == new_size {
674 return Ok(());
675 }
676 if new_size > len {
677 return Err(FdtError::NoSpace);
678 }
679
Andrew Walbran84b9a232023-07-05 14:01:40 +0000680 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900681 let ret = unsafe {
682 libfdt_bindgen::fdt_setprop(
683 self.fdt.as_mut_ptr(),
684 self.offset,
685 name.as_ptr(),
686 prop.cast::<c_void>(),
687 new_size.try_into().map_err(|_| FdtError::BadValue)?,
688 )
689 };
690
691 fdt_err_expect_zero(ret)
692 }
693
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900694 /// Returns reference to the containing device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000695 pub fn fdt(&mut self) -> &mut Fdt {
696 self.fdt
697 }
698
Jaewan Kimf72f4f22023-11-03 19:21:34 +0900699 /// Returns immutable FdtNode of this node.
700 pub fn as_node(&self) -> FdtNode {
701 FdtNode { fdt: self.fdt, offset: self.offset }
702 }
703
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900704 /// 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 +0000705 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900706 let offset = self.add_subnode_offset(name.to_bytes())?;
707 Ok(Self { fdt: self.fdt, offset })
708 }
709
710 /// Adds a new subnode to the given node with name and namelen, and returns it as a FdtNodeMut
711 /// on success.
712 pub fn add_subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Self> {
713 let offset = { self.add_subnode_offset(&name.to_bytes()[..namelen])? };
714 Ok(Self { fdt: self.fdt, offset })
715 }
716
717 fn add_subnode_offset(&mut self, name: &[u8]) -> Result<c_int> {
718 let namelen = name.len().try_into().unwrap();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000719 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000720 let ret = unsafe {
Jaewan Kim5ab13582023-10-20 20:56:27 +0900721 libfdt_bindgen::fdt_add_subnode_namelen(
722 self.fdt.as_mut_ptr(),
723 self.offset,
724 name.as_ptr().cast::<_>(),
725 namelen,
726 )
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000727 };
Jaewan Kim5ab13582023-10-20 20:56:27 +0900728 fdt_err(ret)
729 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000730
Jaewan Kim5ab13582023-10-20 20:56:27 +0900731 /// Returns the subnode of the given name with len.
732 pub fn subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Option<Self>> {
733 let offset = self.subnode_offset(&name.to_bytes()[..namelen])?;
734 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
735 }
736
737 fn subnode_offset(&self, name: &[u8]) -> Result<Option<c_int>> {
738 let namelen = name.len().try_into().unwrap();
739 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
740 let ret = unsafe {
741 libfdt_bindgen::fdt_subnode_offset_namelen(
742 self.fdt.as_ptr(),
743 self.offset,
744 name.as_ptr().cast::<_>(),
745 namelen,
746 )
747 };
748 fdt_err_or_option(ret)
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000749 }
750
751 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000752 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000753 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
754
755 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
756 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900757
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900758 /// Returns the compatible node of the given name that is next after this node.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900759 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000760 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900761 let ret = unsafe {
762 libfdt_bindgen::fdt_node_offset_by_compatible(
763 self.fdt.as_ptr(),
764 self.offset,
765 compatible.as_ptr(),
766 )
767 };
768
769 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
770 }
771
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900772 /// Deletes the node effectively by overwriting this node and its subtree with nop tags.
773 /// Returns the next compatible node of the given name.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900774 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
775 // The reason is that libfdt ensures that the node from where the search for the next
776 // compatible node is started is always a valid one -- except for the special case of offset =
777 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
778 // next compatible node from it.
779 //
780 // We can't do in the opposite direction either. If we call next_compatible to find the next
781 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
782 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
783 // DT).
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900784 pub fn delete_and_next_compatible(mut self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000785 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900786 let ret = unsafe {
787 libfdt_bindgen::fdt_node_offset_by_compatible(
788 self.fdt.as_ptr(),
789 self.offset,
790 compatible.as_ptr(),
791 )
792 };
793 let next_offset = fdt_err_or_option(ret)?;
794
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900795 if Some(self.offset) == next_offset {
796 return Err(FdtError::Internal);
797 }
798
799 // SAFETY: nop_self() only touches bytes of the self and its properties and subnodes, and
800 // doesn't alter any other blob in the tree. self.fdt and next_offset would remain valid.
801 unsafe { self.nop_self()? };
Jiyong Park9c63cd12023-03-21 17:53:07 +0900802
803 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
804 }
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900805
806 /// Deletes this node effectively from DT, by setting it with FDT_NOP
807 pub fn nop(mut self) -> Result<()> {
808 // SAFETY: This consumes self, so invalid node wouldn't be used any further
809 unsafe { self.nop_self() }
810 }
811
812 /// Deletes this node effectively from DT, by setting it with FDT_NOP.
813 /// This only changes bytes of the node and its properties and subnodes, and doesn't alter or
814 /// move any other part of the tree.
815 /// SAFETY: This node is no longer valid.
816 unsafe fn nop_self(&mut self) -> Result<()> {
817 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
818 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
819
820 fdt_err_expect_zero(ret)
821 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000822}
823
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000824/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000825#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100826#[repr(transparent)]
827pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000828 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100829}
830
831impl Fdt {
832 /// Wraps a slice containing a Flattened Device Tree.
833 ///
834 /// Fails if the FDT does not pass validation.
835 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000836 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100837 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
838 fdt.check_full()?;
839 Ok(fdt)
840 }
841
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000842 /// Wraps a mutable slice containing a Flattened Device Tree.
843 ///
844 /// Fails if the FDT does not pass validation.
845 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000846 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000847 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
848 fdt.check_full()?;
849 Ok(fdt)
850 }
851
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900852 /// Creates an empty Flattened Device Tree with a mutable slice.
853 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000854 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900855 // and returns error if buffer was insufficient.
856 // There will be no memory write outside of the given fdt.
857 let ret = unsafe {
858 libfdt_bindgen::fdt_create_empty_tree(
859 fdt.as_mut_ptr().cast::<c_void>(),
860 fdt.len() as i32,
861 )
862 };
863 fdt_err_expect_zero(ret)?;
864
Andrew Walbran84b9a232023-07-05 14:01:40 +0000865 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900866 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
867 fdt.check_full()?;
868
869 Ok(fdt)
870 }
871
David Brazdil1baa9a92022-06-28 14:47:50 +0100872 /// Wraps a slice containing a Flattened Device Tree.
873 ///
874 /// # Safety
875 ///
876 /// The returned FDT might be invalid, only use on slices containing a valid DT.
877 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000878 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
879 // responsible for ensuring that it is actually a valid FDT.
880 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100881 }
882
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000883 /// Wraps a mutable slice containing a Flattened Device Tree.
884 ///
885 /// # Safety
886 ///
887 /// The returned FDT might be invalid, only use on slices containing a valid DT.
888 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000889 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
890 // responsible for ensuring that it is actually a valid FDT.
891 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000892 }
893
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900894 /// Updates this FDT from a slice containing another FDT.
Jiyong Parke9d87e82023-03-21 19:28:40 +0900895 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
896 if self.buffer.len() < new_fdt.len() {
897 Err(FdtError::NoSpace)
898 } else {
899 let totalsize = self.totalsize();
900 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
901 // Zeroize the remaining part. We zeroize up to the size of the original DT because
902 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
903 // time.
904 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
905 Ok(())
906 }
907 }
908
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900909 /// Unpacks the DT to cover the whole slice it is contained in.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000910 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000911 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000912 // internal structures to make use of the whole self.fdt slice but performs no accesses
913 // outside of it and leaves the DT in a state that will be detected by other functions.
914 let ret = unsafe {
915 libfdt_bindgen::fdt_open_into(
916 self.as_ptr(),
917 self.as_mut_ptr(),
918 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
919 )
920 };
921 fdt_err_expect_zero(ret)
922 }
923
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900924 /// Packs the DT to take a minimum amount of memory.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000925 ///
926 /// Doesn't shrink the underlying memory slice.
927 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000928 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000929 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
930 fdt_err_expect_zero(ret)
931 }
932
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000933 /// Applies a DT overlay on the base DT.
934 ///
935 /// # Safety
936 ///
937 /// On failure, the library corrupts the DT and overlay so both must be discarded.
938 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000939 let ret =
940 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
941 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
942 // but that's our caller's responsibility.
943 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
944 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000945 Ok(self)
946 }
947
Alice Wang2422bdc2023-06-12 08:37:55 +0000948 /// Returns an iterator of memory banks specified the "/memory" node.
949 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100950 ///
951 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000952 pub fn memory(&self) -> Result<MemRegIterator> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900953 let memory_node_name = cstr!("/memory");
954 let memory_device_type = cstr!("memory");
David Brazdil1baa9a92022-06-28 14:47:50 +0100955
Alice Wang2422bdc2023-06-12 08:37:55 +0000956 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
957 if node.device_type()? != Some(memory_device_type) {
958 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000959 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000960 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
961 }
962
963 /// Returns the first memory range in the `/memory` node.
964 pub fn first_memory_range(&self) -> Result<Range<usize>> {
965 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100966 }
967
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900968 /// Returns the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000969 pub fn chosen(&self) -> Result<Option<FdtNode>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900970 self.node(cstr!("/chosen"))
David Brazdil1baa9a92022-06-28 14:47:50 +0100971 }
972
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900973 /// Returns the standard /chosen node as mutable.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000974 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900975 self.node_mut(cstr!("/chosen"))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000976 }
977
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900978 /// Returns the root node of the tree.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000979 pub fn root(&self) -> Result<FdtNode> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900980 self.node(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000981 }
982
Jaewan Kimf163d762023-11-01 13:12:50 +0900983 /// Returns the standard /__symbols__ node.
984 pub fn symbols(&self) -> Result<Option<FdtNode>> {
985 self.node(cstr!("/__symbols__"))
986 }
987
988 /// Returns the standard /__symbols__ node as mutable
989 pub fn symbols_mut(&mut self) -> Result<Option<FdtNodeMut>> {
990 self.node_mut(cstr!("/__symbols__"))
991 }
992
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900993 /// Returns a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000994 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
Jaewan Kimbab42592023-10-13 15:47:19 +0900995 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100996 }
997
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000998 /// Iterate over nodes with a given compatible string.
999 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
1000 CompatibleIterator::new(self, compatible)
1001 }
1002
Jaewan Kim17ba7a32023-10-19 13:25:15 +09001003 /// Returns max phandle in the tree.
1004 pub fn max_phandle(&self) -> Result<Phandle> {
1005 let mut phandle: u32 = 0;
1006 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
1007 let ret = unsafe { libfdt_bindgen::fdt_find_max_phandle(self.as_ptr(), &mut phandle) };
1008
1009 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosieba27792023-10-30 12:04:12 +00001010 phandle.try_into()
Jaewan Kim17ba7a32023-10-19 13:25:15 +09001011 }
1012
1013 /// Returns a node with the phandle
1014 pub fn node_with_phandle(&self, phandle: Phandle) -> Result<Option<FdtNode>> {
1015 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
1016 let ret = unsafe { libfdt_bindgen::fdt_node_offset_by_phandle(self.as_ptr(), phandle.0) };
1017 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self, offset }))
1018 }
1019
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001020 /// Returns the mutable root node of the tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001021 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
Jaewan Kimb635bb02023-11-01 13:00:34 +09001022 self.node_mut(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001023 }
1024
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001025 /// Returns a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001026 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
Jaewan Kimbab42592023-10-13 15:47:19 +09001027 Ok(self.path_offset(path.to_bytes())?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001028 }
1029
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001030 /// Returns the device tree as a slice (may be smaller than the containing buffer).
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001031 pub fn as_slice(&self) -> &[u8] {
1032 &self.buffer[..self.totalsize()]
1033 }
1034
Jaewan Kimbab42592023-10-13 15:47:19 +09001035 fn path_offset(&self, path: &[u8]) -> Result<Option<c_int>> {
1036 let len = path.len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +00001037 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +01001038 // function respects the passed number of characters.
1039 let ret = unsafe {
1040 // *_namelen functions don't include the trailing nul terminator in 'len'.
Jaewan Kimbab42592023-10-13 15:47:19 +09001041 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr().cast::<_>(), len)
David Brazdil1baa9a92022-06-28 14:47:50 +01001042 };
1043
Pierre-Clément Tosib244d932022-11-24 16:45:53 +00001044 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +01001045 }
1046
1047 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +00001048 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +01001049 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
1050 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
1051 // checking. The library doesn't maintain an internal state (such as pointers) between
1052 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
Pierre-Clément Tosi02017da2023-09-26 17:57:04 +01001053 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +01001054 fdt_err_expect_zero(ret)
1055 }
1056
Jaewan Kimaa638702023-09-19 13:34:01 +09001057 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
1058 let ptr = ptr as usize;
1059 let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
1060 self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
1061 }
1062
Jaewan Kim72d10902023-10-12 21:59:26 +09001063 fn string(&self, offset: c_int) -> Result<&CStr> {
1064 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
1065 let res = unsafe { libfdt_bindgen::fdt_string(self.as_ptr(), offset) };
1066 if res.is_null() {
1067 return Err(FdtError::Internal);
1068 }
1069
1070 // SAFETY: Non-null return from fdt_string() is valid null-terminating string within FDT.
1071 Ok(unsafe { CStr::from_ptr(res) })
1072 }
1073
Jaewan Kimb3dcfc22023-09-20 10:20:52 +09001074 /// Returns a shared pointer to the device tree.
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +00001075 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001076 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +01001077 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001078
1079 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001080 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001081 }
1082
1083 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +00001084 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +00001085 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001086
1087 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001088 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +00001089 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +00001090 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +00001091 }
1092
1093 fn totalsize(&self) -> usize {
1094 u32::from_be(self.header().totalsize) as usize
1095 }
David Brazdil1baa9a92022-06-28 14:47:50 +01001096}