fdt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 AddSubnode(self, name):
  287. path = self.path + '/' + name
  288. subnode = Node(self._fdt, self, None, name, path)
  289. self.subnodes.append(subnode)
  290. return subnode
  291. def Sync(self, auto_resize=False):
  292. """Sync node changes back to the device tree
  293. This updates the device tree blob with any changes to this node and its
  294. subnodes since the last sync.
  295. Args:
  296. auto_resize: Resize the device tree automatically if it does not
  297. have enough space for the update
  298. Raises:
  299. FdtException if auto_resize is False and there is not enough space
  300. """
  301. if self._offset is None:
  302. # The subnode doesn't exist yet, so add it
  303. fdt_obj = self._fdt._fdt_obj
  304. if auto_resize:
  305. while True:
  306. offset = fdt_obj.add_subnode(self.parent._offset, self.name,
  307. (libfdt.NOSPACE,))
  308. if offset != -libfdt.NOSPACE:
  309. break
  310. fdt_obj.resize(fdt_obj.totalsize() + 1024)
  311. else:
  312. offset = fdt_obj.add_subnode(self.parent._offset, self.name)
  313. self._offset = offset
  314. # Sync subnodes in reverse so that we don't disturb node offsets for
  315. # nodes that are earlier in the DT. This avoids an O(n^2) rescan of
  316. # node offsets.
  317. for node in reversed(self.subnodes):
  318. node.Sync(auto_resize)
  319. # Sync properties now, whose offsets should not have been disturbed.
  320. # We do this after subnodes, since this disturbs the offsets of these
  321. # properties.
  322. prop_list = sorted(self.props.values(), key=lambda prop: prop._offset,
  323. reverse=True)
  324. for prop in prop_list:
  325. prop.Sync(auto_resize)
  326. class Fdt:
  327. """Provides simple access to a flat device tree blob using libfdts.
  328. Properties:
  329. fname: Filename of fdt
  330. _root: Root of device tree (a Node object)
  331. """
  332. def __init__(self, fname):
  333. self._fname = fname
  334. self._cached_offsets = False
  335. self.phandle_to_node = {}
  336. if self._fname:
  337. self._fname = fdt_util.EnsureCompiled(self._fname)
  338. with open(self._fname) as fd:
  339. self._fdt_obj = libfdt.Fdt(fd.read())
  340. def LookupPhandle(self, phandle):
  341. """Look up a phandle
  342. Args:
  343. phandle: Phandle to look up (int)
  344. Returns:
  345. Node object the phandle points to
  346. """
  347. return self.phandle_to_node.get(phandle)
  348. def Scan(self, root='/'):
  349. """Scan a device tree, building up a tree of Node objects
  350. This fills in the self._root property
  351. Args:
  352. root: Ignored
  353. TODO(sjg@chromium.org): Implement the 'root' parameter
  354. """
  355. self._cached_offsets = True
  356. self._root = self.Node(self, None, 0, '/', '/')
  357. self._root.Scan()
  358. def GetRoot(self):
  359. """Get the root Node of the device tree
  360. Returns:
  361. The root Node object
  362. """
  363. return self._root
  364. def GetNode(self, path):
  365. """Look up a node from its path
  366. Args:
  367. path: Path to look up, e.g. '/microcode/update@0'
  368. Returns:
  369. Node object, or None if not found
  370. """
  371. node = self._root
  372. parts = path.split('/')
  373. if len(parts) < 2:
  374. return None
  375. for part in parts[1:]:
  376. node = node.FindNode(part)
  377. if not node:
  378. return None
  379. return node
  380. def Flush(self):
  381. """Flush device tree changes back to the file
  382. If the device tree has changed in memory, write it back to the file.
  383. """
  384. with open(self._fname, 'wb') as fd:
  385. fd.write(self._fdt_obj.as_bytearray())
  386. def Sync(self, auto_resize=False):
  387. """Make sure any DT changes are written to the blob
  388. Args:
  389. auto_resize: Resize the device tree automatically if it does not
  390. have enough space for the update
  391. Raises:
  392. FdtException if auto_resize is False and there is not enough space
  393. """
  394. self._root.Sync(auto_resize)
  395. self.Invalidate()
  396. def Pack(self):
  397. """Pack the device tree down to its minimum size
  398. When nodes and properties shrink or are deleted, wasted space can
  399. build up in the device tree binary.
  400. """
  401. CheckErr(self._fdt_obj.pack(), 'pack')
  402. self.Invalidate()
  403. def GetContents(self):
  404. """Get the contents of the FDT
  405. Returns:
  406. The FDT contents as a string of bytes
  407. """
  408. return self._fdt_obj.as_bytearray()
  409. def GetFdtObj(self):
  410. """Get the contents of the FDT
  411. Returns:
  412. The FDT contents as a libfdt.Fdt object
  413. """
  414. return self._fdt_obj
  415. def GetProps(self, node):
  416. """Get all properties from a node.
  417. Args:
  418. node: Full path to node name to look in.
  419. Returns:
  420. A dictionary containing all the properties, indexed by node name.
  421. The entries are Prop objects.
  422. Raises:
  423. ValueError: if the node does not exist.
  424. """
  425. props_dict = {}
  426. poffset = self._fdt_obj.first_property_offset(node._offset,
  427. QUIET_NOTFOUND)
  428. while poffset >= 0:
  429. p = self._fdt_obj.get_property_by_offset(poffset)
  430. prop = Prop(node, poffset, p.name, p)
  431. props_dict[prop.name] = prop
  432. poffset = self._fdt_obj.next_property_offset(poffset,
  433. QUIET_NOTFOUND)
  434. return props_dict
  435. def Invalidate(self):
  436. """Mark our offset cache as invalid"""
  437. self._cached_offsets = False
  438. def CheckCache(self):
  439. """Refresh the offset cache if needed"""
  440. if self._cached_offsets:
  441. return
  442. self.Refresh()
  443. self._cached_offsets = True
  444. def Refresh(self):
  445. """Refresh the offset cache"""
  446. self._root.Refresh(0)
  447. def GetStructOffset(self, offset):
  448. """Get the file offset of a given struct offset
  449. Args:
  450. offset: Offset within the 'struct' region of the device tree
  451. Returns:
  452. Position of @offset within the device tree binary
  453. """
  454. return self._fdt_obj.off_dt_struct() + offset
  455. @classmethod
  456. def Node(self, fdt, parent, offset, name, path):
  457. """Create a new node
  458. This is used by Fdt.Scan() to create a new node using the correct
  459. class.
  460. Args:
  461. fdt: Fdt object
  462. parent: Parent node, or None if this is the root node
  463. offset: Offset of node
  464. name: Node name
  465. path: Full path to node
  466. """
  467. node = Node(fdt, parent, offset, name, path)
  468. return node
  469. def FdtScan(fname):
  470. """Returns a new Fdt object"""
  471. dtb = Fdt(fname)
  472. dtb.Scan()
  473. return dtb