dtoc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 copy
  9. from optparse import OptionError, OptionParser
  10. import os
  11. import sys
  12. import fdt_util
  13. # Bring in the patman libraries
  14. our_path = os.path.dirname(os.path.realpath(__file__))
  15. sys.path.append(os.path.join(our_path, '../patman'))
  16. # Bring in either the normal fdt library (which relies on libfdt) or the
  17. # fallback one (which uses fdtget and is slower). Both provide the same
  18. # interfface for this file to use.
  19. try:
  20. from fdt import Fdt
  21. import fdt
  22. have_libfdt = True
  23. except ImportError:
  24. have_libfdt = False
  25. from fdt_fallback import Fdt
  26. import fdt_fallback as fdt
  27. import struct
  28. # When we see these properties we ignore them - i.e. do not create a structure member
  29. PROP_IGNORE_LIST = [
  30. '#address-cells',
  31. '#gpio-cells',
  32. '#size-cells',
  33. 'compatible',
  34. 'linux,phandle',
  35. "status",
  36. 'phandle',
  37. 'u-boot,dm-pre-reloc',
  38. ]
  39. # C type declarations for the tyues we support
  40. TYPE_NAMES = {
  41. fdt_util.TYPE_INT: 'fdt32_t',
  42. fdt_util.TYPE_BYTE: 'unsigned char',
  43. fdt_util.TYPE_STRING: 'const char *',
  44. fdt_util.TYPE_BOOL: 'bool',
  45. };
  46. STRUCT_PREFIX = 'dtd_'
  47. VAL_PREFIX = 'dtv_'
  48. def Conv_name_to_c(name):
  49. """Convert a device-tree name to a C identifier
  50. Args:
  51. name: Name to convert
  52. Return:
  53. String containing the C version of this name
  54. """
  55. str = name.replace('@', '_at_')
  56. str = str.replace('-', '_')
  57. str = str.replace(',', '_')
  58. str = str.replace('/', '__')
  59. return str
  60. def TabTo(num_tabs, str):
  61. if len(str) >= num_tabs * 8:
  62. return str + ' '
  63. return str + '\t' * (num_tabs - len(str) / 8)
  64. class DtbPlatdata:
  65. """Provide a means to convert device tree binary data to platform data
  66. The output of this process is C structures which can be used in space-
  67. constrained encvironments where the ~3KB code overhead of device tree
  68. code is not affordable.
  69. Properties:
  70. fdt: Fdt object, referencing the device tree
  71. _dtb_fname: Filename of the input device tree binary file
  72. _valid_nodes: A list of Node object with compatible strings
  73. _options: Command-line options
  74. _phandle_node: A dict of nodes indexed by phandle number (1, 2...)
  75. _outfile: The current output file (sys.stdout or a real file)
  76. _lines: Stashed list of output lines for outputting in the future
  77. _phandle_node: A dict of Nodes indexed by phandle (an integer)
  78. """
  79. def __init__(self, dtb_fname, options):
  80. self._dtb_fname = dtb_fname
  81. self._valid_nodes = None
  82. self._options = options
  83. self._phandle_node = {}
  84. self._outfile = None
  85. self._lines = []
  86. def SetupOutput(self, fname):
  87. """Set up the output destination
  88. Once this is done, future calls to self.Out() will output to this
  89. file.
  90. Args:
  91. fname: Filename to send output to, or '-' for stdout
  92. """
  93. if fname == '-':
  94. self._outfile = sys.stdout
  95. else:
  96. self._outfile = open(fname, 'w')
  97. def Out(self, str):
  98. """Output a string to the output file
  99. Args:
  100. str: String to output
  101. """
  102. self._outfile.write(str)
  103. def Buf(self, str):
  104. """Buffer up a string to send later
  105. Args:
  106. str: String to add to our 'buffer' list
  107. """
  108. self._lines.append(str)
  109. def GetBuf(self):
  110. """Get the contents of the output buffer, and clear it
  111. Returns:
  112. The output buffer, which is then cleared for future use
  113. """
  114. lines = self._lines
  115. self._lines = []
  116. return lines
  117. def GetValue(self, type, value):
  118. """Get a value as a C expression
  119. For integers this returns a byte-swapped (little-endian) hex string
  120. For bytes this returns a hex string, e.g. 0x12
  121. For strings this returns a literal string enclosed in quotes
  122. For booleans this return 'true'
  123. Args:
  124. type: Data type (fdt_util)
  125. value: Data value, as a string of bytes
  126. """
  127. if type == fdt_util.TYPE_INT:
  128. return '%#x' % fdt_util.fdt32_to_cpu(value)
  129. elif type == fdt_util.TYPE_BYTE:
  130. return '%#x' % ord(value[0])
  131. elif type == fdt_util.TYPE_STRING:
  132. return '"%s"' % value
  133. elif type == fdt_util.TYPE_BOOL:
  134. return 'true'
  135. def GetCompatName(self, node):
  136. """Get a node's first compatible string as a C identifier
  137. Args:
  138. node: Node object to check
  139. Return:
  140. C identifier for the first compatible string
  141. """
  142. compat = node.props['compatible'].value
  143. if type(compat) == list:
  144. compat = compat[0]
  145. return Conv_name_to_c(compat)
  146. def ScanDtb(self):
  147. """Scan the device tree to obtain a tree of notes and properties
  148. Once this is done, self.fdt.GetRoot() can be called to obtain the
  149. device tree root node, and progress from there.
  150. """
  151. self.fdt = Fdt(self._dtb_fname)
  152. self.fdt.Scan()
  153. def ScanTree(self):
  154. """Scan the device tree for useful information
  155. This fills in the following properties:
  156. _phandle_node: A dict of Nodes indexed by phandle (an integer)
  157. _valid_nodes: A list of nodes we wish to consider include in the
  158. platform data
  159. """
  160. node_list = []
  161. self._phandle_node = {}
  162. for node in self.fdt.GetRoot().subnodes:
  163. if 'compatible' in node.props:
  164. status = node.props.get('status')
  165. if (not options.include_disabled and not status or
  166. status.value != 'disabled'):
  167. node_list.append(node)
  168. phandle_prop = node.props.get('phandle')
  169. if phandle_prop:
  170. phandle = phandle_prop.GetPhandle()
  171. self._phandle_node[phandle] = node
  172. self._valid_nodes = node_list
  173. def IsPhandle(self, prop):
  174. """Check if a node contains phandles
  175. We have no reliable way of detecting whether a node uses a phandle
  176. or not. As an interim measure, use a list of known property names.
  177. Args:
  178. prop: Prop object to check
  179. Return:
  180. True if the object value contains phandles, else False
  181. """
  182. if prop.name in ['clocks']:
  183. return True
  184. return False
  185. def ScanStructs(self):
  186. """Scan the device tree building up the C structures we will use.
  187. Build a dict keyed by C struct name containing a dict of Prop
  188. object for each struct field (keyed by property name). Where the
  189. same struct appears multiple times, try to use the 'widest'
  190. property, i.e. the one with a type which can express all others.
  191. Once the widest property is determined, all other properties are
  192. updated to match that width.
  193. """
  194. structs = {}
  195. for node in self._valid_nodes:
  196. node_name = self.GetCompatName(node)
  197. fields = {}
  198. # Get a list of all the valid properties in this node.
  199. for name, prop in node.props.iteritems():
  200. if name not in PROP_IGNORE_LIST and name[0] != '#':
  201. fields[name] = copy.deepcopy(prop)
  202. # If we've seen this node_name before, update the existing struct.
  203. if node_name in structs:
  204. struct = structs[node_name]
  205. for name, prop in fields.iteritems():
  206. oldprop = struct.get(name)
  207. if oldprop:
  208. oldprop.Widen(prop)
  209. else:
  210. struct[name] = prop
  211. # Otherwise store this as a new struct.
  212. else:
  213. structs[node_name] = fields
  214. upto = 0
  215. for node in self._valid_nodes:
  216. node_name = self.GetCompatName(node)
  217. struct = structs[node_name]
  218. for name, prop in node.props.iteritems():
  219. if name not in PROP_IGNORE_LIST and name[0] != '#':
  220. prop.Widen(struct[name])
  221. upto += 1
  222. return structs
  223. def GenerateStructs(self, structs):
  224. """Generate struct defintions for the platform data
  225. This writes out the body of a header file consisting of structure
  226. definitions for node in self._valid_nodes. See the documentation in
  227. README.of-plat for more information.
  228. """
  229. self.Out('#include <stdbool.h>\n')
  230. self.Out('#include <libfdt.h>\n')
  231. # Output the struct definition
  232. for name in sorted(structs):
  233. self.Out('struct %s%s {\n' % (STRUCT_PREFIX, name));
  234. for pname in sorted(structs[name]):
  235. prop = structs[name][pname]
  236. if self.IsPhandle(prop):
  237. # For phandles, include a reference to the target
  238. self.Out('\t%s%s[%d]' % (TabTo(2, 'struct phandle_2_cell'),
  239. Conv_name_to_c(prop.name),
  240. len(prop.value) / 2))
  241. else:
  242. ptype = TYPE_NAMES[prop.type]
  243. self.Out('\t%s%s' % (TabTo(2, ptype),
  244. Conv_name_to_c(prop.name)))
  245. if type(prop.value) == list:
  246. self.Out('[%d]' % len(prop.value))
  247. self.Out(';\n')
  248. self.Out('};\n')
  249. def GenerateTables(self):
  250. """Generate device defintions for the platform data
  251. This writes out C platform data initialisation data and
  252. U_BOOT_DEVICE() declarations for each valid node. See the
  253. documentation in README.of-plat for more information.
  254. """
  255. self.Out('#include <common.h>\n')
  256. self.Out('#include <dm.h>\n')
  257. self.Out('#include <dt-structs.h>\n')
  258. self.Out('\n')
  259. node_txt_list = []
  260. for node in self._valid_nodes:
  261. struct_name = self.GetCompatName(node)
  262. var_name = Conv_name_to_c(node.name)
  263. self.Buf('static struct %s%s %s%s = {\n' %
  264. (STRUCT_PREFIX, struct_name, VAL_PREFIX, var_name))
  265. for pname, prop in node.props.iteritems():
  266. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  267. continue
  268. ptype = TYPE_NAMES[prop.type]
  269. member_name = Conv_name_to_c(prop.name)
  270. self.Buf('\t%s= ' % TabTo(3, '.' + member_name))
  271. # Special handling for lists
  272. if type(prop.value) == list:
  273. self.Buf('{')
  274. vals = []
  275. # For phandles, output a reference to the platform data
  276. # of the target node.
  277. if self.IsPhandle(prop):
  278. # Process the list as pairs of (phandle, id)
  279. it = iter(prop.value)
  280. for phandle_cell, id_cell in zip(it, it):
  281. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  282. id = fdt_util.fdt32_to_cpu(id_cell)
  283. target_node = self._phandle_node[phandle]
  284. name = Conv_name_to_c(target_node.name)
  285. vals.append('{&%s%s, %d}' % (VAL_PREFIX, name, id))
  286. else:
  287. for val in prop.value:
  288. vals.append(self.GetValue(prop.type, val))
  289. self.Buf(', '.join(vals))
  290. self.Buf('}')
  291. else:
  292. self.Buf(self.GetValue(prop.type, prop.value))
  293. self.Buf(',\n')
  294. self.Buf('};\n')
  295. # Add a device declaration
  296. self.Buf('U_BOOT_DEVICE(%s) = {\n' % var_name)
  297. self.Buf('\t.name\t\t= "%s",\n' % struct_name)
  298. self.Buf('\t.platdata\t= &%s%s,\n' % (VAL_PREFIX, var_name))
  299. self.Buf('\t.platdata_size\t= sizeof(%s%s),\n' %
  300. (VAL_PREFIX, var_name))
  301. self.Buf('};\n')
  302. self.Buf('\n')
  303. # Output phandle target nodes first, since they may be referenced
  304. # by others
  305. if 'phandle' in node.props:
  306. self.Out(''.join(self.GetBuf()))
  307. else:
  308. node_txt_list.append(self.GetBuf())
  309. # Output all the nodes which are not phandle targets themselves, but
  310. # may reference them. This avoids the need for forward declarations.
  311. for node_txt in node_txt_list:
  312. self.Out(''.join(node_txt))
  313. if __name__ != "__main__":
  314. pass
  315. parser = OptionParser()
  316. parser.add_option('-d', '--dtb-file', action='store',
  317. help='Specify the .dtb input file')
  318. parser.add_option('--include-disabled', action='store_true',
  319. help='Include disabled nodes')
  320. parser.add_option('-o', '--output', action='store', default='-',
  321. help='Select output filename')
  322. (options, args) = parser.parse_args()
  323. if not args:
  324. raise ValueError('Please specify a command: struct, platdata')
  325. plat = DtbPlatdata(options.dtb_file, options)
  326. plat.ScanDtb()
  327. plat.ScanTree()
  328. plat.SetupOutput(options.output)
  329. structs = plat.ScanStructs()
  330. for cmd in args[0].split(','):
  331. if cmd == 'struct':
  332. plat.GenerateStructs(structs)
  333. elif cmd == 'platdata':
  334. plat.GenerateTables()
  335. else:
  336. raise ValueError("Unknown command '%s': (use: struct, platdata)" % cmd)