dtoc.py 13 KB

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