blob: d81c0c11e402dffe949798c3a82fdc78a59c69ed [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
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000020mod ctypes;
Andrew Walbran55ad01b2022-12-05 17:00:40 +000021mod iterators;
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +000022mod libfdt;
Pierre-Clément Tosi99a76902023-12-21 10:30:37 +000023mod result;
Andrew Walbran55ad01b2022-12-05 17:00:40 +000024
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +000025pub use ctypes::Phandle;
Jaewan Kimfe06c852023-10-05 23:40:06 +090026pub use iterators::{
Jaewan Kimc9e14112023-12-04 17:05:27 +090027 AddressRange, CellIterator, CompatibleIterator, DescendantsIterator, MemRegIterator,
28 PropertyIterator, RangesIterator, Reg, RegIterator, SubnodeIterator,
Jaewan Kimfe06c852023-10-05 23:40:06 +090029};
Pierre-Clément Tosi99a76902023-12-21 10:30:37 +000030pub use result::{FdtError, Result};
Andrew Walbran55ad01b2022-12-05 17:00:40 +000031
David Brazdil1baa9a92022-06-28 14:47:50 +010032use core::ffi::{c_int, c_void, CStr};
Alice Wang2422bdc2023-06-12 08:37:55 +000033use core::ops::Range;
Pierre-Clément Tosi1bf532b2023-11-13 11:06:20 +000034use cstr::cstr;
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +000035use libfdt::get_slice_at_ptr;
Pierre-Clément Tosi99a76902023-12-21 10:30:37 +000036use result::{fdt_err, fdt_err_expect_zero, fdt_err_or_option};
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +000037use zerocopy::AsBytes as _;
David Brazdil1baa9a92022-06-28 14:47:50 +010038
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +000039use crate::libfdt::{Libfdt, LibfdtMut};
40
David Brazdil1baa9a92022-06-28 14:47:50 +010041/// Value of a #address-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +000042#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +010043enum AddrCells {
44 Single = 1,
45 Double = 2,
Andrew Walbranb39e6922022-12-05 17:01:20 +000046 Triple = 3,
David Brazdil1baa9a92022-06-28 14:47:50 +010047}
48
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +000049impl TryFrom<usize> for AddrCells {
David Brazdil1baa9a92022-06-28 14:47:50 +010050 type Error = FdtError;
51
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +000052 fn try_from(value: usize) -> Result<Self> {
53 match value {
54 x if x == Self::Single as _ => Ok(Self::Single),
55 x if x == Self::Double as _ => Ok(Self::Double),
56 x if x == Self::Triple as _ => Ok(Self::Triple),
David Brazdil1baa9a92022-06-28 14:47:50 +010057 _ => Err(FdtError::BadNCells),
58 }
59 }
60}
61
62/// Value of a #size-cells property.
Andrew Walbranb39e6922022-12-05 17:01:20 +000063#[derive(Copy, Clone, Debug, Eq, PartialEq)]
David Brazdil1baa9a92022-06-28 14:47:50 +010064enum SizeCells {
65 None = 0,
66 Single = 1,
67 Double = 2,
68}
69
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +000070impl TryFrom<usize> for SizeCells {
David Brazdil1baa9a92022-06-28 14:47:50 +010071 type Error = FdtError;
72
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +000073 fn try_from(value: usize) -> Result<Self> {
74 match value {
75 x if x == Self::None as _ => Ok(Self::None),
76 x if x == Self::Single as _ => Ok(Self::Single),
77 x if x == Self::Double as _ => Ok(Self::Double),
David Brazdil1baa9a92022-06-28 14:47:50 +010078 _ => Err(FdtError::BadNCells),
79 }
80 }
81}
82
Jaewan Kim72d10902023-10-12 21:59:26 +090083/// DT property wrapper to abstract endianess changes
84#[repr(transparent)]
85#[derive(Debug)]
86struct FdtPropertyStruct(libfdt_bindgen::fdt_property);
87
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +000088impl AsRef<FdtPropertyStruct> for libfdt_bindgen::fdt_property {
89 fn as_ref(&self) -> &FdtPropertyStruct {
90 let ptr = self as *const _ as *const _;
91 // SAFETY: Types have the same layout (transparent) so the valid reference remains valid.
92 unsafe { &*ptr }
93 }
94}
95
Jaewan Kim72d10902023-10-12 21:59:26 +090096impl FdtPropertyStruct {
97 fn from_offset(fdt: &Fdt, offset: c_int) -> Result<&Self> {
98 let mut len = 0;
99 let prop =
100 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
101 unsafe { libfdt_bindgen::fdt_get_property_by_offset(fdt.as_ptr(), offset, &mut len) };
102 if prop.is_null() {
103 fdt_err(len)?;
104 return Err(FdtError::Internal); // shouldn't happen.
105 }
106 // SAFETY: prop is only returned when it points to valid libfdt_bindgen.
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000107 let prop = unsafe { &*prop };
108 Ok(prop.as_ref())
Jaewan Kim72d10902023-10-12 21:59:26 +0900109 }
110
111 fn name_offset(&self) -> c_int {
112 u32::from_be(self.0.nameoff).try_into().unwrap()
113 }
114
115 fn data_len(&self) -> usize {
116 u32::from_be(self.0.len).try_into().unwrap()
117 }
118
119 fn data_ptr(&self) -> *const c_void {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000120 self.0.data.as_ptr().cast()
Jaewan Kim72d10902023-10-12 21:59:26 +0900121 }
122}
123
124/// DT property.
125#[derive(Clone, Copy, Debug)]
126pub struct FdtProperty<'a> {
127 fdt: &'a Fdt,
128 offset: c_int,
129 property: &'a FdtPropertyStruct,
130}
131
132impl<'a> FdtProperty<'a> {
133 fn new(fdt: &'a Fdt, offset: c_int) -> Result<Self> {
134 let property = FdtPropertyStruct::from_offset(fdt, offset)?;
135 Ok(Self { fdt, offset, property })
136 }
137
138 /// Returns the property name
139 pub fn name(&self) -> Result<&'a CStr> {
140 self.fdt.string(self.property.name_offset())
141 }
142
143 /// Returns the property value
144 pub fn value(&self) -> Result<&'a [u8]> {
145 self.fdt.get_from_ptr(self.property.data_ptr(), self.property.data_len())
146 }
147
148 fn next_property(&self) -> Result<Option<Self>> {
149 let ret =
150 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
151 unsafe { libfdt_bindgen::fdt_next_property_offset(self.fdt.as_ptr(), self.offset) };
152
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000153 if let Some(offset) = fdt_err_or_option(ret)? {
154 Ok(Some(Self::new(self.fdt, offset)?))
155 } else {
156 Ok(None)
157 }
Jaewan Kim72d10902023-10-12 21:59:26 +0900158 }
159}
160
David Brazdil1baa9a92022-06-28 14:47:50 +0100161/// DT node.
Alice Wang9d4df702023-05-25 14:14:12 +0000162#[derive(Clone, Copy, Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100163pub struct FdtNode<'a> {
164 fdt: &'a Fdt,
165 offset: c_int,
166}
167
168impl<'a> FdtNode<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900169 /// Returns parent node.
David Brazdil1baa9a92022-06-28 14:47:50 +0100170 pub fn parent(&self) -> Result<Self> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000171 let offset = self.fdt.parent_offset(self.offset)?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100172
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000173 Ok(Self { fdt: self.fdt, offset })
David Brazdil1baa9a92022-06-28 14:47:50 +0100174 }
175
Jaewan Kim5b057772023-10-19 01:02:17 +0900176 /// Returns supernode with depth. Note that root is at depth 0.
177 pub fn supernode_at_depth(&self, depth: usize) -> Result<Self> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000178 let offset = self.fdt.supernode_atdepth_offset(self.offset, depth)?;
Jaewan Kim5b057772023-10-19 01:02:17 +0900179
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000180 Ok(Self { fdt: self.fdt, offset })
Jaewan Kim5b057772023-10-19 01:02:17 +0900181 }
182
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900183 /// Returns the standard (deprecated) device_type <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000184 pub fn device_type(&self) -> Result<Option<&CStr>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900185 self.getprop_str(cstr!("device_type"))
David Brazdil1baa9a92022-06-28 14:47:50 +0100186 }
187
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900188 /// Returns the standard reg <prop-encoded-array> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000189 pub fn reg(&self) -> Result<Option<RegIterator<'a>>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000190 if let Some(cells) = self.getprop_cells(cstr!("reg"))? {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000191 let parent = self.parent()?;
David Brazdil1baa9a92022-06-28 14:47:50 +0100192
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000193 let addr_cells = parent.address_cells()?;
194 let size_cells = parent.size_cells()?;
195
196 Ok(Some(RegIterator::new(cells, addr_cells, size_cells)))
197 } else {
198 Ok(None)
199 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100200 }
201
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900202 /// Returns the standard ranges property.
Andrew Walbranb39e6922022-12-05 17:01:20 +0000203 pub fn ranges<A, P, S>(&self) -> Result<Option<RangesIterator<'a, A, P, S>>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000204 if let Some(cells) = self.getprop_cells(cstr!("ranges"))? {
Andrew Walbranb39e6922022-12-05 17:01:20 +0000205 let parent = self.parent()?;
206 let addr_cells = self.address_cells()?;
207 let parent_addr_cells = parent.address_cells()?;
208 let size_cells = self.size_cells()?;
209 Ok(Some(RangesIterator::<A, P, S>::new(
210 cells,
211 addr_cells,
212 parent_addr_cells,
213 size_cells,
214 )))
215 } else {
216 Ok(None)
217 }
218 }
219
Jaewan Kimaa638702023-09-19 13:34:01 +0900220 /// Returns the node name.
221 pub fn name(&self) -> Result<&'a CStr> {
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000222 let name = self.fdt.get_name(self.offset)?;
Jaewan Kimaa638702023-09-19 13:34:01 +0900223 CStr::from_bytes_with_nul(name).map_err(|_| FdtError::Internal)
224 }
225
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900226 /// Returns the value of a given <string> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000227 pub fn getprop_str(&self, name: &CStr) -> Result<Option<&CStr>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000228 if let Some(bytes) = self.getprop(name)? {
229 Ok(Some(CStr::from_bytes_with_nul(bytes).map_err(|_| FdtError::BadValue)?))
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000230 } else {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000231 Ok(None)
232 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100233 }
234
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900235 /// Returns the value of a given property as an array of cells.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000236 pub fn getprop_cells(&self, name: &CStr) -> Result<Option<CellIterator<'a>>> {
237 if let Some(cells) = self.getprop(name)? {
238 Ok(Some(CellIterator::new(cells)))
239 } else {
240 Ok(None)
241 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100242 }
243
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900244 /// Returns the value of a given <u32> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000245 pub fn getprop_u32(&self, name: &CStr) -> Result<Option<u32>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000246 if let Some(bytes) = self.getprop(name)? {
247 Ok(Some(u32::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)))
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000248 } else {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000249 Ok(None)
250 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100251 }
252
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900253 /// Returns the value of a given <u64> property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000254 pub fn getprop_u64(&self, name: &CStr) -> Result<Option<u64>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000255 if let Some(bytes) = self.getprop(name)? {
256 Ok(Some(u64::from_be_bytes(bytes.try_into().map_err(|_| FdtError::BadValue)?)))
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000257 } else {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000258 Ok(None)
259 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100260 }
261
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900262 /// Returns the value of a given property.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000263 pub fn getprop(&self, name: &CStr) -> Result<Option<&'a [u8]>> {
Jiyong Park9c63cd12023-03-21 17:53:07 +0900264 if let Some((prop, len)) = Self::getprop_internal(self.fdt, self.offset, name)? {
Jaewan Kimaa638702023-09-19 13:34:01 +0900265 Ok(Some(self.fdt.get_from_ptr(prop, len)?))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900266 } else {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000267 Ok(None)
Jiyong Park9c63cd12023-03-21 17:53:07 +0900268 }
269 }
270
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900271 /// Returns the pointer and size of the property named `name`, in a node at offset `offset`, in
Jiyong Park9c63cd12023-03-21 17:53:07 +0900272 /// a device tree `fdt`. The pointer is guaranteed to be non-null, in which case error returns.
273 fn getprop_internal(
274 fdt: &'a Fdt,
275 offset: c_int,
276 name: &CStr,
277 ) -> Result<Option<(*const c_void, usize)>> {
David Brazdil1baa9a92022-06-28 14:47:50 +0100278 let mut len: i32 = 0;
Andrew Walbran84b9a232023-07-05 14:01:40 +0000279 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) and the
David Brazdil1baa9a92022-06-28 14:47:50 +0100280 // function respects the passed number of characters.
281 let prop = unsafe {
282 libfdt_bindgen::fdt_getprop_namelen(
Jiyong Park9c63cd12023-03-21 17:53:07 +0900283 fdt.as_ptr(),
284 offset,
David Brazdil1baa9a92022-06-28 14:47:50 +0100285 name.as_ptr(),
286 // *_namelen functions don't include the trailing nul terminator in 'len'.
287 name.to_bytes().len().try_into().map_err(|_| FdtError::BadPath)?,
288 &mut len as *mut i32,
289 )
290 } as *const u8;
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000291
292 let Some(len) = fdt_err_or_option(len)? else {
293 return Ok(None); // Property was not found.
294 };
Jaewan Kimaa638702023-09-19 13:34:01 +0900295 let len = usize::try_from(len).unwrap();
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000296
David Brazdil1baa9a92022-06-28 14:47:50 +0100297 if prop.is_null() {
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000298 // We expected an error code in len but still received a valid value?!
299 return Err(FdtError::Internal);
David Brazdil1baa9a92022-06-28 14:47:50 +0100300 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900301 Ok(Some((prop.cast::<c_void>(), len)))
David Brazdil1baa9a92022-06-28 14:47:50 +0100302 }
303
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900304 /// Returns reference to the containing device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100305 pub fn fdt(&self) -> &Fdt {
306 self.fdt
307 }
308
Alice Wang474c0ee2023-09-14 12:52:33 +0000309 /// Returns the compatible node of the given name that is next after this node.
310 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000311 let offset = self.fdt.node_offset_by_compatible(self.offset, compatible)?;
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000312
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000313 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000314 }
315
Alice Wang474c0ee2023-09-14 12:52:33 +0000316 /// Returns the first range of `reg` in this node.
317 pub fn first_reg(&self) -> Result<Reg<u64>> {
318 self.reg()?.ok_or(FdtError::NotFound)?.next().ok_or(FdtError::NotFound)
319 }
320
David Brazdil1baa9a92022-06-28 14:47:50 +0100321 fn address_cells(&self) -> Result<AddrCells> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000322 self.fdt.address_cells(self.offset)?.try_into()
David Brazdil1baa9a92022-06-28 14:47:50 +0100323 }
324
325 fn size_cells(&self) -> Result<SizeCells> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000326 self.fdt.size_cells(self.offset)?.try_into()
David Brazdil1baa9a92022-06-28 14:47:50 +0100327 }
Jaewan Kimbc828d72023-09-19 15:52:08 +0900328
329 /// Returns an iterator of subnodes
Jaewan Kim4a34b0d2024-01-19 13:17:47 +0900330 pub fn subnodes(&self) -> Result<SubnodeIterator<'a>> {
Jaewan Kimbc828d72023-09-19 15:52:08 +0900331 SubnodeIterator::new(self)
332 }
333
334 fn first_subnode(&self) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000335 let offset = self.fdt.first_subnode(self.offset)?;
Jaewan Kimbc828d72023-09-19 15:52:08 +0900336
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000337 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Jaewan Kimbc828d72023-09-19 15:52:08 +0900338 }
339
340 fn next_subnode(&self) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000341 let offset = self.fdt.next_subnode(self.offset)?;
Jaewan Kimbc828d72023-09-19 15:52:08 +0900342
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000343 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Jaewan Kimbc828d72023-09-19 15:52:08 +0900344 }
Jaewan Kim72d10902023-10-12 21:59:26 +0900345
Jaewan Kimc9e14112023-12-04 17:05:27 +0900346 /// Returns an iterator of descendants
Jaewan Kim1eab7232024-01-04 09:46:16 +0900347 pub fn descendants(&self) -> DescendantsIterator<'a> {
Jaewan Kimc9e14112023-12-04 17:05:27 +0900348 DescendantsIterator::new(self)
349 }
350
351 fn next_node(&self, depth: usize) -> Result<Option<(Self, usize)>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000352 if let Some((offset, depth)) = self.fdt.next_node(self.offset, depth)? {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000353 Ok(Some((Self { fdt: self.fdt, offset }, depth)))
354 } else {
355 Ok(None)
356 }
Jaewan Kimc9e14112023-12-04 17:05:27 +0900357 }
358
Jaewan Kim72d10902023-10-12 21:59:26 +0900359 /// Returns an iterator of properties
360 pub fn properties(&'a self) -> Result<PropertyIterator<'a>> {
361 PropertyIterator::new(self)
362 }
363
364 fn first_property(&self) -> Result<Option<FdtProperty<'a>>> {
365 let ret =
366 // SAFETY: Accesses (read-only) are constrained to the DT totalsize.
367 unsafe { libfdt_bindgen::fdt_first_property_offset(self.fdt.as_ptr(), self.offset) };
368
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000369 if let Some(offset) = fdt_err_or_option(ret)? {
370 Ok(Some(FdtProperty::new(self.fdt, offset)?))
371 } else {
372 Ok(None)
373 }
Jaewan Kim72d10902023-10-12 21:59:26 +0900374 }
Jaewan Kimf34f4b82023-11-03 19:38:38 +0900375
376 /// Returns the phandle
377 pub fn get_phandle(&self) -> Result<Option<Phandle>> {
378 // This rewrites the fdt_get_phandle() because it doesn't return error code.
379 if let Some(prop) = self.getprop_u32(cstr!("phandle"))? {
380 Ok(Some(prop.try_into()?))
381 } else if let Some(prop) = self.getprop_u32(cstr!("linux,phandle"))? {
382 Ok(Some(prop.try_into()?))
383 } else {
384 Ok(None)
385 }
386 }
Jaewan Kim52026012023-12-13 13:49:28 +0900387
388 /// Returns the subnode of the given name. The name doesn't need to be nul-terminated.
389 pub fn subnode(&self, name: &CStr) -> Result<Option<Self>> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000390 let name = name.to_bytes();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000391 let offset = self.fdt.subnode_offset_namelen(self.offset, name)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000392
Jaewan Kim52026012023-12-13 13:49:28 +0900393 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
394 }
395
396 /// Returns the subnode of the given name bytes
397 pub fn subnode_with_name_bytes(&self, name: &[u8]) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000398 let offset = self.fdt.subnode_offset_namelen(self.offset, name)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000399
Jaewan Kim52026012023-12-13 13:49:28 +0900400 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
401 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100402}
403
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000404impl<'a> PartialEq for FdtNode<'a> {
405 fn eq(&self, other: &Self) -> bool {
406 self.fdt.as_ptr() == other.fdt.as_ptr() && self.offset == other.offset
407 }
408}
409
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000410/// Mutable FDT node.
Pierre-Clément Tosi504b4302023-10-30 12:22:50 +0000411#[derive(Debug)]
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000412pub struct FdtNodeMut<'a> {
413 fdt: &'a mut Fdt,
414 offset: c_int,
415}
416
417impl<'a> FdtNodeMut<'a> {
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900418 /// Appends a property name-value (possibly empty) pair to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000419 pub fn appendprop<T: AsRef<[u8]>>(&mut self, name: &CStr, value: &T) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000420 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000421 let ret = unsafe {
422 libfdt_bindgen::fdt_appendprop(
423 self.fdt.as_mut_ptr(),
424 self.offset,
425 name.as_ptr(),
426 value.as_ref().as_ptr().cast::<c_void>(),
427 value.as_ref().len().try_into().map_err(|_| FdtError::BadValue)?,
428 )
429 };
430
431 fdt_err_expect_zero(ret)
432 }
433
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900434 /// Appends a (address, size) pair property to the given node.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000435 pub fn appendprop_addrrange(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000436 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor).
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000437 let ret = unsafe {
438 libfdt_bindgen::fdt_appendprop_addrrange(
439 self.fdt.as_mut_ptr(),
440 self.parent()?.offset,
441 self.offset,
442 name.as_ptr(),
443 addr,
444 size,
445 )
446 };
447
448 fdt_err_expect_zero(ret)
449 }
450
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900451 /// Sets a property name-value pair to the given node.
452 ///
453 /// This may create a new prop or replace existing value.
Jaewan Kimba8929b2023-01-13 11:13:29 +0900454 pub fn setprop(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000455 // SAFETY: New value size is constrained to the DT totalsize
Jaewan Kimba8929b2023-01-13 11:13:29 +0900456 // (validated by underlying libfdt).
457 let ret = unsafe {
458 libfdt_bindgen::fdt_setprop(
459 self.fdt.as_mut_ptr(),
460 self.offset,
461 name.as_ptr(),
462 value.as_ptr().cast::<c_void>(),
463 value.len().try_into().map_err(|_| FdtError::BadValue)?,
464 )
465 };
466
467 fdt_err_expect_zero(ret)
468 }
469
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900470 /// Sets the value of the given property with the given value, and ensure that the given
471 /// value has the same length as the current value length.
472 ///
473 /// This can only be used to replace existing value.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900474 pub fn setprop_inplace(&mut self, name: &CStr, value: &[u8]) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000475 // SAFETY: fdt size is not altered
Jiyong Park9c63cd12023-03-21 17:53:07 +0900476 let ret = unsafe {
477 libfdt_bindgen::fdt_setprop_inplace(
478 self.fdt.as_mut_ptr(),
479 self.offset,
480 name.as_ptr(),
481 value.as_ptr().cast::<c_void>(),
482 value.len().try_into().map_err(|_| FdtError::BadValue)?,
483 )
484 };
485
486 fdt_err_expect_zero(ret)
487 }
488
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900489 /// Sets the value of the given (address, size) pair property with the given value, and
490 /// ensure that the given value has the same length as the current value length.
491 ///
492 /// This can only be used to replace existing value.
Pierre-Clément Tosic27c4272023-05-19 15:46:26 +0000493 pub fn setprop_addrrange_inplace(&mut self, name: &CStr, addr: u64, size: u64) -> Result<()> {
494 let pair = [addr.to_be(), size.to_be()];
495 self.setprop_inplace(name, pair.as_bytes())
496 }
497
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900498 /// Sets a flag-like empty property.
499 ///
500 /// This may create a new prop or replace existing value.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000501 pub fn setprop_empty(&mut self, name: &CStr) -> Result<()> {
502 self.setprop(name, &[])
503 }
504
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900505 /// Deletes the given property.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000506 pub fn delprop(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000507 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000508 // library locates the node's property. Removing the property may shift the offsets of
509 // other nodes and properties but the borrow checker should prevent this function from
510 // being called when FdtNode instances are in use.
511 let ret = unsafe {
512 libfdt_bindgen::fdt_delprop(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
513 };
514
515 fdt_err_expect_zero(ret)
516 }
517
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900518 /// Deletes the given property effectively from DT, by setting it with FDT_NOP.
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000519 pub fn nop_property(&mut self, name: &CStr) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000520 // SAFETY: Accesses are constrained to the DT totalsize (validated by ctor) when the
Pierre-Clément Tosibe3a97b2023-05-19 14:56:23 +0000521 // library locates the node's property.
522 let ret = unsafe {
523 libfdt_bindgen::fdt_nop_property(self.fdt.as_mut_ptr(), self.offset, name.as_ptr())
524 };
525
526 fdt_err_expect_zero(ret)
527 }
528
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900529 /// Trims the size of the given property to new_size.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900530 pub fn trimprop(&mut self, name: &CStr, new_size: usize) -> Result<()> {
531 let (prop, len) =
532 FdtNode::getprop_internal(self.fdt, self.offset, name)?.ok_or(FdtError::NotFound)?;
533 if len == new_size {
534 return Ok(());
535 }
536 if new_size > len {
537 return Err(FdtError::NoSpace);
538 }
539
Andrew Walbran84b9a232023-07-05 14:01:40 +0000540 // SAFETY: new_size is smaller than the old size
Jiyong Park9c63cd12023-03-21 17:53:07 +0900541 let ret = unsafe {
542 libfdt_bindgen::fdt_setprop(
543 self.fdt.as_mut_ptr(),
544 self.offset,
545 name.as_ptr(),
546 prop.cast::<c_void>(),
547 new_size.try_into().map_err(|_| FdtError::BadValue)?,
548 )
549 };
550
551 fdt_err_expect_zero(ret)
552 }
553
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900554 /// Returns reference to the containing device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000555 pub fn fdt(&mut self) -> &mut Fdt {
556 self.fdt
557 }
558
Jaewan Kimf72f4f22023-11-03 19:21:34 +0900559 /// Returns immutable FdtNode of this node.
560 pub fn as_node(&self) -> FdtNode {
561 FdtNode { fdt: self.fdt, offset: self.offset }
562 }
563
Jaewan Kime6363422024-01-19 14:00:00 +0900564 /// Adds new subnodes to the given node.
565 pub fn add_subnodes(&mut self, names: &[&CStr]) -> Result<()> {
566 for name in names {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000567 self.fdt.add_subnode_namelen(self.offset, name.to_bytes())?;
Jaewan Kime6363422024-01-19 14:00:00 +0900568 }
569 Ok(())
570 }
571
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900572 /// Adds a new subnode to the given node and return it as a FdtNodeMut on success.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000573 pub fn add_subnode(&'a mut self, name: &CStr) -> Result<Self> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000574 let name = name.to_bytes();
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000575 let offset = self.fdt.add_subnode_namelen(self.offset, name)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000576
Jaewan Kim5ab13582023-10-20 20:56:27 +0900577 Ok(Self { fdt: self.fdt, offset })
578 }
579
580 /// Adds a new subnode to the given node with name and namelen, and returns it as a FdtNodeMut
581 /// on success.
582 pub fn add_subnode_with_namelen(&'a mut self, name: &CStr, namelen: usize) -> Result<Self> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000583 let name = &name.to_bytes()[..namelen];
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000584 let offset = self.fdt.add_subnode_namelen(self.offset, name)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000585
Jaewan Kim5ab13582023-10-20 20:56:27 +0900586 Ok(Self { fdt: self.fdt, offset })
587 }
588
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900589 /// Returns the first subnode of this
590 pub fn first_subnode(&'a mut self) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000591 let offset = self.fdt.first_subnode(self.offset)?;
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900592
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000593 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900594 }
595
596 /// Returns the next subnode that shares the same parent with this
597 pub fn next_subnode(self) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000598 let offset = self.fdt.next_subnode(self.offset)?;
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900599
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000600 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900601 }
602
603 /// Deletes the current node and returns the next subnode
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000604 pub fn delete_and_next_subnode(self) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000605 let next_offset = self.fdt.next_subnode(self.offset)?;
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900606
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000607 self.delete_and_next(next_offset)
Jaewan Kim5f1a6032023-12-18 15:17:58 +0900608 }
609
Jaewan Kim28a13ea2024-01-04 09:22:40 +0900610 /// Returns the next node
611 pub fn next_node(self, depth: usize) -> Result<Option<(Self, usize)>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000612 let next = self.fdt.next_node(self.offset, depth)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000613
614 Ok(next.map(|(offset, depth)| (Self { fdt: self.fdt, offset }, depth)))
Jaewan Kim28a13ea2024-01-04 09:22:40 +0900615 }
616
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000617 /// Deletes this and returns the next node
Pierre-Clément Tosi81c5bc72024-01-29 13:39:07 +0000618 pub fn delete_and_next_node(self, depth: usize) -> Result<Option<(Self, usize)>> {
619 let next_node = self.fdt.next_node_skip_subnodes(self.offset, depth)?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000620 if let Some((offset, depth)) = next_node {
621 let next_node = self.delete_and_next(Some(offset))?.unwrap();
622 Ok(Some((next_node, depth)))
623 } else {
624 Ok(None)
625 }
Jaewan Kim28a13ea2024-01-04 09:22:40 +0900626 }
627
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000628 fn parent(&'a self) -> Result<FdtNode<'a>> {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000629 self.as_node().parent()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000630 }
Jiyong Park9c63cd12023-03-21 17:53:07 +0900631
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900632 /// Returns the compatible node of the given name that is next after this node.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900633 pub fn next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000634 let offset = self.fdt.node_offset_by_compatible(self.offset, compatible)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900635
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000636 Ok(offset.map(|offset| Self { fdt: self.fdt, offset }))
Jiyong Park9c63cd12023-03-21 17:53:07 +0900637 }
638
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900639 /// Deletes the node effectively by overwriting this node and its subtree with nop tags.
640 /// Returns the next compatible node of the given name.
Jiyong Park9c63cd12023-03-21 17:53:07 +0900641 // Side note: without this, filterint out excessive compatible nodes from the DT is impossible.
642 // The reason is that libfdt ensures that the node from where the search for the next
643 // compatible node is started is always a valid one -- except for the special case of offset =
644 // -1 which is to find the first compatible node. So, we can't delete a node and then find the
645 // next compatible node from it.
646 //
647 // We can't do in the opposite direction either. If we call next_compatible to find the next
648 // node, and delete the current node, the Rust borrow checker kicks in. The next node has a
649 // mutable reference to DT, so we can't use current node (which also has a mutable reference to
650 // DT).
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000651 pub fn delete_and_next_compatible(self, compatible: &CStr) -> Result<Option<Self>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000652 let next_offset = self.fdt.node_offset_by_compatible(self.offset, compatible)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900653
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000654 self.delete_and_next(next_offset)
655 }
656
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000657 fn delete_and_next(self, next_offset: Option<c_int>) -> Result<Option<Self>> {
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900658 if Some(self.offset) == next_offset {
659 return Err(FdtError::Internal);
660 }
661
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000662 self.fdt.nop_node(self.offset)?;
Jiyong Park9c63cd12023-03-21 17:53:07 +0900663
664 Ok(next_offset.map(|offset| Self { fdt: self.fdt, offset }))
665 }
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900666
667 /// Deletes this node effectively from DT, by setting it with FDT_NOP
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000668 pub fn nop(self) -> Result<()> {
669 self.fdt.nop_node(self.offset)
Jaewan Kim4ae0e712023-10-19 14:16:17 +0900670 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000671}
672
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000673/// Wrapper around low-level libfdt functions.
Alice Wang9d4df702023-05-25 14:14:12 +0000674#[derive(Debug)]
David Brazdil1baa9a92022-06-28 14:47:50 +0100675#[repr(transparent)]
676pub struct Fdt {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000677 buffer: [u8],
David Brazdil1baa9a92022-06-28 14:47:50 +0100678}
679
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000680// SAFETY: Fdt calls check_full() before safely returning a &Self, making it impossible for trait
681// methods to be called on invalid device trees.
682unsafe impl Libfdt for Fdt {
683 fn as_fdt_slice(&self) -> &[u8] {
684 &self.buffer[..self.totalsize()]
685 }
686}
687
688// SAFETY: Fdt calls check_full() before safely returning a &Self, making it impossible for trait
689// methods to be called on invalid device trees.
690unsafe impl LibfdtMut for Fdt {
691 fn as_fdt_slice_mut(&mut self) -> &mut [u8] {
692 &mut self.buffer
693 }
694}
695
David Brazdil1baa9a92022-06-28 14:47:50 +0100696impl Fdt {
697 /// Wraps a slice containing a Flattened Device Tree.
698 ///
699 /// Fails if the FDT does not pass validation.
700 pub fn from_slice(fdt: &[u8]) -> Result<&Self> {
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000701 libfdt::check_full(fdt)?;
702 // SAFETY: The FDT was validated.
David Brazdil1baa9a92022-06-28 14:47:50 +0100703 let fdt = unsafe { Self::unchecked_from_slice(fdt) };
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000704
David Brazdil1baa9a92022-06-28 14:47:50 +0100705 Ok(fdt)
706 }
707
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000708 /// Wraps a mutable slice containing a Flattened Device Tree.
709 ///
710 /// Fails if the FDT does not pass validation.
711 pub fn from_mut_slice(fdt: &mut [u8]) -> Result<&mut Self> {
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000712 libfdt::check_full(fdt)?;
713 // SAFETY: The FDT was validated.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000714 let fdt = unsafe { Self::unchecked_from_mut_slice(fdt) };
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000715
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000716 Ok(fdt)
717 }
718
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900719 /// Creates an empty Flattened Device Tree with a mutable slice.
720 pub fn create_empty_tree(fdt: &mut [u8]) -> Result<&mut Self> {
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000721 libfdt::create_empty_tree(fdt)?;
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900722
Pierre-Clément Tosifbb5ee22023-12-21 13:49:59 +0000723 Self::from_mut_slice(fdt)
Jaewan Kim4cf20aa2023-04-03 10:25:38 +0900724 }
725
David Brazdil1baa9a92022-06-28 14:47:50 +0100726 /// Wraps a slice containing a Flattened Device Tree.
727 ///
728 /// # Safety
729 ///
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000730 /// It is undefined to call this function on a slice that does not contain a valid device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100731 pub unsafe fn unchecked_from_slice(fdt: &[u8]) -> &Self {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000732 let self_ptr = fdt as *const _ as *const _;
733 // SAFETY: The pointer is non-null, dereferenceable, and points to allocated memory.
734 unsafe { &*self_ptr }
David Brazdil1baa9a92022-06-28 14:47:50 +0100735 }
736
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000737 /// Wraps a mutable slice containing a Flattened Device Tree.
738 ///
739 /// # Safety
740 ///
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000741 /// It is undefined to call this function on a slice that does not contain a valid device tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000742 pub unsafe fn unchecked_from_mut_slice(fdt: &mut [u8]) -> &mut Self {
Pierre-Clément Tosidf3037f2024-01-22 15:41:43 +0000743 let self_mut_ptr = fdt as *mut _ as *mut _;
744 // SAFETY: The pointer is non-null, dereferenceable, and points to allocated memory.
745 unsafe { &mut *self_mut_ptr }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000746 }
747
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000748 /// Updates this FDT from another FDT.
749 pub fn clone_from(&mut self, other: &Self) -> Result<()> {
750 let new_len = other.buffer.len();
751 if self.buffer.len() < new_len {
752 return Err(FdtError::NoSpace);
Jiyong Parke9d87e82023-03-21 19:28:40 +0900753 }
Pierre-Clément Tosice0b36d2024-01-26 10:50:05 +0000754
755 let zeroed_len = self.totalsize().checked_sub(new_len);
756 let (cloned, zeroed) = self.buffer.split_at_mut(new_len);
757
758 cloned.clone_from_slice(&other.buffer);
759 if let Some(len) = zeroed_len {
760 zeroed[..len].fill(0);
761 }
762
763 Ok(())
Jiyong Parke9d87e82023-03-21 19:28:40 +0900764 }
765
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900766 /// Unpacks the DT to cover the whole slice it is contained in.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000767 pub fn unpack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000768 // SAFETY: "Opens" the DT in-place (supported use-case) by updating its header and
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000769 // internal structures to make use of the whole self.fdt slice but performs no accesses
770 // outside of it and leaves the DT in a state that will be detected by other functions.
771 let ret = unsafe {
772 libfdt_bindgen::fdt_open_into(
773 self.as_ptr(),
774 self.as_mut_ptr(),
775 self.capacity().try_into().map_err(|_| FdtError::Internal)?,
776 )
777 };
778 fdt_err_expect_zero(ret)
779 }
780
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900781 /// Packs the DT to take a minimum amount of memory.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000782 ///
783 /// Doesn't shrink the underlying memory slice.
784 pub fn pack(&mut self) -> Result<()> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000785 // SAFETY: "Closes" the DT in-place by updating its header and relocating its structs.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000786 let ret = unsafe { libfdt_bindgen::fdt_pack(self.as_mut_ptr()) };
787 fdt_err_expect_zero(ret)
788 }
789
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000790 /// Applies a DT overlay on the base DT.
791 ///
792 /// # Safety
793 ///
794 /// On failure, the library corrupts the DT and overlay so both must be discarded.
795 pub unsafe fn apply_overlay<'a>(&'a mut self, overlay: &'a mut Fdt) -> Result<&'a mut Self> {
Andrew Walbran84b9a232023-07-05 14:01:40 +0000796 let ret =
797 // SAFETY: Both pointers are valid because they come from references, and fdt_overlay_apply
798 // doesn't keep them after it returns. It may corrupt their contents if there is an error,
799 // but that's our caller's responsibility.
800 unsafe { libfdt_bindgen::fdt_overlay_apply(self.as_mut_ptr(), overlay.as_mut_ptr()) };
801 fdt_err_expect_zero(ret)?;
Pierre-Clément Tosi90e19352022-11-21 17:11:48 +0000802 Ok(self)
803 }
804
Alice Wang2422bdc2023-06-12 08:37:55 +0000805 /// Returns an iterator of memory banks specified the "/memory" node.
806 /// Throws an error when the "/memory" is not found in the device tree.
David Brazdil1baa9a92022-06-28 14:47:50 +0100807 ///
808 /// NOTE: This does not support individual "/memory@XXXX" banks.
Alice Wang2422bdc2023-06-12 08:37:55 +0000809 pub fn memory(&self) -> Result<MemRegIterator> {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000810 let node = self.node(cstr!("/memory"))?.ok_or(FdtError::NotFound)?;
811 if node.device_type()? != Some(cstr!("memory")) {
Alice Wang2422bdc2023-06-12 08:37:55 +0000812 return Err(FdtError::BadValue);
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000813 }
Alice Wang2422bdc2023-06-12 08:37:55 +0000814 node.reg()?.ok_or(FdtError::BadValue).map(MemRegIterator::new)
815 }
816
817 /// Returns the first memory range in the `/memory` node.
818 pub fn first_memory_range(&self) -> Result<Range<usize>> {
819 self.memory()?.next().ok_or(FdtError::NotFound)
David Brazdil1baa9a92022-06-28 14:47:50 +0100820 }
821
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900822 /// Returns the standard /chosen node.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000823 pub fn chosen(&self) -> Result<Option<FdtNode>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900824 self.node(cstr!("/chosen"))
David Brazdil1baa9a92022-06-28 14:47:50 +0100825 }
826
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900827 /// Returns the standard /chosen node as mutable.
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000828 pub fn chosen_mut(&mut self) -> Result<Option<FdtNodeMut>> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900829 self.node_mut(cstr!("/chosen"))
Pierre-Clément Tosi4ba79662023-02-13 11:22:41 +0000830 }
831
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900832 /// Returns the root node of the tree.
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000833 pub fn root(&self) -> Result<FdtNode> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900834 self.node(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000835 }
836
Jaewan Kimf163d762023-11-01 13:12:50 +0900837 /// Returns the standard /__symbols__ node.
838 pub fn symbols(&self) -> Result<Option<FdtNode>> {
839 self.node(cstr!("/__symbols__"))
840 }
841
842 /// Returns the standard /__symbols__ node as mutable
843 pub fn symbols_mut(&mut self) -> Result<Option<FdtNodeMut>> {
844 self.node_mut(cstr!("/__symbols__"))
845 }
846
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900847 /// Returns a tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000848 pub fn node(&self, path: &CStr) -> Result<Option<FdtNode>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000849 let offset = self.path_offset_namelen(path.to_bytes())?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000850
851 Ok(offset.map(|offset| FdtNode { fdt: self, offset }))
David Brazdil1baa9a92022-06-28 14:47:50 +0100852 }
853
Pierre-Clément Tosi41c158e2022-11-21 19:16:25 +0000854 /// Iterate over nodes with a given compatible string.
855 pub fn compatible_nodes<'a>(&'a self, compatible: &'a CStr) -> Result<CompatibleIterator<'a>> {
856 CompatibleIterator::new(self, compatible)
857 }
858
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900859 /// Returns max phandle in the tree.
860 pub fn max_phandle(&self) -> Result<Phandle> {
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000861 self.find_max_phandle()
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900862 }
863
864 /// Returns a node with the phandle
865 pub fn node_with_phandle(&self, phandle: Phandle) -> Result<Option<FdtNode>> {
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000866 let offset = self.node_offset_by_phandle(phandle)?;
867
Jaewan Kimc63246d2023-11-09 15:41:01 +0900868 Ok(offset.map(|offset| FdtNode { fdt: self, offset }))
869 }
870
871 /// Returns a mutable node with the phandle
872 pub fn node_mut_with_phandle(&mut self, phandle: Phandle) -> Result<Option<FdtNodeMut>> {
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000873 let offset = self.node_offset_by_phandle(phandle)?;
Jaewan Kimc63246d2023-11-09 15:41:01 +0900874
Pierre-Clément Tosiecd5bbc2023-12-21 15:12:45 +0000875 Ok(offset.map(|offset| FdtNodeMut { fdt: self, offset }))
Jaewan Kim17ba7a32023-10-19 13:25:15 +0900876 }
877
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900878 /// Returns the mutable root node of the tree.
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000879 pub fn root_mut(&mut self) -> Result<FdtNodeMut> {
Jaewan Kimb635bb02023-11-01 13:00:34 +0900880 self.node_mut(cstr!("/"))?.ok_or(FdtError::Internal)
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000881 }
882
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900883 /// Returns a mutable tree node by its full path.
Pierre-Clément Tosib244d932022-11-24 16:45:53 +0000884 pub fn node_mut(&mut self, path: &CStr) -> Result<Option<FdtNodeMut>> {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000885 let offset = self.path_offset_namelen(path.to_bytes())?;
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000886
887 Ok(offset.map(|offset| FdtNodeMut { fdt: self, offset }))
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000888 }
889
Pierre-Clément Tosi81c5bc72024-01-29 13:39:07 +0000890 fn next_node_skip_subnodes(&self, node: c_int, depth: usize) -> Result<Option<(c_int, usize)>> {
891 let mut iter = self.next_node(node, depth)?;
892 while let Some((offset, next_depth)) = iter {
893 if next_depth <= depth {
894 return Ok(Some((offset, next_depth)));
895 }
896 iter = self.next_node(offset, next_depth)?;
897 }
898
899 Ok(None)
900 }
901
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900902 /// Returns the device tree as a slice (may be smaller than the containing buffer).
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000903 pub fn as_slice(&self) -> &[u8] {
Pierre-Clément Tosid83741d2024-02-02 10:44:55 +0000904 self.as_fdt_slice()
David Brazdil1baa9a92022-06-28 14:47:50 +0100905 }
906
Jaewan Kimaa638702023-09-19 13:34:01 +0900907 fn get_from_ptr(&self, ptr: *const c_void, len: usize) -> Result<&[u8]> {
Pierre-Clément Tosi60282ae2023-12-21 16:00:02 +0000908 get_slice_at_ptr(self.as_fdt_slice(), ptr.cast(), len).ok_or(FdtError::Internal)
Jaewan Kim72d10902023-10-12 21:59:26 +0900909 }
910
Jaewan Kimb3dcfc22023-09-20 10:20:52 +0900911 /// Returns a shared pointer to the device tree.
Pierre-Clément Tosi8036b4f2023-02-17 10:31:31 +0000912 pub fn as_ptr(&self) -> *const c_void {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000913 self.buffer.as_ptr().cast()
David Brazdil1baa9a92022-06-28 14:47:50 +0100914 }
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000915
916 fn as_mut_ptr(&mut self) -> *mut c_void {
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000917 self.buffer.as_mut_ptr().cast::<_>()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000918 }
919
920 fn capacity(&self) -> usize {
Pierre-Clément Tosief2030e2022-11-28 11:21:20 +0000921 self.buffer.len()
Pierre-Clément Tosi1b0d8902022-11-21 18:16:59 +0000922 }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000923
924 fn header(&self) -> &libfdt_bindgen::fdt_header {
Pierre-Clément Tosicb92b512024-01-22 15:55:25 +0000925 let p = self.as_ptr().cast();
Andrew Walbran84b9a232023-07-05 14:01:40 +0000926 // SAFETY: A valid FDT (verified by constructor) must contain a valid fdt_header.
Pierre-Clément Tosi0dcc75e2023-05-02 13:43:55 +0000927 unsafe { &*p }
Pierre-Clément Tosidb74cb12022-12-08 13:56:25 +0000928 }
929
930 fn totalsize(&self) -> usize {
931 u32::from_be(self.header().totalsize) as usize
932 }
David Brazdil1baa9a92022-06-28 14:47:50 +0100933}