fdt.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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 = self.bytes
  150. self.type = TYPE_INT
  151. self.dirty = True
  152. def SetData(self, bytes):
  153. """Set the value of a property as bytes
  154. Args:
  155. bytes: New property value to set
  156. """
  157. self.bytes = str(bytes)
  158. self.type, self.value = self.BytesToValue(bytes)
  159. self.dirty = True
  160. def Sync(self, auto_resize=False):
  161. """Sync property changes back to the device tree
  162. This updates the device tree blob with any changes to this property
  163. since the last sync.
  164. Args:
  165. auto_resize: Resize the device tree automatically if it does not
  166. have enough space for the update
  167. Raises:
  168. FdtException if auto_resize is False and there is not enough space
  169. """
  170. if self._offset is None or self.dirty:
  171. node = self._node
  172. fdt_obj = node._fdt._fdt_obj
  173. if auto_resize:
  174. while fdt_obj.setprop(node.Offset(), self.name, self.bytes,
  175. (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
  176. fdt_obj.resize(fdt_obj.totalsize() + 1024)
  177. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  178. else:
  179. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  180. class Node:
  181. """A device tree node
  182. Properties:
  183. offset: Integer offset in the device tree
  184. name: Device tree node tname
  185. path: Full path to node, along with the node name itself
  186. _fdt: Device tree object
  187. subnodes: A list of subnodes for this node, each a Node object
  188. props: A dict of properties for this node, each a Prop object.
  189. Keyed by property name
  190. """
  191. def __init__(self, fdt, parent, offset, name, path):
  192. self._fdt = fdt
  193. self.parent = parent
  194. self._offset = offset
  195. self.name = name
  196. self.path = path
  197. self.subnodes = []
  198. self.props = {}
  199. def GetFdt(self):
  200. """Get the Fdt object for this node
  201. Returns:
  202. Fdt object
  203. """
  204. return self._fdt
  205. def FindNode(self, name):
  206. """Find a node given its name
  207. Args:
  208. name: Node name to look for
  209. Returns:
  210. Node object if found, else None
  211. """
  212. for subnode in self.subnodes:
  213. if subnode.name == name:
  214. return subnode
  215. return None
  216. def Offset(self):
  217. """Returns the offset of a node, after checking the cache
  218. This should be used instead of self._offset directly, to ensure that
  219. the cache does not contain invalid offsets.
  220. """
  221. self._fdt.CheckCache()
  222. return self._offset
  223. def Scan(self):
  224. """Scan a node's properties and subnodes
  225. This fills in the props and subnodes properties, recursively
  226. searching into subnodes so that the entire tree is built.
  227. """
  228. fdt_obj = self._fdt._fdt_obj
  229. self.props = self._fdt.GetProps(self)
  230. phandle = fdt_obj.get_phandle(self.Offset())
  231. if phandle:
  232. self._fdt.phandle_to_node[phandle] = self
  233. offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
  234. while offset >= 0:
  235. sep = '' if self.path[-1] == '/' else '/'
  236. name = fdt_obj.get_name(offset)
  237. path = self.path + sep + name
  238. node = Node(self._fdt, self, offset, name, path)
  239. self.subnodes.append(node)
  240. node.Scan()
  241. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  242. def Refresh(self, my_offset):
  243. """Fix up the _offset for each node, recursively
  244. Note: This does not take account of property offsets - these will not
  245. be updated.
  246. """
  247. fdt_obj = self._fdt._fdt_obj
  248. if self._offset != my_offset:
  249. self._offset = my_offset
  250. offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
  251. for subnode in self.subnodes:
  252. if subnode.name != fdt_obj.get_name(offset):
  253. raise ValueError('Internal error, node name mismatch %s != %s' %
  254. (subnode.name, fdt_obj.get_name(offset)))
  255. subnode.Refresh(offset)
  256. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  257. if offset != -libfdt.FDT_ERR_NOTFOUND:
  258. raise ValueError('Internal error, offset == %d' % offset)
  259. poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
  260. while poffset >= 0:
  261. p = fdt_obj.get_property_by_offset(poffset)
  262. prop = self.props.get(p.name)
  263. if not prop:
  264. raise ValueError("Internal error, property '%s' missing, "
  265. 'offset %d' % (p.name, poffset))
  266. prop.RefreshOffset(poffset)
  267. poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
  268. def DeleteProp(self, prop_name):
  269. """Delete a property of a node
  270. The property is deleted and the offset cache is invalidated.
  271. Args:
  272. prop_name: Name of the property to delete
  273. Raises:
  274. ValueError if the property does not exist
  275. """
  276. CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
  277. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  278. del self.props[prop_name]
  279. self._fdt.Invalidate()
  280. def AddZeroProp(self, prop_name):
  281. """Add a new property to the device tree with an integer value of 0.
  282. Args:
  283. prop_name: Name of property
  284. """
  285. self.props[prop_name] = Prop(self, None, prop_name, '\0' * 4)
  286. def AddEmptyProp(self, prop_name, len):
  287. """Add a property with a fixed data size, for filling in later
  288. The device tree is marked dirty so that the value will be written to
  289. the blob on the next sync.
  290. Args:
  291. prop_name: Name of property
  292. len: Length of data in property
  293. """
  294. value = chr(0) * len
  295. self.props[prop_name] = Prop(self, None, prop_name, value)
  296. def SetInt(self, prop_name, val):
  297. """Update an integer property int the device tree.
  298. This is not allowed to change the size of the FDT.
  299. The device tree is marked dirty so that the value will be written to
  300. the blob on the next sync.
  301. Args:
  302. prop_name: Name of property
  303. val: Value to set
  304. """
  305. self.props[prop_name].SetInt(val)
  306. def SetData(self, prop_name, val):
  307. """Set the data value of a property
  308. The device tree is marked dirty so that the value will be written to
  309. the blob on the next sync.
  310. Args:
  311. prop_name: Name of property to set
  312. val: Data value to set
  313. """
  314. self.props[prop_name].SetData(val)
  315. def SetString(self, prop_name, val):
  316. """Set the string value of a property
  317. The device tree is marked dirty so that the value will be written to
  318. the blob on the next sync.
  319. Args:
  320. prop_name: Name of property to set
  321. val: String value to set (will be \0-terminated in DT)
  322. """
  323. self.props[prop_name].SetData(val + chr(0))
  324. def AddString(self, prop_name, val):
  325. """Add a new string property to a node
  326. The device tree is marked dirty so that the value will be written to
  327. the blob on the next sync.
  328. Args:
  329. prop_name: Name of property to add
  330. val: String value of property
  331. """
  332. self.props[prop_name] = Prop(self, None, prop_name, val + chr(0))
  333. def AddSubnode(self, name):
  334. """Add a new subnode to the node
  335. Args:
  336. name: name of node to add
  337. Returns:
  338. New subnode that was created
  339. """
  340. path = self.path + '/' + name
  341. subnode = Node(self._fdt, self, None, name, path)
  342. self.subnodes.append(subnode)
  343. return subnode
  344. def Sync(self, auto_resize=False):
  345. """Sync node changes back to the device tree
  346. This updates the device tree blob with any changes to this node and its
  347. subnodes since the last sync.
  348. Args:
  349. auto_resize: Resize the device tree automatically if it does not
  350. have enough space for the update
  351. Raises:
  352. FdtException if auto_resize is False and there is not enough space
  353. """
  354. if self._offset is None:
  355. # The subnode doesn't exist yet, so add it
  356. fdt_obj = self._fdt._fdt_obj
  357. if auto_resize:
  358. while True:
  359. offset = fdt_obj.add_subnode(self.parent._offset, self.name,
  360. (libfdt.NOSPACE,))
  361. if offset != -libfdt.NOSPACE:
  362. break
  363. fdt_obj.resize(fdt_obj.totalsize() + 1024)
  364. else:
  365. offset = fdt_obj.add_subnode(self.parent._offset, self.name)
  366. self._offset = offset
  367. # Sync subnodes in reverse so that we don't disturb node offsets for
  368. # nodes that are earlier in the DT. This avoids an O(n^2) rescan of
  369. # node offsets.
  370. for node in reversed(self.subnodes):
  371. node.Sync(auto_resize)
  372. # Sync properties now, whose offsets should not have been disturbed.
  373. # We do this after subnodes, since this disturbs the offsets of these
  374. # properties.
  375. prop_list = sorted(self.props.values(), key=lambda prop: prop._offset,
  376. reverse=True)
  377. for prop in prop_list:
  378. prop.Sync(auto_resize)
  379. class Fdt:
  380. """Provides simple access to a flat device tree blob using libfdts.
  381. Properties:
  382. fname: Filename of fdt
  383. _root: Root of device tree (a Node object)
  384. """
  385. def __init__(self, fname):
  386. self._fname = fname
  387. self._cached_offsets = False
  388. self.phandle_to_node = {}
  389. if self._fname:
  390. self._fname = fdt_util.EnsureCompiled(self._fname)
  391. with open(self._fname) as fd:
  392. self._fdt_obj = libfdt.Fdt(fd.read())
  393. @staticmethod
  394. def FromData(data):
  395. """Create a new Fdt object from the given data
  396. Args:
  397. data: Device-tree data blob
  398. Returns:
  399. Fdt object containing the data
  400. """
  401. fdt = Fdt(None)
  402. fdt._fdt_obj = libfdt.Fdt(bytearray(data))
  403. return fdt
  404. def LookupPhandle(self, phandle):
  405. """Look up a phandle
  406. Args:
  407. phandle: Phandle to look up (int)
  408. Returns:
  409. Node object the phandle points to
  410. """
  411. return self.phandle_to_node.get(phandle)
  412. def Scan(self, root='/'):
  413. """Scan a device tree, building up a tree of Node objects
  414. This fills in the self._root property
  415. Args:
  416. root: Ignored
  417. TODO(sjg@chromium.org): Implement the 'root' parameter
  418. """
  419. self._cached_offsets = True
  420. self._root = self.Node(self, None, 0, '/', '/')
  421. self._root.Scan()
  422. def GetRoot(self):
  423. """Get the root Node of the device tree
  424. Returns:
  425. The root Node object
  426. """
  427. return self._root
  428. def GetNode(self, path):
  429. """Look up a node from its path
  430. Args:
  431. path: Path to look up, e.g. '/microcode/update@0'
  432. Returns:
  433. Node object, or None if not found
  434. """
  435. node = self._root
  436. parts = path.split('/')
  437. if len(parts) < 2:
  438. return None
  439. for part in parts[1:]:
  440. node = node.FindNode(part)
  441. if not node:
  442. return None
  443. return node
  444. def Flush(self):
  445. """Flush device tree changes back to the file
  446. If the device tree has changed in memory, write it back to the file.
  447. """
  448. with open(self._fname, 'wb') as fd:
  449. fd.write(self._fdt_obj.as_bytearray())
  450. def Sync(self, auto_resize=False):
  451. """Make sure any DT changes are written to the blob
  452. Args:
  453. auto_resize: Resize the device tree automatically if it does not
  454. have enough space for the update
  455. Raises:
  456. FdtException if auto_resize is False and there is not enough space
  457. """
  458. self._root.Sync(auto_resize)
  459. self.Invalidate()
  460. def Pack(self):
  461. """Pack the device tree down to its minimum size
  462. When nodes and properties shrink or are deleted, wasted space can
  463. build up in the device tree binary.
  464. """
  465. CheckErr(self._fdt_obj.pack(), 'pack')
  466. self.Invalidate()
  467. def GetContents(self):
  468. """Get the contents of the FDT
  469. Returns:
  470. The FDT contents as a string of bytes
  471. """
  472. return self._fdt_obj.as_bytearray()
  473. def GetFdtObj(self):
  474. """Get the contents of the FDT
  475. Returns:
  476. The FDT contents as a libfdt.Fdt object
  477. """
  478. return self._fdt_obj
  479. def GetProps(self, node):
  480. """Get all properties from a node.
  481. Args:
  482. node: Full path to node name to look in.
  483. Returns:
  484. A dictionary containing all the properties, indexed by node name.
  485. The entries are Prop objects.
  486. Raises:
  487. ValueError: if the node does not exist.
  488. """
  489. props_dict = {}
  490. poffset = self._fdt_obj.first_property_offset(node._offset,
  491. QUIET_NOTFOUND)
  492. while poffset >= 0:
  493. p = self._fdt_obj.get_property_by_offset(poffset)
  494. prop = Prop(node, poffset, p.name, p)
  495. props_dict[prop.name] = prop
  496. poffset = self._fdt_obj.next_property_offset(poffset,
  497. QUIET_NOTFOUND)
  498. return props_dict
  499. def Invalidate(self):
  500. """Mark our offset cache as invalid"""
  501. self._cached_offsets = False
  502. def CheckCache(self):
  503. """Refresh the offset cache if needed"""
  504. if self._cached_offsets:
  505. return
  506. self.Refresh()
  507. self._cached_offsets = True
  508. def Refresh(self):
  509. """Refresh the offset cache"""
  510. self._root.Refresh(0)
  511. def GetStructOffset(self, offset):
  512. """Get the file offset of a given struct offset
  513. Args:
  514. offset: Offset within the 'struct' region of the device tree
  515. Returns:
  516. Position of @offset within the device tree binary
  517. """
  518. return self._fdt_obj.off_dt_struct() + offset
  519. @classmethod
  520. def Node(self, fdt, parent, offset, name, path):
  521. """Create a new node
  522. This is used by Fdt.Scan() to create a new node using the correct
  523. class.
  524. Args:
  525. fdt: Fdt object
  526. parent: Parent node, or None if this is the root node
  527. offset: Offset of node
  528. name: Node name
  529. path: Full path to node
  530. """
  531. node = Node(fdt, parent, offset, name, path)
  532. return node
  533. def FdtScan(fname):
  534. """Returns a new Fdt object"""
  535. dtb = Fdt(fname)
  536. dtb.Scan()
  537. return dtb