blob: 758df2aea9b4e10646e5a76e5fe91406ec638398 [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::{
23 AddressRange, CellIterator, CompatibleIterator, MemRegIterator, RangesIterator, Reg,
Jaewan Kimbc828d72023-09-19 15:52:08 +090024 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;
David Brazdil1baa9a92022-06-28 14:47:50 +010032use core::result;
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000033use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010034
35/// Error type corresponding to libfdt error codes.
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37pub enum FdtError {
38 /// FDT_ERR_NOTFOUND
39 NotFound,
40 /// FDT_ERR_EXISTS
41 Exists,
42 /// FDT_ERR_NOSPACE
43 NoSpace,
44 /// FDT_ERR_BADOFFSET
45 BadOffset,
46 /// FDT_ERR_BADPATH
47 BadPath,
48 /// FDT_ERR_BADPHANDLE
49 BadPhandle,
50 /// FDT_ERR_BADSTATE
51 BadState,
52 /// FDT_ERR_TRUNCATED
53 Truncated,
54 /// FDT_ERR_BADMAGIC
55 BadMagic,
56 /// FDT_ERR_BADVERSION
57 BadVersion,
58 /// FDT_ERR_BADSTRUCTURE
59 BadStructure,
60 /// FDT_ERR_BADLAYOUT
61 BadLayout,
62 /// FDT_ERR_INTERNAL
63 Internal,
64 /// FDT_ERR_BADNCELLS
65 BadNCells,
66 /// FDT_ERR_BADVALUE
67 BadValue,
68 /// FDT_ERR_BADOVERLAY
69 BadOverlay,
70 /// FDT_ERR_NOPHANDLES
71 NoPhandles,
72 /// FDT_ERR_BADFLAGS
73 BadFlags,
74 /// FDT_ERR_ALIGNMENT
75 Alignment,
76 /// Unexpected error code
77 Unknown(i32),
78}
79
80impl fmt::Display for FdtError {
81 /// Prints error messages from libfdt.h documentation.
82 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83 match self {
84 Self::NotFound => write!(f, "The requested node or property does not exist"),
85 Self::Exists => write!(f, "Attempted to create an existing node or property"),
86 Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"),
87 Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"),
88 Self::BadPath => write!(f, "Badly formatted path"),
89 Self::BadPhandle => write!(f, "Invalid phandle length or value"),
90 Self::BadState => write!(f, "Received incomplete device tree"),
91 Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"),
92 Self::BadMagic => write!(f, "Device tree header missing its magic number"),
93 Self::BadVersion => write!(f, "Device tree has a version which can't be handled"),
94 Self::BadStructure => write!(f, "Device tree has a corrupt structure block"),
95 Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"),
96 Self::Internal => write!(f, "libfdt has failed an internal assertion"),
97 Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"),
98 Self::BadValue => write!(f, "Unexpected property value"),
99 Self::BadOverlay => write!(f, "Overlay cannot be applied"),
100 Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"),
101 Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"),
102 Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"),
103 Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"),
104 }
105 }
106}
107
108/// Result type with FdtError enum.
109pub type Result<T> = result::Result<T, FdtError>;
110
111fn fdt_err(val: c_int) -> Result<c_int> {
112 if val >= 0 {
113 Ok(val)
114 } else {
115 Err(match -val as _ {
116 libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound,
117 libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists,
118 libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace,
119 libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset,
120 libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath,
121 libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle,
122 libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState,
123 libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated,
124 libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic,
125 libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion,
126 libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure,
127 libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout,
128 libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal,
129 libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells,
130 libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue,
131 libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay,
132 libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles,
133 libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags,
134 libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment,
135 _ => FdtError::Unknown(val),
136 })
137 }
138}
139
140fn fdt_err_expect_zero(val: c_int) -> Result<()> {
141 match fdt_err(val)? {
142 0 => Ok(()),
143 _ => Err(FdtError::Unknown(val)),
144 }
145}
146
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000147fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> {
148 match fdt_err(val) {
149 Ok(val) => Ok(Some(val)),
150 Err(FdtError::NotFound) => Ok(None),
151 Err(e) => Err(e),
152 }
153}
154
David Brazdil1baa9a92022-06-28 14:47:50 +0100155/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000156#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100157enum AddrCells {
158 Single = 1,
159 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000160 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100161}
162
163impl TryFrom<c_int> for AddrCells {
164 type Error = FdtError;
165
166 fn try_from(res: c_int) -> Result<Self> {
167 match fdt_err(res)? {
168 x if x == Self::Single as c_int => Ok(Self::Single),
169 x if x == Self::Double as c_int => Ok(Self::Double),
Andrew Walbranb39e6922022-12-05 17:01:20 +0000170 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100171 _ => Err(FdtError::BadNCells),
172 }
173 }
174}
175
176/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000177#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100178enum SizeCells {
179 None = 0,
180 Single = 1,
181 Double = 2,
182}
183
184impl TryFrom<c_int> for SizeCells {
185 type Error = FdtError;
186
187 fn try_from(res: c_int) -> Result<Self> {
188 match fdt_err(res)? {
189 x if x == Self::None as c_int => Ok(Self::None),
190 x if x == Self::Single as c_int => Ok(Self::Single),
191 x if x == Self::Double as c_int => Ok(Self::Double),
192 _ => Err(FdtError::BadNCells),
193 }
194 }
195}
196
David Brazdil1baa9a92022-06-28 14:47:50 +0100197/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000198#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100199pub struct FdtNode<'a> {
200 fdt: &'a Fdt,
201 offset: c_int,
202}
203
204impl<'a> FdtNode<'a> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900205 /// Create immutable node from a mutable node at the same offset
206 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
207 FdtNode { fdt: other.fdt, offset: other.offset }
208 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100209 /// Find parent node.
210 pub fn parent(&self) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000211 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100212 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
213
214 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
215 }
216
217 /// Retrieve the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000218 pub fn device_type(&self) -> Result<Option<&CStr>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100219 self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap())
220 }
221
222 /// Retrieve the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000223 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
224 let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100225
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000226 if let Some(cells) = self.getprop_cells(reg)? {
227 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100228
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000229 let addr_cells = parent.address_cells()?;
230 let size_cells = parent.size_cells()?;
231
232 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
233 } else {
234 Ok(None)
235 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100236 }
237
Andrew Walbranb39e6922022-12-05 17:01:20 +0000238 /// Retrieves the standard ranges property.
239 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
240 let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap();
241 if let Some(cells) = self.getprop_cells(ranges)? {
242 let parent = self.parent()?;
243 let addr_cells = self.address_cells()?;
244 let parent_addr_cells = parent.address_cells()?;
245 let size_cells = self.size_cells()?;
246 Ok(Some(RangesIterator::<A, P, S>::new(
247 cells,
248 addr_cells,
249 parent_addr_cells,
250 size_cells,
251 )))
252 } else {
253 Ok(None)
254 }
255 }
256
Jaewan Kimaa638702023-09-19 13:34:01 +0900257 /// Returns the node name.
258 pub fn name(&self) -> Result<&'a CStr> {
259 let mut len: c_int = 0;
260 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
261 // function returns valid null terminating string and otherwise returned values are dropped.
262 let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
263 as *const c_void;
264 let len = usize::try_from(fdt_err(len)?).unwrap();
265 let name = self.fdt.get_from_ptr(name, len + 1)?;
266 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
267 }
268
David Brazdil1baa9a92022-06-28 14:47:50 +0100269 /// Retrieve the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000270 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
271 let value = if let Some(bytes) = self.getprop(name)? {
272 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
273 } else {
274 None
275 };
276 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100277 }
278
279 /// Retrieve the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000280 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
281 if let Some(cells) = self.getprop(name)? {
282 Ok(Some(CellIterator::new(cells)))
283 } else {
284 Ok(None)
285 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100286 }
287
288 /// Retrieve the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000289 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
290 let value = if let Some(bytes) = self.getprop(name)? {
291 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
292 } else {
293 None
294 };
295 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100296 }
297
298 /// Retrieve the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000299 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
300 let value = if let Some(bytes) = self.getprop(name)? {
301 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
302 } else {
303 None
304 };
305 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100306 }
307
308 /// Retrieve the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000309 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900310 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900311 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900312 } else {
313 Ok(None) // property was not found
314 }
315 }
316
317 /// Return the pointer and size of the property named `name`, in a node at offset `offset`, in
318 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
319 fn getprop_internal(
320 fdt: &'a Fdt,
321 offset: c_int,
322 name: &CStr,
323 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100324 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000325 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100326 // function respects the passed number of characters.
327 let prop = unsafe {
328 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900329 fdt.as_ptr(),
330 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100331 name.as_ptr(),
332 // *_namelen functions don't include the trailing nul terminator in 'len'.
333 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
334 &mut len as *mut i32,
335 )
336 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000337
338 let Some(len) = fdt_err_or_option(len)? else {
339 return Ok(None); // Property was not found.
340 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900341 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000342
David Brazdil1baa9a92022-06-28 14:47:50 +0100343 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000344 // We expected an error code in len but still received a valid value?!
345 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100346 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900347 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100348 }
349
350 /// Get reference to the containing device tree.
351 pub fn fdt(&self) -> &Fdt {
352 self.fdt
353 }
354
Alice Wang474c0ee2023-09-14 12:52:33 +0000355 /// Returns the compatible node of the given name that is next after this node.
356 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000357 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000358 let ret = unsafe {
359 libfdt_bindgen::fdt_node_offset_by_compatible(
360 self.fdt.as_ptr(),
361 self.offset,
362 compatible.as_ptr(),
363 )
364 };
365
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000366 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000367 }
368
Alice Wang474c0ee2023-09-14 12:52:33 +0000369 /// Returns the first range of `reg` in this node.
370 pub fn first_reg(&self) -> Result<Reg<u64>> {
371 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
372 }
373
David Brazdil1baa9a92022-06-28 14:47:50 +0100374 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000375 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100376 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
377 .try_into()
378 .map_err(|_| FdtError::Internal)
379 }
380
381 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000382 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100383 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
384 .try_into()
385 .map_err(|_| FdtError::Internal)
386 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900387
388 /// Returns an iterator of subnodes
389 pub fn subnodes(&'a self) -> Result<SubnodeIterator<'a>> {
390 SubnodeIterator::new(self)
391 }
392
393 fn first_subnode(&self) -> Result<Option<Self>> {
394 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
395 let ret = unsafe { libfdt_bindgen::fdt_first_subnode(self.fdt.as_ptr(), self.offset) };
396
397 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
398 }
399
400 fn next_subnode(&self) -> Result<Option<Self>> {
401 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
402 let ret = unsafe { libfdt_bindgen::fdt_next_subnode(self.fdt.as_ptr(), self.offset) };
403
404 Ok(fdt_err_or_option(ret)?.map(|offset| FdtNode { fdt: self.fdt, offset }))
405 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100406}
407
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000408/// Mutable FDT node.
409pub struct FdtNodeMut<'a> {
410 fdt: &'a mut Fdt,
411 offset: c_int,
412}
413
414impl<'a> FdtNodeMut<'a> {
415 /// Append a property name-value (possibly empty) pair to the given node.
416 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000417 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000418 let ret = unsafe {
419 libfdt_bindgen::fdt_appendprop(
420 self.fdt.as_mut_ptr(),
421 self.offset,
422 name.as_ptr(),
423 value.as_ref().as_ptr().cast::<c_void>(),
424 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
425 )
426 };
427
428 fdt_err_expect_zero(ret)
429 }
430
431 /// Append a (address, size) pair property to the given node.
432 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000433 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000434 let ret = unsafe {
435 libfdt_bindgen::fdt_appendprop_addrrange(
436 self.fdt.as_mut_ptr(),
437 self.parent()?.offset,
438 self.offset,
439 name.as_ptr(),
440 addr,
441 size,
442 )
443 };
444
445 fdt_err_expect_zero(ret)
446 }
447
Jaewan Kimba8929b2023-01-13 11:13:29 +0900448 /// Create or change a property name-value pair to the given node.
449 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000450 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900451 // (validated by underlying libfdt).
452 let ret = unsafe {
453 libfdt_bindgen::fdt_setprop(
454 self.fdt.as_mut_ptr(),
455 self.offset,
456 name.as_ptr(),
457 value.as_ptr().cast::<c_void>(),
458 value.len().try_into().map_err(|_| FdtError::BadValue)?,
459 )
460 };
461
462 fdt_err_expect_zero(ret)
463 }
464
Jiyong Park9c63cd12023-03-21 17:53:07 +0900465 /// Replace the value of the given property with the given value, and ensure that the given
466 /// value has the same length as the current value length
467 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000468 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900469 let ret = unsafe {
470 libfdt_bindgen::fdt_setprop_inplace(
471 self.fdt.as_mut_ptr(),
472 self.offset,
473 name.as_ptr(),
474 value.as_ptr().cast::<c_void>(),
475 value.len().try_into().map_err(|_| FdtError::BadValue)?,
476 )
477 };
478
479 fdt_err_expect_zero(ret)
480 }
481
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000482 /// Replace the value of the given (address, size) pair property with the given value, and
483 /// ensure that the given value has the same length as the current value length
484 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
485 let pair = [addr.to_be(), size.to_be()];
486 self.setprop_inplace(name, pair.as_bytes())
487 }
488
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000489 /// Create or change a flag-like empty property.
490 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
491 self.setprop(name, &[])
492 }
493
494 /// Delete the given property.
495 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000496 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000497 // library locates the node's property. Removing the property may shift the offsets of
498 // other nodes and properties but the borrow checker should prevent this function from
499 // being called when FdtNode instances are in use.
500 let ret = unsafe {
501 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
502 };
503
504 fdt_err_expect_zero(ret)
505 }
506
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000507 /// Overwrite the given property with FDT_NOP, effectively removing it from the DT.
508 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000509 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000510 // library locates the node's property.
511 let ret = unsafe {
512 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
513 };
514
515 fdt_err_expect_zero(ret)
516 }
517
Jiyong Park9c63cd12023-03-21 17:53:07 +0900518 /// Reduce the size of the given property to new_size
519 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
520 let (prop, len) =
521 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
522 if len == new_size {
523 return Ok(());
524 }
525 if new_size > len {
526 return Err(FdtError::NoSpace);
527 }
528
Andrew Walbran84b9a232023-07-05 14:01:40 +0000529 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900530 let ret = unsafe {
531 libfdt_bindgen::fdt_setprop(
532 self.fdt.as_mut_ptr(),
533 self.offset,
534 name.as_ptr(),
535 prop.cast::<c_void>(),
536 new_size.try_into().map_err(|_| FdtError::BadValue)?,
537 )
538 };
539
540 fdt_err_expect_zero(ret)
541 }
542
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000543 /// Get reference to the containing device tree.
544 pub fn fdt(&mut self) -> &mut Fdt {
545 self.fdt
546 }
547
548 /// Add a new subnode to the given node and return it as a FdtNodeMut on success.
549 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000550 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000551 let ret = unsafe {
552 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
553 };
554
555 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
556 }
557
558 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000559 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000560 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
561
562 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
563 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900564
Alice Wang474c0ee2023-09-14 12:52:33 +0000565 /// Returns the compatible node of the given name that is next after this node
Jiyong Park9c63cd12023-03-21 17:53:07 +0900566 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000567 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900568 let ret = unsafe {
569 libfdt_bindgen::fdt_node_offset_by_compatible(
570 self.fdt.as_ptr(),
571 self.offset,
572 compatible.as_ptr(),
573 )
574 };
575
576 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
577 }
578
579 /// Replace this node and its subtree with nop tags, effectively removing it from the tree, and
580 /// then return the next compatible node of the given name.
581 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
582 // The reason is that libfdt ensures that the node from where the search for the next
583 // compatible node is started is always a valid one -- except for the special case of offset =
584 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
585 // next compatible node from it.
586 //
587 // We can't do in the opposite direction either. If we call next_compatible to find the next
588 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
589 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
590 // DT).
591 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000592 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900593 let ret = unsafe {
594 libfdt_bindgen::fdt_node_offset_by_compatible(
595 self.fdt.as_ptr(),
596 self.offset,
597 compatible.as_ptr(),
598 )
599 };
600 let next_offset = fdt_err_or_option(ret)?;
601
Andrew Walbran84b9a232023-07-05 14:01:40 +0000602 // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its
Jiyong Park9c63cd12023-03-21 17:53:07 +0900603 // properties and subnodes, and will not alter or move any other part of the tree.
604 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
605 fdt_err_expect_zero(ret)?;
606
607 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
608 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000609}
610
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000611/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000612#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100613#[repr(transparent)]
614pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000615 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100616}
617
618impl Fdt {
619 /// Wraps a slice containing a Flattened Device Tree.
620 ///
621 /// Fails if the FDT does not pass validation.
622 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000623 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100624 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
625 fdt.check_full()?;
626 Ok(fdt)
627 }
628
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000629 /// Wraps a mutable slice containing a Flattened Device Tree.
630 ///
631 /// Fails if the FDT does not pass validation.
632 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000633 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000634 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
635 fdt.check_full()?;
636 Ok(fdt)
637 }
638
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900639 /// Creates an empty Flattened Device Tree with a mutable slice.
640 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000641 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900642 // and returns error if buffer was insufficient.
643 // There will be no memory write outside of the given fdt.
644 let ret = unsafe {
645 libfdt_bindgen::fdt_create_empty_tree(
646 fdt.as_mut_ptr().cast::<c_void>(),
647 fdt.len() as i32,
648 )
649 };
650 fdt_err_expect_zero(ret)?;
651
Andrew Walbran84b9a232023-07-05 14:01:40 +0000652 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900653 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
654 fdt.check_full()?;
655
656 Ok(fdt)
657 }
658
David Brazdil1baa9a92022-06-28 14:47:50 +0100659 /// Wraps a slice containing a Flattened Device Tree.
660 ///
661 /// # Safety
662 ///
663 /// The returned FDT might be invalid, only use on slices containing a valid DT.
664 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000665 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
666 // responsible for ensuring that it is actually a valid FDT.
667 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100668 }
669
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000670 /// Wraps a mutable slice containing a Flattened Device Tree.
671 ///
672 /// # Safety
673 ///
674 /// The returned FDT might be invalid, only use on slices containing a valid DT.
675 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000676 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
677 // responsible for ensuring that it is actually a valid FDT.
678 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000679 }
680
Jiyong Parke9d87e82023-03-21 19:28:40 +0900681 /// Update this FDT from a slice containing another FDT
682 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
683 if self.buffer.len() < new_fdt.len() {
684 Err(FdtError::NoSpace)
685 } else {
686 let totalsize = self.totalsize();
687 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
688 // Zeroize the remaining part. We zeroize up to the size of the original DT because
689 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
690 // time.
691 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
692 Ok(())
693 }
694 }
695
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000696 /// Make the whole slice containing the DT available to libfdt.
697 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000698 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000699 // internal structures to make use of the whole self.fdt slice but performs no accesses
700 // outside of it and leaves the DT in a state that will be detected by other functions.
701 let ret = unsafe {
702 libfdt_bindgen::fdt_open_into(
703 self.as_ptr(),
704 self.as_mut_ptr(),
705 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
706 )
707 };
708 fdt_err_expect_zero(ret)
709 }
710
711 /// Pack the DT to take a minimum amount of memory.
712 ///
713 /// Doesn't shrink the underlying memory slice.
714 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000715 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000716 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
717 fdt_err_expect_zero(ret)
718 }
719
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000720 /// Applies a DT overlay on the base DT.
721 ///
722 /// # Safety
723 ///
724 /// On failure, the library corrupts the DT and overlay so both must be discarded.
725 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000726 let ret =
727 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
728 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
729 // but that's our caller's responsibility.
730 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
731 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000732 Ok(self)
733 }
734
Alice Wang2422bdc2023-06-12 08:37:55 +0000735 /// Returns an iterator of memory banks specified the "/memory" node.
736 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100737 ///
738 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000739 pub fn memory(&self) -> Result<MemRegIterator> {
740 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
741 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100742
Alice Wang2422bdc2023-06-12 08:37:55 +0000743 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
744 if node.device_type()? != Some(memory_device_type) {
745 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000746 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000747 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
748 }
749
750 /// Returns the first memory range in the `/memory` node.
751 pub fn first_memory_range(&self) -> Result<Range<usize>> {
752 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100753 }
754
755 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000756 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100757 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
758 }
759
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000760 /// Retrieve the standard /chosen node as mutable.
761 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
762 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
763 }
764
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000765 /// Get the root node of the tree.
766 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000767 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000768 }
769
David Brazdil1baa9a92022-06-28 14:47:50 +0100770 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000771 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
772 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100773 }
774
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000775 /// Iterate over nodes with a given compatible string.
776 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
777 CompatibleIterator::new(self, compatible)
778 }
779
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000780 /// Get the mutable root node of the tree.
781 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
782 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
783 }
784
785 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000786 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
787 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000788 }
789
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000790 /// Return the device tree as a slice (may be smaller than the containing buffer).
791 pub fn as_slice(&self) -> &[u8] {
792 &self.buffer[..self.totalsize()]
793 }
794
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000795 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100796 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000797 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100798 // function respects the passed number of characters.
799 let ret = unsafe {
800 // *_namelen functions don't include the trailing nul terminator in 'len'.
801 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
802 };
803
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000804 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100805 }
806
807 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000808 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +0100809 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
810 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
811 // checking. The library doesn't maintain an internal state (such as pointers) between
812 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
Pierre-Clément Tosi02017da2023-09-26 17:57:04 +0100813 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +0100814 fdt_err_expect_zero(ret)
815 }
816
Jaewan Kimaa638702023-09-19 13:34:01 +0900817 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
818 let ptr = ptr as usize;
819 let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
820 self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
821 }
822
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000823 /// Return a shared pointer to the device tree.
824 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000825 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100826 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000827
828 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000829 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000830 }
831
832 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000833 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000834 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000835
836 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000837 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000838 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000839 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000840 }
841
842 fn totalsize(&self) -> usize {
843 u32::from_be(self.header().totalsize) as usize
844 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100845}