blob: a305e0300596ee8de1d84f110c2d75180bb13fef [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
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000344 fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000345 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000346 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000358 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100359 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000365 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100366 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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000381 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000382 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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000397 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000398 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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000414 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900415 // (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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000432 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900433 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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000460 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000461 // 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<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000473 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000474 // 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
Andrew Walbran84b9a232023-07-05 14:01:40 +0000493 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900494 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000514 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000515 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>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000523 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000524 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>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000531 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900532 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>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000556 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900557 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
Andrew Walbran84b9a232023-07-05 14:01:40 +0000566 // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its
Jiyong Park9c63cd12023-03-21 17:53:07 +0900567 // 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000614 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100615 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000624 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000625 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> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000632 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900633 // 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
Andrew Walbran84b9a232023-07-05 14:01:40 +0000643 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900644 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 {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000656 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
657 // responsible for ensuring that it is actually a valid FDT.
658 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100659 }
660
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000661 /// Wraps a mutable slice containing a Flattened Device Tree.
662 ///
663 /// # Safety
664 ///
665 /// The returned FDT might be invalid, only use on slices containing a valid DT.
666 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000667 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
668 // responsible for ensuring that it is actually a valid FDT.
669 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000670 }
671
Jiyong Parke9d87e82023-03-21 19:28:40 +0900672 /// Update this FDT from a slice containing another FDT
673 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
674 if self.buffer.len() < new_fdt.len() {
675 Err(FdtError::NoSpace)
676 } else {
677 let totalsize = self.totalsize();
678 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
679 // Zeroize the remaining part. We zeroize up to the size of the original DT because
680 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
681 // time.
682 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
683 Ok(())
684 }
685 }
686
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000687 /// Make the whole slice containing the DT available to libfdt.
688 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000689 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000690 // internal structures to make use of the whole self.fdt slice but performs no accesses
691 // outside of it and leaves the DT in a state that will be detected by other functions.
692 let ret = unsafe {
693 libfdt_bindgen::fdt_open_into(
694 self.as_ptr(),
695 self.as_mut_ptr(),
696 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
697 )
698 };
699 fdt_err_expect_zero(ret)
700 }
701
702 /// Pack the DT to take a minimum amount of memory.
703 ///
704 /// Doesn't shrink the underlying memory slice.
705 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000706 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000707 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
708 fdt_err_expect_zero(ret)
709 }
710
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000711 /// Applies a DT overlay on the base DT.
712 ///
713 /// # Safety
714 ///
715 /// On failure, the library corrupts the DT and overlay so both must be discarded.
716 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000717 let ret =
718 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
719 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
720 // but that's our caller's responsibility.
721 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
722 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000723 Ok(self)
724 }
725
Alice Wang2422bdc2023-06-12 08:37:55 +0000726 /// Returns an iterator of memory banks specified the "/memory" node.
727 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100728 ///
729 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000730 pub fn memory(&self) -> Result<MemRegIterator> {
731 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
732 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100733
Alice Wang2422bdc2023-06-12 08:37:55 +0000734 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
735 if node.device_type()? != Some(memory_device_type) {
736 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000737 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000738 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
739 }
740
741 /// Returns the first memory range in the `/memory` node.
742 pub fn first_memory_range(&self) -> Result<Range<usize>> {
743 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100744 }
745
746 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000747 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100748 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
749 }
750
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000751 /// Retrieve the standard /chosen node as mutable.
752 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
753 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
754 }
755
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000756 /// Get the root node of the tree.
757 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000758 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000759 }
760
David Brazdil1baa9a92022-06-28 14:47:50 +0100761 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000762 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
763 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100764 }
765
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000766 /// Iterate over nodes with a given compatible string.
767 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
768 CompatibleIterator::new(self, compatible)
769 }
770
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000771 /// Get the mutable root node of the tree.
772 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
773 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
774 }
775
776 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000777 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
778 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000779 }
780
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000781 /// Return the device tree as a slice (may be smaller than the containing buffer).
782 pub fn as_slice(&self) -> &[u8] {
783 &self.buffer[..self.totalsize()]
784 }
785
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000786 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100787 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000788 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100789 // function respects the passed number of characters.
790 let ret = unsafe {
791 // *_namelen functions don't include the trailing nul terminator in 'len'.
792 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
793 };
794
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000795 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100796 }
797
798 fn check_full(&self) -> Result<()> {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000799 let len = self.buffer.len();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000800 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +0100801 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
802 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
803 // checking. The library doesn't maintain an internal state (such as pointers) between
804 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
805 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) };
806 fdt_err_expect_zero(ret)
807 }
808
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000809 /// Return a shared pointer to the device tree.
810 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000811 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100812 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000813
814 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000815 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000816 }
817
818 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000819 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000820 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000821
822 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000823 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000824 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000825 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000826 }
827
828 fn totalsize(&self) -> usize {
829 u32::from_be(self.header().totalsize) as usize
830 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100831}