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.
24 """A device tree property
27 name: Property name (as per the device tree)
28 value: Property value as a string of bytes, or a list of strings of
32 def __init__(self, node, offset, name, bytes):
33 PropBase.__init__(self, node, offset, name)
36 self.type = fdt.TYPE_BOOL
39 self.type, self.value = self.BytesToValue(bytes)
45 offset: Integer offset in the device tree
46 name: Device tree node tname
47 path: Full path to node, along with the node name itself
48 _fdt: Device tree object
49 subnodes: A list of subnodes for this node, each a Node object
50 props: A dict of properties for this node, each a Prop object.
51 Keyed by property name
53 def __init__(self, fdt, offset, name, path):
54 NodeBase.__init__(self, fdt, offset, name, path)
57 """Scan a node's properties and subnodes
59 This fills in the props and subnodes properties, recursively
60 searching into subnodes so that the entire tree is built.
62 self.props = self._fdt.GetProps(self.path)
64 offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
66 sep = '' if self.path[-1] == '/' else '/'
67 name = libfdt.Name(self._fdt.GetFdt(), offset)
68 path = self.path + sep + name
69 node = Node(self._fdt, offset, name, path)
70 self.subnodes.append(node)
73 offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
77 """Provides simple access to a flat device tree blob using libfdt.
80 _fdt: Device tree contents (bytearray)
81 _cached_offsets: True if all the nodes have a valid _offset property,
82 False if something has changed to invalidate the offsets
84 def __init__(self, fname):
85 Fdt.__init__(self, fname)
86 with open(self._fname) as fd:
90 """Get the contents of the FDT
93 The FDT contents as a string of bytes
97 def GetProps(self, node):
98 """Get all properties from a node.
101 node: Full path to node name to look in.
104 A dictionary containing all the properties, indexed by node name.
105 The entries are Prop objects.
108 ValueError: if the node does not exist.
110 offset = libfdt.fdt_path_offset(self._fdt, node)
114 poffset = libfdt.fdt_first_property_offset(self._fdt, offset)
116 dprop, plen = libfdt.fdt_get_property_by_offset(self._fdt, poffset)
117 prop = Prop(node, poffset, libfdt.String(self._fdt, dprop.nameoff),
119 props_dict[prop.name] = prop
121 poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
125 def Node(self, fdt, offset, name, path):
128 This is used by Fdt.Scan() to create a new node using the correct
133 offset: Offset of node
135 path: Full path to node
137 node = Node(fdt, offset, name, path)