dtoc.py 13 KB

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