3 # Copyright (C) 2016 Google, Inc
4 # Written by Simon Glass <sjg@chromium.org>
6 # SPDX-License-Identifier: GPL-2.0+
13 from fdt import Fdt, NodeBase, PropBase
17 # This deals with a device tree, presenting it as a list of Node and Prop
18 # objects, representing nodes and properties, respectively.
20 # This implementation uses a libfdt Python library to access the device tree,
21 # so it is fairly efficient.
23 def CheckErr(errnum, msg):
25 raise ValueError('Error %d: %s: %s' %
26 (errnum, libfdt.fdt_strerror(errnum), msg))
29 """A device tree property
32 name: Property name (as per the device tree)
33 value: Property value as a string of bytes, or a list of strings of
37 def __init__(self, node, offset, name, bytes):
38 PropBase.__init__(self, node, offset, name)
41 self.type = fdt.TYPE_BOOL
44 self.type, self.value = self.BytesToValue(bytes)
47 """Get the offset of a property
50 The offset of the property (struct fdt_property) within the file
52 return self._node._fdt.GetStructOffset(self._offset)
58 offset: Integer offset in the device tree
59 name: Device tree node tname
60 path: Full path to node, along with the node name itself
61 _fdt: Device tree object
62 subnodes: A list of subnodes for this node, each a Node object
63 props: A dict of properties for this node, each a Prop object.
64 Keyed by property name
66 def __init__(self, fdt, offset, name, path):
67 NodeBase.__init__(self, fdt, offset, name, path)
70 """Returns the offset of a node, after checking the cache
72 This should be used instead of self._offset directly, to ensure that
73 the cache does not contain invalid offsets.
75 self._fdt.CheckCache()
79 """Scan a node's properties and subnodes
81 This fills in the props and subnodes properties, recursively
82 searching into subnodes so that the entire tree is built.
84 self.props = self._fdt.GetProps(self, self.path)
86 offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
88 sep = '' if self.path[-1] == '/' else '/'
89 name = libfdt.Name(self._fdt.GetFdt(), offset)
90 path = self.path + sep + name
91 node = Node(self._fdt, offset, name, path)
92 self.subnodes.append(node)
95 offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
97 def Refresh(self, my_offset):
98 """Fix up the _offset for each node, recursively
100 Note: This does not take account of property offsets - these will not
103 if self._offset != my_offset:
104 #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
105 self._offset = my_offset
106 offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
107 for subnode in self.subnodes:
108 subnode.Refresh(offset)
109 offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
111 def DeleteProp(self, prop_name):
112 """Delete a property of a node
114 The property is deleted and the offset cache is invalidated.
117 prop_name: Name of the property to delete
119 ValueError if the property does not exist
121 CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
122 "Node '%s': delete property: '%s'" % (self.path, prop_name))
123 del self.props[prop_name]
124 self._fdt.Invalidate()
126 class FdtNormal(Fdt):
127 """Provides simple access to a flat device tree blob using libfdt.
130 _fdt: Device tree contents (bytearray)
131 _cached_offsets: True if all the nodes have a valid _offset property,
132 False if something has changed to invalidate the offsets
134 def __init__(self, fname):
135 Fdt.__init__(self, fname)
136 self._cached_offsets = False
138 self._fname = fdt_util.EnsureCompiled(self._fname)
140 with open(self._fname) as fd:
141 self._fdt = bytearray(fd.read())
144 """Get the contents of the FDT
147 The FDT contents as a string of bytes
152 """Flush device tree changes back to the file"""
153 with open(self._fname, 'wb') as fd:
157 """Pack the device tree down to its minimum size"""
158 CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
159 fdt_len = libfdt.fdt_totalsize(self._fdt)
160 del self._fdt[fdt_len:]
162 def GetProps(self, node, path):
163 """Get all properties from a node.
166 node: Full path to node name to look in.
169 A dictionary containing all the properties, indexed by node name.
170 The entries are Prop objects.
173 ValueError: if the node does not exist.
175 offset = libfdt.fdt_path_offset(self._fdt, path)
179 poffset = libfdt.fdt_first_property_offset(self._fdt, offset)
181 dprop, plen = libfdt.fdt_get_property_by_offset(self._fdt, poffset)
182 prop = Prop(node, poffset, libfdt.String(self._fdt, dprop.nameoff),
184 props_dict[prop.name] = prop
186 poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
189 def Invalidate(self):
190 """Mark our offset cache as invalid"""
191 self._cached_offsets = False
193 def CheckCache(self):
194 """Refresh the offset cache if needed"""
195 if self._cached_offsets:
198 self._cached_offsets = True
201 """Refresh the offset cache"""
202 self._root.Refresh(0)
204 def GetStructOffset(self, offset):
205 """Get the file offset of a given struct offset
208 offset: Offset within the 'struct' region of the device tree
210 Position of @offset within the device tree binary
212 return libfdt.fdt_off_dt_struct(self._fdt) + offset
215 def Node(self, fdt, offset, name, path):
218 This is used by Fdt.Scan() to create a new node using the correct
223 offset: Offset of node
225 path: Full path to node
227 node = Node(fdt, offset, name, path)