blob: 43eadaea908571660f31ce685a5cee8f50b3a734 [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
Jaewan Kimaa638702023-09-19 13:34:01 +0900254 /// Returns the node name.
255 pub fn name(&self) -> Result<&'a CStr> {
256 let mut len: c_int = 0;
257 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor). On success, the
258 // function returns valid null terminating string and otherwise returned values are dropped.
259 let name = unsafe { libfdt_bindgen::fdt_get_name(self.fdt.as_ptr(), self.offset, &mut len) }
260 as *const c_void;
261 let len = usize::try_from(fdt_err(len)?).unwrap();
262 let name = self.fdt.get_from_ptr(name, len + 1)?;
263 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
264 }
265
David Brazdil1baa9a92022-06-28 14:47:50 +0100266 /// Retrieve the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000267 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
268 let value = if let Some(bytes) = self.getprop(name)? {
269 Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?)
270 } else {
271 None
272 };
273 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100274 }
275
276 /// Retrieve the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000277 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
278 if let Some(cells) = self.getprop(name)? {
279 Ok(Some(CellIterator::new(cells)))
280 } else {
281 Ok(None)
282 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100283 }
284
285 /// Retrieve the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000286 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
287 let value = if let Some(bytes) = self.getprop(name)? {
288 Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
289 } else {
290 None
291 };
292 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100293 }
294
295 /// Retrieve the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000296 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
297 let value = if let Some(bytes) = self.getprop(name)? {
298 Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?))
299 } else {
300 None
301 };
302 Ok(value)
David Brazdil1baa9a92022-06-28 14:47:50 +0100303 }
304
305 /// Retrieve the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000306 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900307 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900308 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900309 } else {
310 Ok(None) // property was not found
311 }
312 }
313
314 /// Return the pointer and size of the property named `name`, in a node at offset `offset`, in
315 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
316 fn getprop_internal(
317 fdt: &'a Fdt,
318 offset: c_int,
319 name: &CStr,
320 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100321 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000322 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100323 // function respects the passed number of characters.
324 let prop = unsafe {
325 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900326 fdt.as_ptr(),
327 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100328 name.as_ptr(),
329 // *_namelen functions don't include the trailing nul terminator in 'len'.
330 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
331 &mut len as *mut i32,
332 )
333 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000334
335 let Some(len) = fdt_err_or_option(len)? else {
336 return Ok(None); // Property was not found.
337 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900338 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000339
David Brazdil1baa9a92022-06-28 14:47:50 +0100340 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000341 // We expected an error code in len but still received a valid value?!
342 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100343 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900344 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100345 }
346
347 /// Get reference to the containing device tree.
348 pub fn fdt(&self) -> &Fdt {
349 self.fdt
350 }
351
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000352 fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000353 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000354 let ret = unsafe {
355 libfdt_bindgen::fdt_node_offset_by_compatible(
356 self.fdt.as_ptr(),
357 self.offset,
358 compatible.as_ptr(),
359 )
360 };
361
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000362 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000363 }
364
David Brazdil1baa9a92022-06-28 14:47:50 +0100365 fn address_cells(&self) -> Result<AddrCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000366 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100367 unsafe { libfdt_bindgen::fdt_address_cells(self.fdt.as_ptr(), self.offset) }
368 .try_into()
369 .map_err(|_| FdtError::Internal)
370 }
371
372 fn size_cells(&self) -> Result<SizeCells> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000373 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
David Brazdil1baa9a92022-06-28 14:47:50 +0100374 unsafe { libfdt_bindgen::fdt_size_cells(self.fdt.as_ptr(), self.offset) }
375 .try_into()
376 .map_err(|_| FdtError::Internal)
377 }
378}
379
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000380/// Mutable FDT node.
381pub struct FdtNodeMut<'a> {
382 fdt: &'a mut Fdt,
383 offset: c_int,
384}
385
386impl<'a> FdtNodeMut<'a> {
387 /// Append a property name-value (possibly empty) pair to the given node.
388 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000389 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000390 let ret = unsafe {
391 libfdt_bindgen::fdt_appendprop(
392 self.fdt.as_mut_ptr(),
393 self.offset,
394 name.as_ptr(),
395 value.as_ref().as_ptr().cast::<c_void>(),
396 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
397 )
398 };
399
400 fdt_err_expect_zero(ret)
401 }
402
403 /// Append a (address, size) pair property to the given node.
404 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000405 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000406 let ret = unsafe {
407 libfdt_bindgen::fdt_appendprop_addrrange(
408 self.fdt.as_mut_ptr(),
409 self.parent()?.offset,
410 self.offset,
411 name.as_ptr(),
412 addr,
413 size,
414 )
415 };
416
417 fdt_err_expect_zero(ret)
418 }
419
Jaewan Kimba8929b2023-01-13 11:13:29 +0900420 /// Create or change a property name-value pair to the given node.
421 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000422 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900423 // (validated by underlying libfdt).
424 let ret = unsafe {
425 libfdt_bindgen::fdt_setprop(
426 self.fdt.as_mut_ptr(),
427 self.offset,
428 name.as_ptr(),
429 value.as_ptr().cast::<c_void>(),
430 value.len().try_into().map_err(|_| FdtError::BadValue)?,
431 )
432 };
433
434 fdt_err_expect_zero(ret)
435 }
436
Jiyong Park9c63cd12023-03-21 17:53:07 +0900437 /// Replace the value of the given property with the given value, and ensure that the given
438 /// value has the same length as the current value length
439 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000440 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900441 let ret = unsafe {
442 libfdt_bindgen::fdt_setprop_inplace(
443 self.fdt.as_mut_ptr(),
444 self.offset,
445 name.as_ptr(),
446 value.as_ptr().cast::<c_void>(),
447 value.len().try_into().map_err(|_| FdtError::BadValue)?,
448 )
449 };
450
451 fdt_err_expect_zero(ret)
452 }
453
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000454 /// Replace the value of the given (address, size) pair property with the given value, and
455 /// ensure that the given value has the same length as the current value length
456 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
457 let pair = [addr.to_be(), size.to_be()];
458 self.setprop_inplace(name, pair.as_bytes())
459 }
460
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000461 /// Create or change a flag-like empty property.
462 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
463 self.setprop(name, &[])
464 }
465
466 /// Delete the given property.
467 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000468 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000469 // library locates the node's property. Removing the property may shift the offsets of
470 // other nodes and properties but the borrow checker should prevent this function from
471 // being called when FdtNode instances are in use.
472 let ret = unsafe {
473 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
474 };
475
476 fdt_err_expect_zero(ret)
477 }
478
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000479 /// Overwrite the given property with FDT_NOP, effectively removing it from the DT.
480 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000481 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000482 // library locates the node's property.
483 let ret = unsafe {
484 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
485 };
486
487 fdt_err_expect_zero(ret)
488 }
489
Jiyong Park9c63cd12023-03-21 17:53:07 +0900490 /// Reduce the size of the given property to new_size
491 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
492 let (prop, len) =
493 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
494 if len == new_size {
495 return Ok(());
496 }
497 if new_size > len {
498 return Err(FdtError::NoSpace);
499 }
500
Andrew Walbran84b9a232023-07-05 14:01:40 +0000501 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900502 let ret = unsafe {
503 libfdt_bindgen::fdt_setprop(
504 self.fdt.as_mut_ptr(),
505 self.offset,
506 name.as_ptr(),
507 prop.cast::<c_void>(),
508 new_size.try_into().map_err(|_| FdtError::BadValue)?,
509 )
510 };
511
512 fdt_err_expect_zero(ret)
513 }
514
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000515 /// Get reference to the containing device tree.
516 pub fn fdt(&mut self) -> &mut Fdt {
517 self.fdt
518 }
519
520 /// Add a new subnode to the given node and return it as a FdtNodeMut on success.
521 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000522 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000523 let ret = unsafe {
524 libfdt_bindgen::fdt_add_subnode(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
525 };
526
527 Ok(Self { fdt: self.fdt, offset: fdt_err(ret)? })
528 }
529
530 fn parent(&'a self) -> Result<FdtNode<'a>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000531 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000532 let ret = unsafe { libfdt_bindgen::fdt_parent_offset(self.fdt.as_ptr(), self.offset) };
533
534 Ok(FdtNode { fdt: &*self.fdt, offset: fdt_err(ret)? })
535 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900536
537 /// Return the compatible node of the given name that is next to this node
538 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000539 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900540 let ret = unsafe {
541 libfdt_bindgen::fdt_node_offset_by_compatible(
542 self.fdt.as_ptr(),
543 self.offset,
544 compatible.as_ptr(),
545 )
546 };
547
548 Ok(fdt_err_or_option(ret)?.map(|offset| Self { fdt: self.fdt, offset }))
549 }
550
551 /// Replace this node and its subtree with nop tags, effectively removing it from the tree, and
552 /// then return the next compatible node of the given name.
553 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
554 // The reason is that libfdt ensures that the node from where the search for the next
555 // compatible node is started is always a valid one -- except for the special case of offset =
556 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
557 // next compatible node from it.
558 //
559 // We can't do in the opposite direction either. If we call next_compatible to find the next
560 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
561 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
562 // DT).
563 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000564 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900565 let ret = unsafe {
566 libfdt_bindgen::fdt_node_offset_by_compatible(
567 self.fdt.as_ptr(),
568 self.offset,
569 compatible.as_ptr(),
570 )
571 };
572 let next_offset = fdt_err_or_option(ret)?;
573
Andrew Walbran84b9a232023-07-05 14:01:40 +0000574 // SAFETY: fdt_nop_node alter only the bytes in the blob which contain the node and its
Jiyong Park9c63cd12023-03-21 17:53:07 +0900575 // properties and subnodes, and will not alter or move any other part of the tree.
576 let ret = unsafe { libfdt_bindgen::fdt_nop_node(self.fdt.as_mut_ptr(), self.offset) };
577 fdt_err_expect_zero(ret)?;
578
579 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
580 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000581}
582
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000583/// Iterator over nodes sharing a same compatible string.
584pub struct CompatibleIterator<'a> {
585 node: FdtNode<'a>,
586 compatible: &'a CStr,
587}
588
589impl<'a> CompatibleIterator<'a> {
590 fn new(fdt: &'a Fdt, compatible: &'a CStr) -> Result<Self> {
591 let node = fdt.root()?;
592 Ok(Self { node, compatible })
593 }
594}
595
596impl<'a> Iterator for CompatibleIterator<'a> {
597 type Item = FdtNode<'a>;
598
599 fn next(&mut self) -> Option<Self::Item> {
600 let next = self.node.next_compatible(self.compatible).ok()?;
601
602 if let Some(node) = next {
603 self.node = node;
604 }
605
606 next
607 }
608}
609
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000610/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000611#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100612#[repr(transparent)]
613pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000614 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100615}
616
617impl Fdt {
618 /// Wraps a slice containing a Flattened Device Tree.
619 ///
620 /// Fails if the FDT does not pass validation.
621 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000622 // SAFETY: The FDT will be validated before it is returned.
David Brazdil1baa9a92022-06-28 14:47:50 +0100623 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
624 fdt.check_full()?;
625 Ok(fdt)
626 }
627
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000628 /// Wraps a mutable slice containing a Flattened Device Tree.
629 ///
630 /// Fails if the FDT does not pass validation.
631 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000632 // SAFETY: The FDT will be validated before it is returned.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000633 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
634 fdt.check_full()?;
635 Ok(fdt)
636 }
637
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900638 /// Creates an empty Flattened Device Tree with a mutable slice.
639 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000640 // SAFETY: fdt_create_empty_tree() only write within the specified length,
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900641 // and returns error if buffer was insufficient.
642 // There will be no memory write outside of the given fdt.
643 let ret = unsafe {
644 libfdt_bindgen::fdt_create_empty_tree(
645 fdt.as_mut_ptr().cast::<c_void>(),
646 fdt.len() as i32,
647 )
648 };
649 fdt_err_expect_zero(ret)?;
650
Andrew Walbran84b9a232023-07-05 14:01:40 +0000651 // SAFETY: The FDT will be validated before it is returned.
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900652 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
653 fdt.check_full()?;
654
655 Ok(fdt)
656 }
657
David Brazdil1baa9a92022-06-28 14:47:50 +0100658 /// Wraps a slice containing a Flattened Device Tree.
659 ///
660 /// # Safety
661 ///
662 /// The returned FDT might be invalid, only use on slices containing a valid DT.
663 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000664 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
665 // responsible for ensuring that it is actually a valid FDT.
666 unsafe { mem::transmute::<&[u8], &Self>(fdt) }
David Brazdil1baa9a92022-06-28 14:47:50 +0100667 }
668
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000669 /// Wraps a mutable slice containing a Flattened Device Tree.
670 ///
671 /// # Safety
672 ///
673 /// The returned FDT might be invalid, only use on slices containing a valid DT.
674 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000675 // SAFETY: Fdt is a wrapper around a [u8], so the transmute is valid. The caller is
676 // responsible for ensuring that it is actually a valid FDT.
677 unsafe { mem::transmute::<&mut [u8], &mut Self>(fdt) }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000678 }
679
Jiyong Parke9d87e82023-03-21 19:28:40 +0900680 /// Update this FDT from a slice containing another FDT
681 pub fn copy_from_slice(&mut self, new_fdt: &[u8]) -> Result<()> {
682 if self.buffer.len() < new_fdt.len() {
683 Err(FdtError::NoSpace)
684 } else {
685 let totalsize = self.totalsize();
686 self.buffer[..new_fdt.len()].clone_from_slice(new_fdt);
687 // Zeroize the remaining part. We zeroize up to the size of the original DT because
688 // zeroizing the entire buffer (max 2MB) is not necessary and may increase the VM boot
689 // time.
690 self.buffer[new_fdt.len()..max(new_fdt.len(), totalsize)].fill(0_u8);
691 Ok(())
692 }
693 }
694
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000695 /// Make the whole slice containing the DT available to libfdt.
696 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000697 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000698 // internal structures to make use of the whole self.fdt slice but performs no accesses
699 // outside of it and leaves the DT in a state that will be detected by other functions.
700 let ret = unsafe {
701 libfdt_bindgen::fdt_open_into(
702 self.as_ptr(),
703 self.as_mut_ptr(),
704 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
705 )
706 };
707 fdt_err_expect_zero(ret)
708 }
709
710 /// Pack the DT to take a minimum amount of memory.
711 ///
712 /// Doesn't shrink the underlying memory slice.
713 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000714 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000715 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
716 fdt_err_expect_zero(ret)
717 }
718
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000719 /// Applies a DT overlay on the base DT.
720 ///
721 /// # Safety
722 ///
723 /// On failure, the library corrupts the DT and overlay so both must be discarded.
724 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000725 let ret =
726 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
727 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
728 // but that's our caller's responsibility.
729 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
730 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000731 Ok(self)
732 }
733
Alice Wang2422bdc2023-06-12 08:37:55 +0000734 /// Returns an iterator of memory banks specified the "/memory" node.
735 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100736 ///
737 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000738 pub fn memory(&self) -> Result<MemRegIterator> {
739 let memory_node_name = CStr::from_bytes_with_nul(b"/memory\0").unwrap();
740 let memory_device_type = CStr::from_bytes_with_nul(b"memory\0").unwrap();
David Brazdil1baa9a92022-06-28 14:47:50 +0100741
Alice Wang2422bdc2023-06-12 08:37:55 +0000742 let node = self.node(memory_node_name)?.ok_or(FdtError::NotFound)?;
743 if node.device_type()? != Some(memory_device_type) {
744 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000745 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000746 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
747 }
748
749 /// Returns the first memory range in the `/memory` node.
750 pub fn first_memory_range(&self) -> Result<Range<usize>> {
751 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100752 }
753
754 /// Retrieve the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000755 pub fn chosen(&self) -> Result<Option<FdtNode>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100756 self.node(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
757 }
758
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000759 /// Retrieve the standard /chosen node as mutable.
760 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
761 self.node_mut(CStr::from_bytes_with_nul(b"/chosen\0").unwrap())
762 }
763
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000764 /// Get the root node of the tree.
765 pub fn root(&self) -> Result<FdtNode> {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000766 self.node(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000767 }
768
David Brazdil1baa9a92022-06-28 14:47:50 +0100769 /// Find a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000770 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
771 Ok(self.path_offset(path)?.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100772 }
773
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000774 /// Iterate over nodes with a given compatible string.
775 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
776 CompatibleIterator::new(self, compatible)
777 }
778
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000779 /// Get the mutable root node of the tree.
780 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
781 self.node_mut(CStr::from_bytes_with_nul(b"/\0").unwrap())?.ok_or(FdtError::Internal)
782 }
783
784 /// Find a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000785 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
786 Ok(self.path_offset(path)?.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000787 }
788
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000789 /// Return the device tree as a slice (may be smaller than the containing buffer).
790 pub fn as_slice(&self) -> &[u8] {
791 &self.buffer[..self.totalsize()]
792 }
793
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000794 fn path_offset(&self, path: &CStr) -> Result<Option<c_int>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100795 let len = path.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000796 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100797 // function respects the passed number of characters.
798 let ret = unsafe {
799 // *_namelen functions don't include the trailing nul terminator in 'len'.
800 libfdt_bindgen::fdt_path_offset_namelen(self.as_ptr(), path.as_ptr(), len)
801 };
802
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000803 fdt_err_or_option(ret)
David Brazdil1baa9a92022-06-28 14:47:50 +0100804 }
805
806 fn check_full(&self) -> Result<()> {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000807 let len = self.buffer.len();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000808 // SAFETY: Only performs read accesses within the limits of the slice. If successful, this
David Brazdil1baa9a92022-06-28 14:47:50 +0100809 // call guarantees to other unsafe calls that the header contains a valid totalsize (w.r.t.
810 // 'len' i.e. the self.fdt slice) that those C functions can use to perform bounds
811 // checking. The library doesn't maintain an internal state (such as pointers) between
812 // calls as it expects the client code to keep track of the objects (DT, nodes, ...).
813 let ret = unsafe { libfdt_bindgen::fdt_check_full(self.as_ptr(), len) };
814 fdt_err_expect_zero(ret)
815 }
816
Jaewan Kimaa638702023-09-19 13:34:01 +0900817 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
818 let ptr = ptr as usize;
819 let offset = ptr.checked_sub(self.as_ptr() as usize).ok_or(FdtError::Internal)?;
820 self.buffer.get(offset..(offset + len)).ok_or(FdtError::Internal)
821 }
822
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000823 /// Return a shared pointer to the device tree.
824 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000825 self.buffer.as_ptr().cast::<_>()
David Brazdil1baa9a92022-06-28 14:47:50 +0100826 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000827
828 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000829 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000830 }
831
832 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000833 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000834 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000835
836 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000837 let p = self.as_ptr().cast::<_>();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000838 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000839 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000840 }
841
842 fn totalsize(&self) -> usize {
843 u32::from_be(self.header().totalsize) as usize
844 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100845}