fdt.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2016 Google, Inc
  4. # Written by Simon Glass <sjg@chromium.org>
  5. #
  6. # SPDX-License-Identifier: GPL-2.0+
  7. #
  8. import struct
  9. import sys
  10. import fdt_util
  11. import libfdt
  12. # This deals with a device tree, presenting it as an assortment of Node and
  13. # Prop objects, representing nodes and properties, respectively. This file
  14. # contains the base classes and defines the high-level API. See fdt_select.py
  15. # for how to create an Fdt object.
  16. # This implementation uses a libfdt Python library to access the device tree,
  17. # so it is fairly efficient.
  18. # A list of types we support
  19. (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL) = range(4)
  20. def CheckErr(errnum, msg):
  21. if errnum:
  22. raise ValueError('Error %d: %s: %s' %
  23. (errnum, libfdt.fdt_strerror(errnum), msg))
  24. class Prop:
  25. """A device tree property
  26. Properties:
  27. name: Property name (as per the device tree)
  28. value: Property value as a string of bytes, or a list of strings of
  29. bytes
  30. type: Value type
  31. """
  32. def __init__(self, node, offset, name, bytes):
  33. self._node = node
  34. self._offset = offset
  35. self.name = name
  36. self.value = None
  37. self.bytes = str(bytes)
  38. if not bytes:
  39. self.type = TYPE_BOOL
  40. self.value = True
  41. return
  42. self.type, self.value = self.BytesToValue(bytes)
  43. def GetPhandle(self):
  44. """Get a (single) phandle value from a property
  45. Gets the phandle valuie from a property and returns it as an integer
  46. """
  47. return fdt_util.fdt32_to_cpu(self.value[:4])
  48. def Widen(self, newprop):
  49. """Figure out which property type is more general
  50. Given a current property and a new property, this function returns the
  51. one that is less specific as to type. The less specific property will
  52. be ble to represent the data in the more specific property. This is
  53. used for things like:
  54. node1 {
  55. compatible = "fred";
  56. value = <1>;
  57. };
  58. node1 {
  59. compatible = "fred";
  60. value = <1 2>;
  61. };
  62. He we want to use an int array for 'value'. The first property
  63. suggests that a single int is enough, but the second one shows that
  64. it is not. Calling this function with these two propertes would
  65. update the current property to be like the second, since it is less
  66. specific.
  67. """
  68. if newprop.type < self.type:
  69. self.type = newprop.type
  70. if type(newprop.value) == list and type(self.value) != list:
  71. self.value = [self.value]
  72. if type(self.value) == list and len(newprop.value) > len(self.value):
  73. val = self.GetEmpty(self.type)
  74. while len(self.value) < len(newprop.value):
  75. self.value.append(val)
  76. def BytesToValue(self, bytes):
  77. """Converts a string of bytes into a type and value
  78. Args:
  79. A string containing bytes
  80. Return:
  81. A tuple:
  82. Type of data
  83. Data, either a single element or a list of elements. Each element
  84. is one of:
  85. TYPE_STRING: string value from the property
  86. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  87. TYPE_BYTE: a byte stored as a single-byte string
  88. """
  89. bytes = str(bytes)
  90. size = len(bytes)
  91. strings = bytes.split('\0')
  92. is_string = True
  93. count = len(strings) - 1
  94. if count > 0 and not strings[-1]:
  95. for string in strings[:-1]:
  96. if not string:
  97. is_string = False
  98. break
  99. for ch in string:
  100. if ch < ' ' or ch > '~':
  101. is_string = False
  102. break
  103. else:
  104. is_string = False
  105. if is_string:
  106. if count == 1:
  107. return TYPE_STRING, strings[0]
  108. else:
  109. return TYPE_STRING, strings[:-1]
  110. if size % 4:
  111. if size == 1:
  112. return TYPE_BYTE, bytes[0]
  113. else:
  114. return TYPE_BYTE, list(bytes)
  115. val = []
  116. for i in range(0, size, 4):
  117. val.append(bytes[i:i + 4])
  118. if size == 4:
  119. return TYPE_INT, val[0]
  120. else:
  121. return TYPE_INT, val
  122. def GetEmpty(self, type):
  123. """Get an empty / zero value of the given type
  124. Returns:
  125. A single value of the given type
  126. """
  127. if type == TYPE_BYTE:
  128. return chr(0)
  129. elif type == TYPE_INT:
  130. return struct.pack('<I', 0);
  131. elif type == TYPE_STRING:
  132. return ''
  133. else:
  134. return True
  135. def GetOffset(self):
  136. """Get the offset of a property
  137. Returns:
  138. The offset of the property (struct fdt_property) within the file
  139. """
  140. return self._node._fdt.GetStructOffset(self._offset)
  141. class Node:
  142. """A device tree node
  143. Properties:
  144. offset: Integer offset in the device tree
  145. name: Device tree node tname
  146. path: Full path to node, along with the node name itself
  147. _fdt: Device tree object
  148. subnodes: A list of subnodes for this node, each a Node object
  149. props: A dict of properties for this node, each a Prop object.
  150. Keyed by property name
  151. """
  152. def __init__(self, fdt, offset, name, path):
  153. self._fdt = fdt
  154. self._offset = offset
  155. self.name = name
  156. self.path = path
  157. self.subnodes = []
  158. self.props = {}
  159. def _FindNode(self, name):
  160. """Find a node given its name
  161. Args:
  162. name: Node name to look for
  163. Returns:
  164. Node object if found, else None
  165. """
  166. for subnode in self.subnodes:
  167. if subnode.name == name:
  168. return subnode
  169. return None
  170. def Offset(self):
  171. """Returns the offset of a node, after checking the cache
  172. This should be used instead of self._offset directly, to ensure that
  173. the cache does not contain invalid offsets.
  174. """
  175. self._fdt.CheckCache()
  176. return self._offset
  177. def Scan(self):
  178. """Scan a node's properties and subnodes
  179. This fills in the props and subnodes properties, recursively
  180. searching into subnodes so that the entire tree is built.
  181. """
  182. self.props = self._fdt.GetProps(self)
  183. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
  184. while offset >= 0:
  185. sep = '' if self.path[-1] == '/' else '/'
  186. name = self._fdt._fdt_obj.get_name(offset)
  187. path = self.path + sep + name
  188. node = Node(self._fdt, offset, name, path)
  189. self.subnodes.append(node)
  190. node.Scan()
  191. offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  192. def Refresh(self, my_offset):
  193. """Fix up the _offset for each node, recursively
  194. Note: This does not take account of property offsets - these will not
  195. be updated.
  196. """
  197. if self._offset != my_offset:
  198. #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
  199. self._offset = my_offset
  200. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
  201. for subnode in self.subnodes:
  202. subnode.Refresh(offset)
  203. offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  204. def DeleteProp(self, prop_name):
  205. """Delete a property of a node
  206. The property is deleted and the offset cache is invalidated.
  207. Args:
  208. prop_name: Name of the property to delete
  209. Raises:
  210. ValueError if the property does not exist
  211. """
  212. CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
  213. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  214. del self.props[prop_name]
  215. self._fdt.Invalidate()
  216. class Fdt:
  217. """Provides simple access to a flat device tree blob using libfdts.
  218. Properties:
  219. fname: Filename of fdt
  220. _root: Root of device tree (a Node object)
  221. """
  222. def __init__(self, fname):
  223. self._fname = fname
  224. self._cached_offsets = False
  225. if self._fname:
  226. self._fname = fdt_util.EnsureCompiled(self._fname)
  227. with open(self._fname) as fd:
  228. self._fdt = bytearray(fd.read())
  229. self._fdt_obj = libfdt.Fdt(self._fdt)
  230. def Scan(self, root='/'):
  231. """Scan a device tree, building up a tree of Node objects
  232. This fills in the self._root property
  233. Args:
  234. root: Ignored
  235. TODO(sjg@chromium.org): Implement the 'root' parameter
  236. """
  237. self._root = self.Node(self, 0, '/', '/')
  238. self._root.Scan()
  239. def GetRoot(self):
  240. """Get the root Node of the device tree
  241. Returns:
  242. The root Node object
  243. """
  244. return self._root
  245. def GetNode(self, path):
  246. """Look up a node from its path
  247. Args:
  248. path: Path to look up, e.g. '/microcode/update@0'
  249. Returns:
  250. Node object, or None if not found
  251. """
  252. node = self._root
  253. for part in path.split('/')[1:]:
  254. node = node._FindNode(part)
  255. if not node:
  256. return None
  257. return node
  258. def Flush(self):
  259. """Flush device tree changes back to the file
  260. If the device tree has changed in memory, write it back to the file.
  261. """
  262. with open(self._fname, 'wb') as fd:
  263. fd.write(self._fdt)
  264. def Pack(self):
  265. """Pack the device tree down to its minimum size
  266. When nodes and properties shrink or are deleted, wasted space can
  267. build up in the device tree binary.
  268. """
  269. CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
  270. fdt_len = libfdt.fdt_totalsize(self._fdt)
  271. del self._fdt[fdt_len:]
  272. def GetFdt(self):
  273. """Get the contents of the FDT
  274. Returns:
  275. The FDT contents as a string of bytes
  276. """
  277. return self._fdt
  278. def CheckErr(errnum, msg):
  279. if errnum:
  280. raise ValueError('Error %d: %s: %s' %
  281. (errnum, libfdt.fdt_strerror(errnum), msg))
  282. def GetProps(self, node):
  283. """Get all properties from a node.
  284. Args:
  285. node: Full path to node name to look in.
  286. Returns:
  287. A dictionary containing all the properties, indexed by node name.
  288. The entries are Prop objects.
  289. Raises:
  290. ValueError: if the node does not exist.
  291. """
  292. props_dict = {}
  293. poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
  294. while poffset >= 0:
  295. p = self._fdt_obj.get_property_by_offset(poffset)
  296. prop = Prop(node, poffset, p.name, p.value)
  297. props_dict[prop.name] = prop
  298. poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
  299. return props_dict
  300. def Invalidate(self):
  301. """Mark our offset cache as invalid"""
  302. self._cached_offsets = False
  303. def CheckCache(self):
  304. """Refresh the offset cache if needed"""
  305. if self._cached_offsets:
  306. return
  307. self.Refresh()
  308. self._cached_offsets = True
  309. def Refresh(self):
  310. """Refresh the offset cache"""
  311. self._root.Refresh(0)
  312. def GetStructOffset(self, offset):
  313. """Get the file offset of a given struct offset
  314. Args:
  315. offset: Offset within the 'struct' region of the device tree
  316. Returns:
  317. Position of @offset within the device tree binary
  318. """
  319. return libfdt.fdt_off_dt_struct(self._fdt) + offset
  320. @classmethod
  321. def Node(self, fdt, offset, name, path):
  322. """Create a new node
  323. This is used by Fdt.Scan() to create a new node using the correct
  324. class.
  325. Args:
  326. fdt: Fdt object
  327. offset: Offset of node
  328. name: Node name
  329. path: Full path to node
  330. """
  331. node = Node(fdt, offset, name, path)
  332. return node