blob: 9da2054b396caaa8e575119ffc5d11ad8cb15b2f [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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000208 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
David Brazdil1baa9a92022-06-28 14:47:50 +0100209 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;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000314 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100315 // 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
Alice Wang474c0ee2023-09-14 12:52:33 +0000344 /// Returns the compatible node of the given name that is next after this node.
345 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000346 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000347 let ret = unsafe {
348 libfdt_bindgen::fdt_node_offset_by_compatible(
349 self.fdt.as_ptr(),
350 self.offset,
351 compatible.as_ptr(),
352 )
353 };
354
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000355 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000356 }
357
Alice Wang474c0ee2023-09-14 12:52:33 +0000358 /// Returns the first range of `reg` in this node.
359 pub fn first_reg(&self) -> Result<Reg<u64>> {
360 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
361 }
362
David Brazdil1baa9a92022-06-28 14:47:50 +0100363 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000364 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100365 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
366 .try_into()
367 .map_err(|_| FdtError::Internal)
368 }
369
370 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000371 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100372 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
373 .try_into()
374 .map_err(|_| FdtError::Internal)
375 }
376}
377
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000378/// Mutable FDT node.
379pub struct FdtNodeMut<'a> {
380 fdt: &'a mut Fdt,
381 offset: c_int,
382}
383
384impl<'a> FdtNodeMut<'a> {
385 /// Append a property name-value (possibly empty) pair to the given node.
386 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000387 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000388 let ret = unsafe {
389 libfdt_bindgen::fdt_appendprop(
390 self.fdt.as_mut_ptr(),
391 self.offset,
392 name.as_ptr(),
393 value.as_ref().as_ptr().cast::<c_void>(),
394 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
395 )
396 };
397
398 fdt_err_expect_zero(ret)
399 }
400
401 /// Append a (address, size) pair property to the given node.
402 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000403 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000404 let ret = unsafe {
405 libfdt_bindgen::fdt_appendprop_addrrange(
406 self.fdt.as_mut_ptr(),
407 self.parent()?.offset,
408 self.offset,
409 name.as_ptr(),
410 addr,
411 size,
412 )
413 };
414
415 fdt_err_expect_zero(ret)
416 }
417
Jaewan Kimba8929b2023-01-13 11:13:29 +0900418 /// Create or change a property name-value pair to the given node.
419 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000420 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900421 // (validated by underlying libfdt).
422 let ret = unsafe {
423 libfdt_bindgen::fdt_setprop(
424 self.fdt.as_mut_ptr(),
425 self.offset,
426 name.as_ptr(),
427 value.as_ptr().cast::<c_void>(),
428 value.len().try_into().map_err(|_| FdtError::BadValue)?,
429 )
430 };
431
432 fdt_err_expect_zero(ret)
433 }
434
Jiyong Park9c63cd12023-03-21 17:53:07 +0900435 /// Replace the value of the given property with the given value, and ensure that the given
436 /// value has the same length as the current value length
437 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000438 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900439 let ret = unsafe {
440 libfdt_bindgen::fdt_setprop_inplace(
441 self.fdt.as_mut_ptr(),
442 self.offset,
443 name.as_ptr(),
444 value.as_ptr().cast::<c_void>(),
445 value.len().try_into().map_err(|_| FdtError::BadValue)?,
446 )
447 };
448
449 fdt_err_expect_zero(ret)
450 }
451
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000452 /// Replace the value of the given (address, size) pair property with the given value, and
453 /// ensure that the given value has the same length as the current value length
454 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
455 let pair = [addr.to_be(), size.to_be()];
456 self.setprop_inplace(name, pair.as_bytes())
457 }
458
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000459 /// Create or change a flag-like empty property.
460 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
461 self.setprop(name, &[])
462 }
463
464 /// Delete the given property.
465 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000466 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000467 // library locates the node's property. Removing the property may shift the offsets of
468 // other nodes and properties but the borrow checker should prevent this function from
469 // being called when FdtNode instances are in use.
470 let ret = unsafe {
471 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
472 };
473
474 fdt_err_expect_zero(ret)
475 }
476
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000477 /// Overwrite the given property with FDT_NOP, effectively removing it from the DT.
478 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000479 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000480 // library locates the node's property.
481 let ret = unsafe {
482 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
483 };
484
485 fdt_err_expect_zero(ret)
486 }
487
Jiyong Park9c63cd12023-03-21 17:53:07 +0900488 /// Reduce the size of the given property to new_size
489 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
490 let (prop, len) =
491 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
492 if len == new_size {
493 return Ok(());
494 }
495 if new_size > len {
496 return Err(FdtError::NoSpace);
497 }
498
Andrew Walbran84b9a232023-07-05 14:01:40 +0000499 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900500 let ret = unsafe {
501 libfdt_bindgen::fdt_setprop(
502 self.fdt.as_mut_ptr(),
503 self.offset,
504 name.as_ptr(),
505 prop.cast::<c_void>(),
506 new_size.try_into().map_err(|_| FdtError::BadValue)?,
507 )
508 };
509
510 fdt_err_expect_zero(ret)
511 }
512
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000513 /// Get reference to the containing device tree.
514 pub fn fdt(&mut self) -> &mut Fdt {
515 self.fdt
516 }
517
518 /// Add a new subnode to the given node and return it as a FdtNodeMut on success.
519 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000520 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000521 let ret = unsafe {
522 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
523 };
524
525 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
526 }
527
528 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000529 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000530 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
531
532 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
533 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900534
Alice Wang474c0ee2023-09-14 12:52:33 +0000535 /// Returns the compatible node of the given name that is next after this node
Jiyong Park9c63cd12023-03-21 17:53:07 +0900536 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000537 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900538 let ret = unsafe {
539 libfdt_bindgen::fdt_node_offset_by_compatible(
540 self.fdt.as_ptr(),
541 self.offset,
542 compatible.as_ptr(),
543 )
544 };
545
546 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
547 }
548
549 /// Replace this node and its subtree with nop tags, effectively removing it from the tree, and
550 /// then return the next compatible node of the given name.
551 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
552 // The reason is that libfdt ensures that the node from where the search for the next
553 // compatible node is started is always a valid one -- except for the special case of offset =
554 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
555 // next compatible node from it.
556 //
557 // We can't do in the opposite direction either. If we call next_compatible to find the next
558 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
559 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
560 // DT).
561 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000562 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900563 let ret = unsafe {
564 libfdt_bindgen::fdt_node_offset_by_compatible(
565 self.fdt.as_ptr(),
566 self.offset,
567 compatible.as_ptr(),
568 )
569 };
570 let next_offset = fdt_err_or_option(ret)?;
571
Andrew Walbran84b9a232023-07-05 14:01:40 +0000572 // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its
Jiyong Park9c63cd12023-03-21 17:53:07 +0900573 // properties and subnodes, and will not alter or move any other part of the tree.
574 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
575 fdt_err_expect_zero(ret)?;
576
577 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
578 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000579}
580
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000581/// Iterator over nodes sharing a same compatible string.
582pub struct CompatibleIterator<'a> {
583 node: FdtNode<'a>,
584 compatible: &'a CStr,
585}
586
587impl<'a> CompatibleIterator<'a> {
588 fn new(fdt: &'a Fdt, compatible: &'a CStr) -> Result<Self> {
589 let node = fdt.root()?;
590 Ok(Self { node, compatible })
591 }
592}
593
594impl<'a> Iterator for CompatibleIterator<'a> {
595 type Item = FdtNode<'a>;
596
597 fn next(&mut self) -> Option<Self::Item> {
598 let next = self.node.next_compatible(self.compatible).ok()?;
599
600 if let Some(node) = next {
601 self.node = node;
602 }
603
604 next
605 }
606}
607
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000608/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000609#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100610#[repr(transparent)]
611pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000612 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100613}
614
615impl Fdt {
616 /// Wraps a slice containing a Flattened Device Tree.
617 ///
618 /// Fails if the FDT does not pass validation.
619 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000620 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100621 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
622 fdt.check_full()?;
623 Ok(fdt)
624 }
625
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000626 /// Wraps a mutable slice containing a Flattened Device Tree.
627 ///
628 /// Fails if the FDT does not pass validation.
629 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000630 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000631 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
632 fdt.check_full()?;
633 Ok(fdt)
634 }
635
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900636 /// Creates an empty Flattened Device Tree with a mutable slice.
637 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000638 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900639 // and returns error if buffer was insufficient.
640 // There will be no memory write outside of the given fdt.
641 let ret = unsafe {
642 libfdt_bindgen::fdt_create_empty_tree(
643 fdt.as_mut_ptr().cast::<c_void>(),
644 fdt.len() as i32,
645 )
646 };
647 fdt_err_expect_zero(ret)?;
648
Andrew Walbran84b9a232023-07-05 14:01:40 +0000649 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900650 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
651 fdt.check_full()?;
652
653 Ok(fdt)
654 }
655
David Brazdil1baa9a92022-06-28 14:47:50 +0100656 /// Wraps a slice containing a Flattened Device Tree.
657 ///
658 /// # Safety
659 ///
660 /// The returned FDT might be invalid, only use on slices containing a valid DT.
661 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000662 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
663 // responsible for ensuring that it is actually a valid FDT.
664 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100665 }
666
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000667 /// Wraps a mutable slice containing a Flattened Device Tree.
668 ///
669 /// # Safety
670 ///
671 /// The returned FDT might be invalid, only use on slices containing a valid DT.
672 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000673 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
674 // responsible for ensuring that it is actually a valid FDT.
675 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000676 }
677
Jiyong Parke9d87e82023-03-21 19:28:40 +0900678 /// Update this FDT from a slice containing another FDT
679 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
680 if self.buffer.len() < new_fdt.len() {
681 Err(FdtError::NoSpace)
682 } else {
683 let totalsize = self.totalsize();
684 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
685 // Zeroize the remaining part. We zeroize up to the size of the original DT because
686 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
687 // time.
688 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
689 Ok(())
690 }
691 }
692
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000693 /// Make the whole slice containing the DT available to libfdt.
694 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000695 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000696 // internal structures to make use of the whole self.fdt slice but performs no accesses
697 // outside of it and leaves the DT in a state that will be detected by other functions.
698 let ret = unsafe {
699 libfdt_bindgen::fdt_open_into(
700 self.as_ptr(),
701 self.as_mut_ptr(),
702 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
703 )
704 };
705 fdt_err_expect_zero(ret)
706 }
707
708 /// Pack the DT to take a minimum amount of memory.
709 ///
710 /// Doesn't shrink the underlying memory slice.
711 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000712 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000713 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
714 fdt_err_expect_zero(ret)
715 }
716
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000717 /// Applies a DT overlay on the base DT.
718 ///
719 /// # Safety
720 ///
721 /// On failure, the library corrupts the DT and overlay so both must be discarded.
722 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000723 let ret =
724 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
725 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
726 // but that's our caller's responsibility.
727 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
728 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000729 Ok(self)
730 }
731
Alice Wang2422bdc2023-06-12 08:37:55 +0000732 /// Returns an iterator of memory banks specified the "/memory" node.
733 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100734 ///
735 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000736 pub fn memory(&self) -> Result<MemRegIterator> {
737 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
738 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100739
Alice Wang2422bdc2023-06-12 08:37:55 +0000740 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
741 if node.device_type()? != Some(memory_device_type) {
742 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000743 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000744 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
745 }
746
747 /// Returns the first memory range in the `/memory` node.
748 pub fn first_memory_range(&self) -> Result<Range<usize>> {
749 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100750 }
751
752 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000753 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100754 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
755 }
756
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000757 /// Retrieve the standard /chosen node as mutable.
758 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
759 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
760 }
761
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000762 /// Get the root node of the tree.
763 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000764 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000765 }
766
David Brazdil1baa9a92022-06-28 14:47:50 +0100767 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000768 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
769 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100770 }
771
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000772 /// Iterate over nodes with a given compatible string.
773 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
774 CompatibleIterator::new(self, compatible)
775 }
776
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000777 /// Get the mutable root node of the tree.
778 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
779 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
780 }
781
782 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000783 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
784 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000785 }
786
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000787 /// Return the device tree as a slice (may be smaller than the containing buffer).
788 pub fn as_slice(&self) -> &[u8] {
789 &self.buffer[..self.totalsize()]
790 }
791
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000792 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100793 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000794 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100795 // function respects the passed number of characters.
796 let ret = unsafe {
797 // *_namelen functions don't include the trailing nul terminator in 'len'.
798 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
799 };
800
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000801 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100802 }
803
804 fn check_full(&self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000805 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +0100806 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
807 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
808 // checking. The library doesn't maintain an internal state (such as pointers) between
809 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
Pierre-Clément Tosi02017da2023-09-26 17:57:04 +0100810 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), self.capacity()) };
David Brazdil1baa9a92022-06-28 14:47:50 +0100811 fdt_err_expect_zero(ret)
812 }
813
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000814 /// Return a shared pointer to the device tree.
815 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000816 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100817 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000818
819 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000820 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000821 }
822
823 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000824 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000825 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000826
827 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000828 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000829 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000830 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000831 }
832
833 fn totalsize(&self) -> usize {
834 u32::from_be(self.header().totalsize) as usize
835 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100836}