fdt.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. #!/usr/bin/python
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Copyright (C) 2016 Google, Inc
  5. # Written by Simon Glass <sjg@chromium.org>
  6. #
  7. import struct
  8. import sys
  9. import fdt_util
  10. import libfdt
  11. from libfdt import QUIET_NOTFOUND
  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. You can use
  15. # FdtScan() as a convenience function to create and scan an Fdt.
  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, TYPE_INT64) = range(5)
  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. self.dirty = False
  39. if not bytes:
  40. self.type = TYPE_BOOL
  41. self.value = True
  42. return
  43. self.type, self.value = self.BytesToValue(bytes)
  44. def RefreshOffset(self, poffset):
  45. self._offset = poffset
  46. def Widen(self, newprop):
  47. """Figure out which property type is more general
  48. Given a current property and a new property, this function returns the
  49. one that is less specific as to type. The less specific property will
  50. be ble to represent the data in the more specific property. This is
  51. used for things like:
  52. node1 {
  53. compatible = "fred";
  54. value = <1>;
  55. };
  56. node1 {
  57. compatible = "fred";
  58. value = <1 2>;
  59. };
  60. He we want to use an int array for 'value'. The first property
  61. suggests that a single int is enough, but the second one shows that
  62. it is not. Calling this function with these two propertes would
  63. update the current property to be like the second, since it is less
  64. specific.
  65. """
  66. if newprop.type < self.type:
  67. self.type = newprop.type
  68. if type(newprop.value) == list and type(self.value) != list:
  69. self.value = [self.value]
  70. if type(self.value) == list and len(newprop.value) > len(self.value):
  71. val = self.GetEmpty(self.type)
  72. while len(self.value) < len(newprop.value):
  73. self.value.append(val)
  74. def BytesToValue(self, bytes):
  75. """Converts a string of bytes into a type and value
  76. Args:
  77. A string containing bytes
  78. Return:
  79. A tuple:
  80. Type of data
  81. Data, either a single element or a list of elements. Each element
  82. is one of:
  83. TYPE_STRING: string value from the property
  84. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  85. TYPE_BYTE: a byte stored as a single-byte string
  86. """
  87. bytes = str(bytes)
  88. size = len(bytes)
  89. strings = bytes.split('\0')
  90. is_string = True
  91. count = len(strings) - 1
  92. if count > 0 and not strings[-1]:
  93. for string in strings[:-1]:
  94. if not string:
  95. is_string = False
  96. break
  97. for ch in string:
  98. if ch < ' ' or ch > '~':
  99. is_string = False
  100. break
  101. else:
  102. is_string = False
  103. if is_string:
  104. if count == 1:
  105. return TYPE_STRING, strings[0]
  106. else:
  107. return TYPE_STRING, strings[:-1]
  108. if size % 4:
  109. if size == 1:
  110. return TYPE_BYTE, bytes[0]
  111. else:
  112. return TYPE_BYTE, list(bytes)
  113. val = []
  114. for i in range(0, size, 4):
  115. val.append(bytes[i:i + 4])
  116. if size == 4:
  117. return TYPE_INT, val[0]
  118. else:
  119. return TYPE_INT, val
  120. @classmethod
  121. def GetEmpty(self, type):
  122. """Get an empty / zero value of the given type
  123. Returns:
  124. A single value of the given type
  125. """
  126. if type == TYPE_BYTE:
  127. return chr(0)
  128. elif type == TYPE_INT:
  129. return struct.pack('<I', 0);
  130. elif type == TYPE_STRING:
  131. return ''
  132. else:
  133. return True
  134. def GetOffset(self):
  135. """Get the offset of a property
  136. Returns:
  137. The offset of the property (struct fdt_property) within the file
  138. """
  139. self._node._fdt.CheckCache()
  140. return self._node._fdt.GetStructOffset(self._offset)
  141. def SetInt(self, val):
  142. """Set the integer value of the property
  143. The device tree is marked dirty so that the value will be written to
  144. the block on the next sync.
  145. Args:
  146. val: Integer value (32-bit, single cell)
  147. """
  148. self.bytes = struct.pack('>I', val);
  149. self.value = val
  150. self.type = TYPE_INT
  151. self.dirty = True
  152. def Sync(self, auto_resize=False):
  153. """Sync property changes back to the device tree
  154. This updates the device tree blob with any changes to this property
  155. since the last sync.
  156. Args:
  157. auto_resize: Resize the device tree automatically if it does not
  158. have enough space for the update
  159. Raises:
  160. FdtException if auto_resize is False and there is not enough space
  161. """
  162. if self._offset is None or self.dirty:
  163. node = self._node
  164. fdt_obj = node._fdt._fdt_obj
  165. if auto_resize:
  166. while fdt_obj.setprop(node.Offset(), self.name, self.bytes,
  167. (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
  168. fdt_obj.resize(fdt_obj.totalsize() + 1024)
  169. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  170. else:
  171. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  172. class Node:
  173. """A device tree node
  174. Properties:
  175. offset: Integer offset in the device tree
  176. name: Device tree node tname
  177. path: Full path to node, along with the node name itself
  178. _fdt: Device tree object
  179. subnodes: A list of subnodes for this node, each a Node object
  180. props: A dict of properties for this node, each a Prop object.
  181. Keyed by property name
  182. """
  183. def __init__(self, fdt, parent, offset, name, path):
  184. self._fdt = fdt
  185. self.parent = parent
  186. self._offset = offset
  187. self.name = name
  188. self.path = path
  189. self.subnodes = []
  190. self.props = {}
  191. def GetFdt(self):
  192. """Get the Fdt object for this node
  193. Returns:
  194. Fdt object
  195. """
  196. return self._fdt
  197. def FindNode(self, name):
  198. """Find a node given its name
  199. Args:
  200. name: Node name to look for
  201. Returns:
  202. Node object if found, else None
  203. """
  204. for subnode in self.subnodes:
  205. if subnode.name == name:
  206. return subnode
  207. return None
  208. def Offset(self):
  209. """Returns the offset of a node, after checking the cache
  210. This should be used instead of self._offset directly, to ensure that
  211. the cache does not contain invalid offsets.
  212. """
  213. self._fdt.CheckCache()
  214. return self._offset
  215. def Scan(self):
  216. """Scan a node's properties and subnodes
  217. This fills in the props and subnodes properties, recursively
  218. searching into subnodes so that the entire tree is built.
  219. """
  220. fdt_obj = self._fdt._fdt_obj
  221. self.props = self._fdt.GetProps(self)
  222. phandle = fdt_obj.get_phandle(self.Offset())
  223. if phandle:
  224. self._fdt.phandle_to_node[phandle] = self
  225. offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
  226. while offset >= 0:
  227. sep = '' if self.path[-1] == '/' else '/'
  228. name = fdt_obj.get_name(offset)
  229. path = self.path + sep + name
  230. node = Node(self._fdt, self, offset, name, path)
  231. self.subnodes.append(node)
  232. node.Scan()
  233. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  234. def Refresh(self, my_offset):
  235. """Fix up the _offset for each node, recursively
  236. Note: This does not take account of property offsets - these will not
  237. be updated.
  238. """
  239. fdt_obj = self._fdt._fdt_obj
  240. if self._offset != my_offset:
  241. self._offset = my_offset
  242. offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
  243. for subnode in self.subnodes:
  244. if subnode.name != fdt_obj.get_name(offset):
  245. raise ValueError('Internal error, node name mismatch %s != %s' %
  246. (subnode.name, fdt_obj.get_name(offset)))
  247. subnode.Refresh(offset)
  248. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  249. if offset != -libfdt.FDT_ERR_NOTFOUND:
  250. raise ValueError('Internal error, offset == %d' % offset)
  251. poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
  252. while poffset >= 0:
  253. p = fdt_obj.get_property_by_offset(poffset)
  254. prop = self.props.get(p.name)
  255. if not prop:
  256. raise ValueError("Internal error, property '%s' missing, "
  257. 'offset %d' % (p.name, poffset))
  258. prop.RefreshOffset(poffset)
  259. poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
  260. def DeleteProp(self, prop_name):
  261. """Delete a property of a node
  262. The property is deleted and the offset cache is invalidated.
  263. Args:
  264. prop_name: Name of the property to delete
  265. Raises:
  266. ValueError if the property does not exist
  267. """
  268. CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
  269. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  270. del self.props[prop_name]
  271. self._fdt.Invalidate()
  272. def AddZeroProp(self, prop_name):
  273. """Add a new property to the device tree with an integer value of 0.
  274. Args:
  275. prop_name: Name of property
  276. """
  277. self.props[prop_name] = Prop(self, None, prop_name, '\0' * 4)
  278. def SetInt(self, prop_name, val):
  279. """Update an integer property int the device tree.
  280. This is not allowed to change the size of the FDT.
  281. Args:
  282. prop_name: Name of property
  283. val: Value to set
  284. """
  285. self.props[prop_name].SetInt(val)
  286. def Sync(self, auto_resize=False):
  287. """Sync node changes back to the device tree
  288. This updates the device tree blob with any changes to this node and its
  289. subnodes since the last sync.
  290. Args:
  291. auto_resize: Resize the device tree automatically if it does not
  292. have enough space for the update
  293. Raises:
  294. FdtException if auto_resize is False and there is not enough space
  295. """
  296. # Sync subnodes in reverse so that we don't disturb node offsets for
  297. # nodes that are earlier in the DT. This avoids an O(n^2) rescan of
  298. # node offsets.
  299. for node in reversed(self.subnodes):
  300. node.Sync(auto_resize)
  301. # Sync properties now, whose offsets should not have been disturbed.
  302. # We do this after subnodes, since this disturbs the offsets of these
  303. # properties.
  304. prop_list = sorted(self.props.values(), key=lambda prop: prop._offset,
  305. reverse=True)
  306. for prop in prop_list:
  307. prop.Sync(auto_resize)
  308. class Fdt:
  309. """Provides simple access to a flat device tree blob using libfdts.
  310. Properties:
  311. fname: Filename of fdt
  312. _root: Root of device tree (a Node object)
  313. """
  314. def __init__(self, fname):
  315. self._fname = fname
  316. self._cached_offsets = False
  317. self.phandle_to_node = {}
  318. if self._fname:
  319. self._fname = fdt_util.EnsureCompiled(self._fname)
  320. with open(self._fname) as fd:
  321. self._fdt_obj = libfdt.Fdt(fd.read())
  322. def LookupPhandle(self, phandle):
  323. """Look up a phandle
  324. Args:
  325. phandle: Phandle to look up (int)
  326. Returns:
  327. Node object the phandle points to
  328. """
  329. return self.phandle_to_node.get(phandle)
  330. def Scan(self, root='/'):
  331. """Scan a device tree, building up a tree of Node objects
  332. This fills in the self._root property
  333. Args:
  334. root: Ignored
  335. TODO(sjg@chromium.org): Implement the 'root' parameter
  336. """
  337. self._cached_offsets = True
  338. self._root = self.Node(self, None, 0, '/', '/')
  339. self._root.Scan()
  340. def GetRoot(self):
  341. """Get the root Node of the device tree
  342. Returns:
  343. The root Node object
  344. """
  345. return self._root
  346. def GetNode(self, path):
  347. """Look up a node from its path
  348. Args:
  349. path: Path to look up, e.g. '/microcode/update@0'
  350. Returns:
  351. Node object, or None if not found
  352. """
  353. node = self._root
  354. parts = path.split('/')
  355. if len(parts) < 2:
  356. return None
  357. for part in parts[1:]:
  358. node = node.FindNode(part)
  359. if not node:
  360. return None
  361. return node
  362. def Flush(self):
  363. """Flush device tree changes back to the file
  364. If the device tree has changed in memory, write it back to the file.
  365. """
  366. with open(self._fname, 'wb') as fd:
  367. fd.write(self._fdt_obj.as_bytearray())
  368. def Sync(self, auto_resize=False):
  369. """Make sure any DT changes are written to the blob
  370. Args:
  371. auto_resize: Resize the device tree automatically if it does not
  372. have enough space for the update
  373. Raises:
  374. FdtException if auto_resize is False and there is not enough space
  375. """
  376. self._root.Sync(auto_resize)
  377. self.Invalidate()
  378. def Pack(self):
  379. """Pack the device tree down to its minimum size
  380. When nodes and properties shrink or are deleted, wasted space can
  381. build up in the device tree binary.
  382. """
  383. CheckErr(self._fdt_obj.pack(), 'pack')
  384. self.Invalidate()
  385. def GetContents(self):
  386. """Get the contents of the FDT
  387. Returns:
  388. The FDT contents as a string of bytes
  389. """
  390. return self._fdt_obj.as_bytearray()
  391. def GetFdtObj(self):
  392. """Get the contents of the FDT
  393. Returns:
  394. The FDT contents as a libfdt.Fdt object
  395. """
  396. return self._fdt_obj
  397. def GetProps(self, node):
  398. """Get all properties from a node.
  399. Args:
  400. node: Full path to node name to look in.
  401. Returns:
  402. A dictionary containing all the properties, indexed by node name.
  403. The entries are Prop objects.
  404. Raises:
  405. ValueError: if the node does not exist.
  406. """
  407. props_dict = {}
  408. poffset = self._fdt_obj.first_property_offset(node._offset,
  409. QUIET_NOTFOUND)
  410. while poffset >= 0:
  411. p = self._fdt_obj.get_property_by_offset(poffset)
  412. prop = Prop(node, poffset, p.name, p)
  413. props_dict[prop.name] = prop
  414. poffset = self._fdt_obj.next_property_offset(poffset,
  415. QUIET_NOTFOUND)
  416. return props_dict
  417. def Invalidate(self):
  418. """Mark our offset cache as invalid"""
  419. self._cached_offsets = False
  420. def CheckCache(self):
  421. """Refresh the offset cache if needed"""
  422. if self._cached_offsets:
  423. return
  424. self.Refresh()
  425. self._cached_offsets = True
  426. def Refresh(self):
  427. """Refresh the offset cache"""
  428. self._root.Refresh(0)
  429. def GetStructOffset(self, offset):
  430. """Get the file offset of a given struct offset
  431. Args:
  432. offset: Offset within the 'struct' region of the device tree
  433. Returns:
  434. Position of @offset within the device tree binary
  435. """
  436. return self._fdt_obj.off_dt_struct() + offset
  437. @classmethod
  438. def Node(self, fdt, parent, offset, name, path):
  439. """Create a new node
  440. This is used by Fdt.Scan() to create a new node using the correct
  441. class.
  442. Args:
  443. fdt: Fdt object
  444. parent: Parent node, or None if this is the root node
  445. offset: Offset of node
  446. name: Node name
  447. path: Full path to node
  448. """
  449. node = Node(fdt, parent, offset, name, path)
  450. return node
  451. def FdtScan(fname):
  452. """Returns a new Fdt object"""
  453. dtb = Fdt(fname)
  454. dtb.Scan()
  455. return dtb