3 # Copyright (C) 2016 Google, Inc
4 # Written by Simon Glass <sjg@chromium.org>
6 # SPDX-License-Identifier: GPL-2.0+
15 # This deals with a device tree, presenting it as an assortment of Node and
16 # Prop objects, representing nodes and properties, respectively. This file
17 # contains the base classes and defines the high-level API. You can use
18 # FdtScan() as a convenience function to create and scan an Fdt.
20 # This implementation uses a libfdt Python library to access the device tree,
21 # so it is fairly efficient.
23 # A list of types we support
24 (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL) = range(4)
26 def CheckErr(errnum, msg):
28 raise ValueError('Error %d: %s: %s' %
29 (errnum, libfdt.fdt_strerror(errnum), msg))
32 """A device tree property
35 name: Property name (as per the device tree)
36 value: Property value as a string of bytes, or a list of strings of
40 def __init__(self, node, offset, name, bytes):
45 self.bytes = str(bytes)
50 self.type, self.value = self.BytesToValue(bytes)
53 """Get a (single) phandle value from a property
55 Gets the phandle valuie from a property and returns it as an integer
57 return fdt_util.fdt32_to_cpu(self.value[:4])
59 def Widen(self, newprop):
60 """Figure out which property type is more general
62 Given a current property and a new property, this function returns the
63 one that is less specific as to type. The less specific property will
64 be ble to represent the data in the more specific property. This is
76 He we want to use an int array for 'value'. The first property
77 suggests that a single int is enough, but the second one shows that
78 it is not. Calling this function with these two propertes would
79 update the current property to be like the second, since it is less
82 if newprop.type < self.type:
83 self.type = newprop.type
85 if type(newprop.value) == list and type(self.value) != list:
86 self.value = [self.value]
88 if type(self.value) == list and len(newprop.value) > len(self.value):
89 val = self.GetEmpty(self.type)
90 while len(self.value) < len(newprop.value):
91 self.value.append(val)
93 def BytesToValue(self, bytes):
94 """Converts a string of bytes into a type and value
97 A string containing bytes
102 Data, either a single element or a list of elements. Each element
104 TYPE_STRING: string value from the property
105 TYPE_INT: a byte-swapped integer stored as a 4-byte string
106 TYPE_BYTE: a byte stored as a single-byte string
110 strings = bytes.split('\0')
112 count = len(strings) - 1
113 if count > 0 and not strings[-1]:
114 for string in strings[:-1]:
119 if ch < ' ' or ch > '~':
126 return TYPE_STRING, strings[0]
128 return TYPE_STRING, strings[:-1]
131 return TYPE_BYTE, bytes[0]
133 return TYPE_BYTE, list(bytes)
135 for i in range(0, size, 4):
136 val.append(bytes[i:i + 4])
138 return TYPE_INT, val[0]
142 def GetEmpty(self, type):
143 """Get an empty / zero value of the given type
146 A single value of the given type
148 if type == TYPE_BYTE:
150 elif type == TYPE_INT:
151 return struct.pack('<I', 0);
152 elif type == TYPE_STRING:
158 """Get the offset of a property
161 The offset of the property (struct fdt_property) within the file
163 return self._node._fdt.GetStructOffset(self._offset)
166 """A device tree node
169 offset: Integer offset in the device tree
170 name: Device tree node tname
171 path: Full path to node, along with the node name itself
172 _fdt: Device tree object
173 subnodes: A list of subnodes for this node, each a Node object
174 props: A dict of properties for this node, each a Prop object.
175 Keyed by property name
177 def __init__(self, fdt, offset, name, path):
179 self._offset = offset
185 def _FindNode(self, name):
186 """Find a node given its name
189 name: Node name to look for
191 Node object if found, else None
193 for subnode in self.subnodes:
194 if subnode.name == name:
199 """Returns the offset of a node, after checking the cache
201 This should be used instead of self._offset directly, to ensure that
202 the cache does not contain invalid offsets.
204 self._fdt.CheckCache()
208 """Scan a node's properties and subnodes
210 This fills in the props and subnodes properties, recursively
211 searching into subnodes so that the entire tree is built.
213 self.props = self._fdt.GetProps(self)
215 offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
217 sep = '' if self.path[-1] == '/' else '/'
218 name = self._fdt._fdt_obj.get_name(offset)
219 path = self.path + sep + name
220 node = Node(self._fdt, offset, name, path)
221 self.subnodes.append(node)
224 offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
226 def Refresh(self, my_offset):
227 """Fix up the _offset for each node, recursively
229 Note: This does not take account of property offsets - these will not
232 if self._offset != my_offset:
233 #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
234 self._offset = my_offset
235 offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
236 for subnode in self.subnodes:
237 subnode.Refresh(offset)
238 offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
240 def DeleteProp(self, prop_name):
241 """Delete a property of a node
243 The property is deleted and the offset cache is invalidated.
246 prop_name: Name of the property to delete
248 ValueError if the property does not exist
250 CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
251 "Node '%s': delete property: '%s'" % (self.path, prop_name))
252 del self.props[prop_name]
253 self._fdt.Invalidate()
256 """Provides simple access to a flat device tree blob using libfdts.
259 fname: Filename of fdt
260 _root: Root of device tree (a Node object)
262 def __init__(self, fname):
264 self._cached_offsets = False
266 self._fname = fdt_util.EnsureCompiled(self._fname)
268 with open(self._fname) as fd:
269 self._fdt = bytearray(fd.read())
270 self._fdt_obj = libfdt.Fdt(self._fdt)
272 def Scan(self, root='/'):
273 """Scan a device tree, building up a tree of Node objects
275 This fills in the self._root property
280 TODO(sjg@chromium.org): Implement the 'root' parameter
282 self._root = self.Node(self, 0, '/', '/')
286 """Get the root Node of the device tree
293 def GetNode(self, path):
294 """Look up a node from its path
297 path: Path to look up, e.g. '/microcode/update@0'
299 Node object, or None if not found
302 for part in path.split('/')[1:]:
303 node = node._FindNode(part)
309 """Flush device tree changes back to the file
311 If the device tree has changed in memory, write it back to the file.
313 with open(self._fname, 'wb') as fd:
317 """Pack the device tree down to its minimum size
319 When nodes and properties shrink or are deleted, wasted space can
320 build up in the device tree binary.
322 CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
323 fdt_len = libfdt.fdt_totalsize(self._fdt)
324 del self._fdt[fdt_len:]
327 """Get the contents of the FDT
330 The FDT contents as a string of bytes
334 def CheckErr(errnum, msg):
336 raise ValueError('Error %d: %s: %s' %
337 (errnum, libfdt.fdt_strerror(errnum), msg))
340 def GetProps(self, node):
341 """Get all properties from a node.
344 node: Full path to node name to look in.
347 A dictionary containing all the properties, indexed by node name.
348 The entries are Prop objects.
351 ValueError: if the node does not exist.
354 poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
356 p = self._fdt_obj.get_property_by_offset(poffset)
357 prop = Prop(node, poffset, p.name, p.value)
358 props_dict[prop.name] = prop
360 poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
363 def Invalidate(self):
364 """Mark our offset cache as invalid"""
365 self._cached_offsets = False
367 def CheckCache(self):
368 """Refresh the offset cache if needed"""
369 if self._cached_offsets:
372 self._cached_offsets = True
375 """Refresh the offset cache"""
376 self._root.Refresh(0)
378 def GetStructOffset(self, offset):
379 """Get the file offset of a given struct offset
382 offset: Offset within the 'struct' region of the device tree
384 Position of @offset within the device tree binary
386 return libfdt.fdt_off_dt_struct(self._fdt) + offset
389 def Node(self, fdt, offset, name, path):
392 This is used by Fdt.Scan() to create a new node using the correct
397 offset: Offset of node
399 path: Full path to node
401 node = Node(fdt, offset, name, path)
405 """Returns a new Fdt object from the implementation we are using"""