blob: 8e0bb6538caa1f7b6b65f6f625b6d42e06e314a5 [file] [log] [blame]
David Brazdil1baa9a92022-06-28 14:47:50 +01001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Wrapper around libfdt library. Provides parsing/generating functionality
16//! to a bare-metal environment.
17
18#![no_std]
19
Andrew Walbran55ad01b2022-12-05 17:00:40 +000020mod iterators;
21
Andrew Walbranb39e6922022-12-05 17:01:20 +000022pub use iterators::{AddressRange, CellIterator, MemRegIterator, RangesIterator, Reg, RegIterator};
Andrew Walbran55ad01b2022-12-05 17:00:40 +000023
Jiyong Parke9d87e82023-03-21 19:28:40 +090024use core::cmp::max;
David Brazdil1baa9a92022-06-28 14:47:50 +010025use core::ffi::{c_int, c_void, CStr};
26use core::fmt;
27use core::mem;
Alice Wang2422bdc2023-06-12 08:37:55 +000028use core::ops::Range;
David Brazdil1baa9a92022-06-28 14:47:50 +010029use core::result;
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000030use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010031
32/// Error type corresponding to libfdt error codes.
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum FdtError {
35 /// FDT_ERR_NOTFOUND
36 NotFound,
37 /// FDT_ERR_EXISTS
38 Exists,
39 /// FDT_ERR_NOSPACE
40 NoSpace,
41 /// FDT_ERR_BADOFFSET
42 BadOffset,
43 /// FDT_ERR_BADPATH
44 BadPath,
45 /// FDT_ERR_BADPHANDLE
46 BadPhandle,
47 /// FDT_ERR_BADSTATE
48 BadState,
49 /// FDT_ERR_TRUNCATED
50 Truncated,
51 /// FDT_ERR_BADMAGIC
52 BadMagic,
53 /// FDT_ERR_BADVERSION
54 BadVersion,
55 /// FDT_ERR_BADSTRUCTURE
56 BadStructure,
57 /// FDT_ERR_BADLAYOUT
58 BadLayout,
59 /// FDT_ERR_INTERNAL
60 Internal,
61 /// FDT_ERR_BADNCELLS
62 BadNCells,
63 /// FDT_ERR_BADVALUE
64 BadValue,
65 /// FDT_ERR_BADOVERLAY
66 BadOverlay,
67 /// FDT_ERR_NOPHANDLES
68 NoPhandles,
69 /// FDT_ERR_BADFLAGS
70 BadFlags,
71 /// FDT_ERR_ALIGNMENT
72 Alignment,
73 /// Unexpected error code
74 Unknown(i32),
75}
76
77impl fmt::Display for FdtError {
78 /// Prints error messages from libfdt.h documentation.
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80 match self {
81 Self::NotFound => write!(f, "The requested node or property does not exist"),
82 Self::Exists => write!(f, "Attempted to create an existing node or property"),
83 Self::NoSpace => write!(f, "Insufficient buffer space to contain the expanded tree"),
84 Self::BadOffset => write!(f, "Structure block offset is out-of-bounds or invalid"),
85 Self::BadPath => write!(f, "Badly formatted path"),
86 Self::BadPhandle => write!(f, "Invalid phandle length or value"),
87 Self::BadState => write!(f, "Received incomplete device tree"),
88 Self::Truncated => write!(f, "Device tree or sub-block is improperly terminated"),
89 Self::BadMagic => write!(f, "Device tree header missing its magic number"),
90 Self::BadVersion => write!(f, "Device tree has a version which can't be handled"),
91 Self::BadStructure => write!(f, "Device tree has a corrupt structure block"),
92 Self::BadLayout => write!(f, "Device tree sub-blocks in unsupported order"),
93 Self::Internal => write!(f, "libfdt has failed an internal assertion"),
94 Self::BadNCells => write!(f, "Bad format or value of #address-cells or #size-cells"),
95 Self::BadValue => write!(f, "Unexpected property value"),
96 Self::BadOverlay => write!(f, "Overlay cannot be applied"),
97 Self::NoPhandles => write!(f, "Device tree doesn't have any phandle available anymore"),
98 Self::BadFlags => write!(f, "Invalid flag or invalid combination of flags"),
99 Self::Alignment => write!(f, "Device tree base address is not 8-byte aligned"),
100 Self::Unknown(e) => write!(f, "Unknown libfdt error '{e}'"),
101 }
102 }
103}
104
105/// Result type with FdtError enum.
106pub type Result<T> = result::Result<T, FdtError>;
107
108fn fdt_err(val: c_int) -> Result<c_int> {
109 if val >= 0 {
110 Ok(val)
111 } else {
112 Err(match -val as _ {
113 libfdt_bindgen::FDT_ERR_NOTFOUND => FdtError::NotFound,
114 libfdt_bindgen::FDT_ERR_EXISTS => FdtError::Exists,
115 libfdt_bindgen::FDT_ERR_NOSPACE => FdtError::NoSpace,
116 libfdt_bindgen::FDT_ERR_BADOFFSET => FdtError::BadOffset,
117 libfdt_bindgen::FDT_ERR_BADPATH => FdtError::BadPath,
118 libfdt_bindgen::FDT_ERR_BADPHANDLE => FdtError::BadPhandle,
119 libfdt_bindgen::FDT_ERR_BADSTATE => FdtError::BadState,
120 libfdt_bindgen::FDT_ERR_TRUNCATED => FdtError::Truncated,
121 libfdt_bindgen::FDT_ERR_BADMAGIC => FdtError::BadMagic,
122 libfdt_bindgen::FDT_ERR_BADVERSION => FdtError::BadVersion,
123 libfdt_bindgen::FDT_ERR_BADSTRUCTURE => FdtError::BadStructure,
124 libfdt_bindgen::FDT_ERR_BADLAYOUT => FdtError::BadLayout,
125 libfdt_bindgen::FDT_ERR_INTERNAL => FdtError::Internal,
126 libfdt_bindgen::FDT_ERR_BADNCELLS => FdtError::BadNCells,
127 libfdt_bindgen::FDT_ERR_BADVALUE => FdtError::BadValue,
128 libfdt_bindgen::FDT_ERR_BADOVERLAY => FdtError::BadOverlay,
129 libfdt_bindgen::FDT_ERR_NOPHANDLES => FdtError::NoPhandles,
130 libfdt_bindgen::FDT_ERR_BADFLAGS => FdtError::BadFlags,
131 libfdt_bindgen::FDT_ERR_ALIGNMENT => FdtError::Alignment,
132 _ => FdtError::Unknown(val),
133 })
134 }
135}
136
137fn fdt_err_expect_zero(val: c_int) -> Result<()> {
138 match fdt_err(val)? {
139 0 => Ok(()),
140 _ => Err(FdtError::Unknown(val)),
141 }
142}
143
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000144fn fdt_err_or_option(val: c_int) -> Result<Option<c_int>> {
145 match fdt_err(val) {
146 Ok(val) => Ok(Some(val)),
147 Err(FdtError::NotFound) => Ok(None),
148 Err(e) => Err(e),
149 }
150}
151
David Brazdil1baa9a92022-06-28 14:47:50 +0100152/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000153#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100154enum AddrCells {
155 Single = 1,
156 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +0000157 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +0100158}
159
160impl TryFrom<c_int> for AddrCells {
161 type Error = FdtError;
162
163 fn try_from(res: c_int) -> Result<Self> {
164 match fdt_err(res)? {
165 x if x == Self::Single as c_int => Ok(Self::Single),
166 x if x == Self::Double as c_int => Ok(Self::Double),
Andrew Walbranb39e6922022-12-05 17:01:20 +0000167 x if x == Self::Triple as c_int => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +0100168 _ => Err(FdtError::BadNCells),
169 }
170 }
171}
172
173/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000174#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100175enum SizeCells {
176 None = 0,
177 Single = 1,
178 Double = 2,
179}
180
181impl TryFrom<c_int> for SizeCells {
182 type Error = FdtError;
183
184 fn try_from(res: c_int) -> Result<Self> {
185 match fdt_err(res)? {
186 x if x == Self::None as c_int => Ok(Self::None),
187 x if x == Self::Single as c_int => Ok(Self::Single),
188 x if x == Self::Double as c_int => Ok(Self::Double),
189 _ => Err(FdtError::BadNCells),
190 }
191 }
192}
193
David Brazdil1baa9a92022-06-28 14:47:50 +0100194/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000195#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100196pub struct FdtNode<'a> {
197 fdt: &'a Fdt,
198 offset: c_int,
199}
200
201impl<'a> FdtNode<'a> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900202 /// Create immutable node from a mutable node at the same offset
203 pub fn from_mut(other: &'a FdtNodeMut) -> Self {
204 FdtNode { fdt: other.fdt, offset: other.offset }
205 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100206 /// Find parent node.
207 pub fn parent(&self) -> Result<Self> {
208 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
209 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
210
211 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
212 }
213
214 /// Retrieve the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000215 pub fn device_type(&self) -> Result<Option<&CStr>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100216 self.getprop_str(CStr::from_bytes_with_nul(b"device_type\0").unwrap())
217 }
218
219 /// Retrieve the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000220 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
221 let reg = CStr::from_bytes_with_nul(b"reg\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100222
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000223 if let Some(cells) = self.getprop_cells(reg)? {
224 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100225
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000226 let addr_cells = parent.address_cells()?;
227 let size_cells = parent.size_cells()?;
228
229 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
230 } else {
231 Ok(None)
232 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100233 }
234
Andrew Walbranb39e6922022-12-05 17:01:20 +0000235 /// Retrieves the standard ranges property.
236 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
237 let ranges = CStr::from_bytes_with_nul(b"ranges\0").unwrap();
238 if let Some(cells) = self.getprop_cells(ranges)? {
239 let parent = self.parent()?;
240 let addr_cells = self.address_cells()?;
241 let parent_addr_cells = parent.address_cells()?;
242 let size_cells = self.size_cells()?;
243 Ok(Some(RangesIterator::<A, P, S>::new(
244 cells,
245 addr_cells,
246 parent_addr_cells,
247 size_cells,
248 )))
249 } else {
250 Ok(None)
251 }
252 }
253
David Brazdil1baa9a92022-06-28 14:47:50 +0100254 /// Retrieve the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000255 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
256 let value = if let Some(bytes) = self.getprop(name)? {
257 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
258 } else {
259 None
260 };
261 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100262 }
263
264 /// Retrieve the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000265 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
266 if let Some(cells) = self.getprop(name)? {
267 Ok(Some(CellIterator::new(cells)))
268 } else {
269 Ok(None)
270 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100271 }
272
273 /// Retrieve the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000274 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
275 let value = if let Some(bytes) = self.getprop(name)? {
276 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
277 } else {
278 None
279 };
280 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100281 }
282
283 /// Retrieve the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000284 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
285 let value = if let Some(bytes) = self.getprop(name)? {
286 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
287 } else {
288 None
289 };
290 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100291 }
292
293 /// Retrieve the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000294 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900295 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
296 let offset = (prop as usize)
297 .checked_sub(self.fdt.as_ptr() as usize)
298 .ok_or(FdtError::Internal)?;
299
300 Ok(Some(self.fdt.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)?))
301 } else {
302 Ok(None) // property was not found
303 }
304 }
305
306 /// Return the pointer and size of the property named `name`, in a node at offset `offset`, in
307 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
308 fn getprop_internal(
309 fdt: &'a Fdt,
310 offset: c_int,
311 name: &CStr,
312 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100313 let mut len: i32 = 0;
314 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) and the
315 // function respects the passed number of characters.
316 let prop = unsafe {
317 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900318 fdt.as_ptr(),
319 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100320 name.as_ptr(),
321 // *_namelen functions don't include the trailing nul terminator in 'len'.
322 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
323 &mut len as *mut i32,
324 )
325 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000326
327 let Some(len) = fdt_err_or_option(len)? else {
328 return Ok(None); // Property was not found.
329 };
330 let len = usize::try_from(len).map_err(|_| FdtError::Internal)?;
331
David Brazdil1baa9a92022-06-28 14:47:50 +0100332 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000333 // We expected an error code in len but still received a valid value?!
334 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100335 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900336 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100337 }
338
339 /// Get reference to the containing device tree.
340 pub fn fdt(&self) -> &Fdt {
341 self.fdt
342 }
343
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000344 fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
345 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
346 let ret = unsafe {
347 libfdt_bindgen::fdt_node_offset_by_compatible(
348 self.fdt.as_ptr(),
349 self.offset,
350 compatible.as_ptr(),
351 )
352 };
353
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000354 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000355 }
356
David Brazdil1baa9a92022-06-28 14:47:50 +0100357 fn address_cells(&self) -> Result<AddrCells> {
358 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
359 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
360 .try_into()
361 .map_err(|_| FdtError::Internal)
362 }
363
364 fn size_cells(&self) -> Result<SizeCells> {
365 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
366 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
367 .try_into()
368 .map_err(|_| FdtError::Internal)
369 }
370}
371
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000372/// Mutable FDT node.
373pub struct FdtNodeMut<'a> {
374 fdt: &'a mut Fdt,
375 offset: c_int,
376}
377
378impl<'a> FdtNodeMut<'a> {
379 /// Append a property name-value (possibly empty) pair to the given node.
380 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
381 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
382 let ret = unsafe {
383 libfdt_bindgen::fdt_appendprop(
384 self.fdt.as_mut_ptr(),
385 self.offset,
386 name.as_ptr(),
387 value.as_ref().as_ptr().cast::<c_void>(),
388 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
389 )
390 };
391
392 fdt_err_expect_zero(ret)
393 }
394
395 /// Append a (address, size) pair property to the given node.
396 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
397 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
398 let ret = unsafe {
399 libfdt_bindgen::fdt_appendprop_addrrange(
400 self.fdt.as_mut_ptr(),
401 self.parent()?.offset,
402 self.offset,
403 name.as_ptr(),
404 addr,
405 size,
406 )
407 };
408
409 fdt_err_expect_zero(ret)
410 }
411
Jaewan Kimba8929b2023-01-13 11:13:29 +0900412 /// Create or change a property name-value pair to the given node.
413 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
414 // SAFETY - New value size is constrained to the DT totalsize
415 // (validated by underlying libfdt).
416 let ret = unsafe {
417 libfdt_bindgen::fdt_setprop(
418 self.fdt.as_mut_ptr(),
419 self.offset,
420 name.as_ptr(),
421 value.as_ptr().cast::<c_void>(),
422 value.len().try_into().map_err(|_| FdtError::BadValue)?,
423 )
424 };
425
426 fdt_err_expect_zero(ret)
427 }
428
Jiyong Park9c63cd12023-03-21 17:53:07 +0900429 /// Replace the value of the given property with the given value, and ensure that the given
430 /// value has the same length as the current value length
431 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
432 // SAFETY - fdt size is not altered
433 let ret = unsafe {
434 libfdt_bindgen::fdt_setprop_inplace(
435 self.fdt.as_mut_ptr(),
436 self.offset,
437 name.as_ptr(),
438 value.as_ptr().cast::<c_void>(),
439 value.len().try_into().map_err(|_| FdtError::BadValue)?,
440 )
441 };
442
443 fdt_err_expect_zero(ret)
444 }
445
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000446 /// Replace the value of the given (address, size) pair property with the given value, and
447 /// ensure that the given value has the same length as the current value length
448 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
449 let pair = [addr.to_be(), size.to_be()];
450 self.setprop_inplace(name, pair.as_bytes())
451 }
452
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000453 /// Create or change a flag-like empty property.
454 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
455 self.setprop(name, &[])
456 }
457
458 /// Delete the given property.
459 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
460 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) when the
461 // library locates the node's property. Removing the property may shift the offsets of
462 // other nodes and properties but the borrow checker should prevent this function from
463 // being called when FdtNode instances are in use.
464 let ret = unsafe {
465 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
466 };
467
468 fdt_err_expect_zero(ret)
469 }
470
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000471 /// Overwrite the given property with FDT_NOP, effectively removing it from the DT.
472 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
473 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) when the
474 // library locates the node's property.
475 let ret = unsafe {
476 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
477 };
478
479 fdt_err_expect_zero(ret)
480 }
481
Jiyong Park9c63cd12023-03-21 17:53:07 +0900482 /// Reduce the size of the given property to new_size
483 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
484 let (prop, len) =
485 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
486 if len == new_size {
487 return Ok(());
488 }
489 if new_size > len {
490 return Err(FdtError::NoSpace);
491 }
492
493 // SAFETY - new_size is smaller than the old size
494 let ret = unsafe {
495 libfdt_bindgen::fdt_setprop(
496 self.fdt.as_mut_ptr(),
497 self.offset,
498 name.as_ptr(),
499 prop.cast::<c_void>(),
500 new_size.try_into().map_err(|_| FdtError::BadValue)?,
501 )
502 };
503
504 fdt_err_expect_zero(ret)
505 }
506
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000507 /// Get reference to the containing device tree.
508 pub fn fdt(&mut self) -> &mut Fdt {
509 self.fdt
510 }
511
512 /// Add a new subnode to the given node and return it as a FdtNodeMut on success.
513 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
514 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor).
515 let ret = unsafe {
516 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
517 };
518
519 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
520 }
521
522 fn parent(&'a self) -> Result<FdtNode<'a>> {
523 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
524 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
525
526 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
527 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900528
529 /// Return the compatible node of the given name that is next to this node
530 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
531 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
532 let ret = unsafe {
533 libfdt_bindgen::fdt_node_offset_by_compatible(
534 self.fdt.as_ptr(),
535 self.offset,
536 compatible.as_ptr(),
537 )
538 };
539
540 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
541 }
542
543 /// Replace this node and its subtree with nop tags, effectively removing it from the tree, and
544 /// then return the next compatible node of the given name.
545 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
546 // The reason is that libfdt ensures that the node from where the search for the next
547 // compatible node is started is always a valid one -- except for the special case of offset =
548 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
549 // next compatible node from it.
550 //
551 // We can't do in the opposite direction either. If we call next_compatible to find the next
552 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
553 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
554 // DT).
555 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
556 // SAFETY - Accesses (read-only) are constrained to the DT totalsize.
557 let ret = unsafe {
558 libfdt_bindgen::fdt_node_offset_by_compatible(
559 self.fdt.as_ptr(),
560 self.offset,
561 compatible.as_ptr(),
562 )
563 };
564 let next_offset = fdt_err_or_option(ret)?;
565
566 // SAFETY - fdt_nop_node alter only the bytes in the blob which contain the node and its
567 // properties and subnodes, and will not alter or move any other part of the tree.
568 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
569 fdt_err_expect_zero(ret)?;
570
571 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
572 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000573}
574
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000575/// Iterator over nodes sharing a same compatible string.
576pub struct CompatibleIterator<'a> {
577 node: FdtNode<'a>,
578 compatible: &'a CStr,
579}
580
581impl<'a> CompatibleIterator<'a> {
582 fn new(fdt: &'a Fdt, compatible: &'a CStr) -> Result<Self> {
583 let node = fdt.root()?;
584 Ok(Self { node, compatible })
585 }
586}
587
588impl<'a> Iterator for CompatibleIterator<'a> {
589 type Item = FdtNode<'a>;
590
591 fn next(&mut self) -> Option<Self::Item> {
592 let next = self.node.next_compatible(self.compatible).ok()?;
593
594 if let Some(node) = next {
595 self.node = node;
596 }
597
598 next
599 }
600}
601
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000602/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000603#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100604#[repr(transparent)]
605pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000606 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100607}
608
609impl Fdt {
610 /// Wraps a slice containing a Flattened Device Tree.
611 ///
612 /// Fails if the FDT does not pass validation.
613 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
614 // SAFETY - The FDT will be validated before it is returned.
615 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
616 fdt.check_full()?;
617 Ok(fdt)
618 }
619
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000620 /// Wraps a mutable slice containing a Flattened Device Tree.
621 ///
622 /// Fails if the FDT does not pass validation.
623 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
624 // SAFETY - The FDT will be validated before it is returned.
625 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
626 fdt.check_full()?;
627 Ok(fdt)
628 }
629
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900630 /// Creates an empty Flattened Device Tree with a mutable slice.
631 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
632 // SAFETY - fdt_create_empty_tree() only write within the specified length,
633 // and returns error if buffer was insufficient.
634 // There will be no memory write outside of the given fdt.
635 let ret = unsafe {
636 libfdt_bindgen::fdt_create_empty_tree(
637 fdt.as_mut_ptr().cast::<c_void>(),
638 fdt.len() as i32,
639 )
640 };
641 fdt_err_expect_zero(ret)?;
642
643 // SAFETY - The FDT will be validated before it is returned.
644 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
645 fdt.check_full()?;
646
647 Ok(fdt)
648 }
649
David Brazdil1baa9a92022-06-28 14:47:50 +0100650 /// Wraps a slice containing a Flattened Device Tree.
651 ///
652 /// # Safety
653 ///
654 /// The returned FDT might be invalid, only use on slices containing a valid DT.
655 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
656 mem::transmute::<&[u8], &Self>(fdt)
657 }
658
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000659 /// Wraps a mutable 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_mut_slice(fdt: &mut [u8]) -> &mut Self {
665 mem::transmute::<&mut [u8], &mut Self>(fdt)
666 }
667
Jiyong Parke9d87e82023-03-21 19:28:40 +0900668 /// Update this FDT from a slice containing another FDT
669 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
670 if self.buffer.len() < new_fdt.len() {
671 Err(FdtError::NoSpace)
672 } else {
673 let totalsize = self.totalsize();
674 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
675 // Zeroize the remaining part. We zeroize up to the size of the original DT because
676 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
677 // time.
678 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
679 Ok(())
680 }
681 }
682
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000683 /// Make the whole slice containing the DT available to libfdt.
684 pub fn unpack(&mut self) -> Result<()> {
685 // SAFETY - "Opens" the DT in-place (supported use-case) by updating its header and
686 // internal structures to make use of the whole self.fdt slice but performs no accesses
687 // outside of it and leaves the DT in a state that will be detected by other functions.
688 let ret = unsafe {
689 libfdt_bindgen::fdt_open_into(
690 self.as_ptr(),
691 self.as_mut_ptr(),
692 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
693 )
694 };
695 fdt_err_expect_zero(ret)
696 }
697
698 /// Pack the DT to take a minimum amount of memory.
699 ///
700 /// Doesn't shrink the underlying memory slice.
701 pub fn pack(&mut self) -> Result<()> {
702 // SAFETY - "Closes" the DT in-place by updating its header and relocating its structs.
703 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
704 fdt_err_expect_zero(ret)
705 }
706
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000707 /// Applies a DT overlay on the base DT.
708 ///
709 /// # Safety
710 ///
711 /// On failure, the library corrupts the DT and overlay so both must be discarded.
712 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
713 fdt_err_expect_zero(libfdt_bindgen::fdt_overlay_apply(
714 self.as_mut_ptr(),
715 overlay.as_mut_ptr(),
716 ))?;
717 Ok(self)
718 }
719
Alice Wang2422bdc2023-06-12 08:37:55 +0000720 /// Returns an iterator of memory banks specified the "/memory" node.
721 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100722 ///
723 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000724 pub fn memory(&self) -> Result<MemRegIterator> {
725 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
726 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100727
Alice Wang2422bdc2023-06-12 08:37:55 +0000728 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
729 if node.device_type()? != Some(memory_device_type) {
730 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000731 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000732 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
733 }
734
735 /// Returns the first memory range in the `/memory` node.
736 pub fn first_memory_range(&self) -> Result<Range<usize>> {
737 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100738 }
739
740 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000741 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100742 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
743 }
744
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000745 /// Retrieve the standard /chosen node as mutable.
746 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
747 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
748 }
749
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000750 /// Get the root node of the tree.
751 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000752 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000753 }
754
David Brazdil1baa9a92022-06-28 14:47:50 +0100755 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000756 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
757 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100758 }
759
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000760 /// Iterate over nodes with a given compatible string.
761 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
762 CompatibleIterator::new(self, compatible)
763 }
764
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000765 /// Get the mutable root node of the tree.
766 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
767 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
768 }
769
770 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000771 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
772 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000773 }
774
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000775 /// Return the device tree as a slice (may be smaller than the containing buffer).
776 pub fn as_slice(&self) -> &[u8] {
777 &self.buffer[..self.totalsize()]
778 }
779
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000780 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100781 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
782 // SAFETY - Accesses are constrained to the DT totalsize (validated by ctor) and the
783 // function respects the passed number of characters.
784 let ret = unsafe {
785 // *_namelen functions don't include the trailing nul terminator in 'len'.
786 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
787 };
788
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000789 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100790 }
791
792 fn check_full(&self) -> Result<()> {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000793 let len = self.buffer.len();
David Brazdil1baa9a92022-06-28 14:47:50 +0100794 // SAFETY - Only performs read accesses within the limits of the slice. If successful, this
795 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
796 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
797 // checking. The library doesn't maintain an internal state (such as pointers) between
798 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
799 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) };
800 fdt_err_expect_zero(ret)
801 }
802
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000803 /// Return a shared pointer to the device tree.
804 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000805 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100806 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000807
808 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000809 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000810 }
811
812 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000813 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000814 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000815
816 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000817 let p = self.as_ptr().cast::<_>();
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000818 // SAFETY - A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000819 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000820 }
821
822 fn totalsize(&self) -> usize {
823 u32::from_be(self.header().totalsize) as usize
824 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100825}