dtoc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. str = str.replace('/', '__')
  53. return str
  54. def TabTo(num_tabs, str):
  55. if len(str) >= num_tabs * 8:
  56. return str + ' '
  57. return str + '\t' * (num_tabs - len(str) // 8)
  58. class DtbPlatdata:
  59. """Provide a means to convert device tree binary data to platform data
  60. The output of this process is C structures which can be used in space-
  61. constrained encvironments where the ~3KB code overhead of device tree
  62. code is not affordable.
  63. Properties:
  64. fdt: Fdt object, referencing the device tree
  65. _dtb_fname: Filename of the input device tree binary file
  66. _valid_nodes: A list of Node object with compatible strings
  67. _options: Command-line options
  68. _phandle_node: A dict of nodes indexed by phandle number (1, 2...)
  69. _outfile: The current output file (sys.stdout or a real file)
  70. _lines: Stashed list of output lines for outputting in the future
  71. _phandle_node: A dict of Nodes indexed by phandle (an integer)
  72. """
  73. def __init__(self, dtb_fname, options):
  74. self._dtb_fname = dtb_fname
  75. self._valid_nodes = None
  76. self._options = options
  77. self._phandle_node = {}
  78. self._outfile = None
  79. self._lines = []
  80. def SetupOutput(self, fname):
  81. """Set up the output destination
  82. Once this is done, future calls to self.Out() will output to this
  83. file.
  84. Args:
  85. fname: Filename to send output to, or '-' for stdout
  86. """
  87. if fname == '-':
  88. self._outfile = sys.stdout
  89. else:
  90. self._outfile = open(fname, 'w')
  91. def Out(self, str):
  92. """Output a string to the output file
  93. Args:
  94. str: String to output
  95. """
  96. self._outfile.write(str)
  97. def Buf(self, str):
  98. """Buffer up a string to send later
  99. Args:
  100. str: String to add to our 'buffer' list
  101. """
  102. self._lines.append(str)
  103. def GetBuf(self):
  104. """Get the contents of the output buffer, and clear it
  105. Returns:
  106. The output buffer, which is then cleared for future use
  107. """
  108. lines = self._lines
  109. self._lines = []
  110. return lines
  111. def GetValue(self, type, value):
  112. """Get a value as a C expression
  113. For integers this returns a byte-swapped (little-endian) hex string
  114. For bytes this returns a hex string, e.g. 0x12
  115. For strings this returns a literal string enclosed in quotes
  116. For booleans this return 'true'
  117. Args:
  118. type: Data type (fdt_util)
  119. value: Data value, as a string of bytes
  120. """
  121. if type == fdt.TYPE_INT:
  122. return '%#x' % fdt_util.fdt32_to_cpu(value)
  123. elif type == fdt.TYPE_BYTE:
  124. return '%#x' % ord(value[0])
  125. elif type == fdt.TYPE_STRING:
  126. return '"%s"' % value
  127. elif type == fdt.TYPE_BOOL:
  128. return 'true'
  129. def GetCompatName(self, node):
  130. """Get a node's first compatible string as a C identifier
  131. Args:
  132. node: Node object to check
  133. Return:
  134. C identifier for the first compatible string
  135. """
  136. compat = node.props['compatible'].value
  137. if type(compat) == list:
  138. compat = compat[0]
  139. return Conv_name_to_c(compat)
  140. def ScanDtb(self):
  141. """Scan the device tree to obtain a tree of notes and properties
  142. Once this is done, self.fdt.GetRoot() can be called to obtain the
  143. device tree root node, and progress from there.
  144. """
  145. self.fdt = fdt_select.FdtScan(self._dtb_fname)
  146. def ScanNode(self, root):
  147. for node in root.subnodes:
  148. if 'compatible' in node.props:
  149. status = node.props.get('status')
  150. if (not options.include_disabled and not status or
  151. status.value != 'disabled'):
  152. self._valid_nodes.append(node)
  153. phandle_prop = node.props.get('phandle')
  154. if phandle_prop:
  155. phandle = phandle_prop.GetPhandle()
  156. self._phandle_node[phandle] = node
  157. # recurse to handle any subnodes
  158. self.ScanNode(node);
  159. def ScanTree(self):
  160. """Scan the device tree for useful information
  161. This fills in the following properties:
  162. _phandle_node: A dict of Nodes indexed by phandle (an integer)
  163. _valid_nodes: A list of nodes we wish to consider include in the
  164. platform data
  165. """
  166. self._phandle_node = {}
  167. self._valid_nodes = []
  168. return self.ScanNode(self.fdt.GetRoot());
  169. for node in self.fdt.GetRoot().subnodes:
  170. if 'compatible' in node.props:
  171. status = node.props.get('status')
  172. if (not options.include_disabled and not status or
  173. status.value != 'disabled'):
  174. node_list.append(node)
  175. phandle_prop = node.props.get('phandle')
  176. if phandle_prop:
  177. phandle = phandle_prop.GetPhandle()
  178. self._phandle_node[phandle] = node
  179. self._valid_nodes = node_list
  180. def IsPhandle(self, prop):
  181. """Check if a node contains phandles
  182. We have no reliable way of detecting whether a node uses a phandle
  183. or not. As an interim measure, use a list of known property names.
  184. Args:
  185. prop: Prop object to check
  186. Return:
  187. True if the object value contains phandles, else False
  188. """
  189. if prop.name in ['clocks']:
  190. return True
  191. return False
  192. def ScanStructs(self):
  193. """Scan the device tree building up the C structures we will use.
  194. Build a dict keyed by C struct name containing a dict of Prop
  195. object for each struct field (keyed by property name). Where the
  196. same struct appears multiple times, try to use the 'widest'
  197. property, i.e. the one with a type which can express all others.
  198. Once the widest property is determined, all other properties are
  199. updated to match that width.
  200. """
  201. structs = {}
  202. for node in self._valid_nodes:
  203. node_name = self.GetCompatName(node)
  204. fields = {}
  205. # Get a list of all the valid properties in this node.
  206. for name, prop in node.props.items():
  207. if name not in PROP_IGNORE_LIST and name[0] != '#':
  208. fields[name] = copy.deepcopy(prop)
  209. # If we've seen this node_name before, update the existing struct.
  210. if node_name in structs:
  211. struct = structs[node_name]
  212. for name, prop in fields.items():
  213. oldprop = struct.get(name)
  214. if oldprop:
  215. oldprop.Widen(prop)
  216. else:
  217. struct[name] = prop
  218. # Otherwise store this as a new struct.
  219. else:
  220. structs[node_name] = fields
  221. upto = 0
  222. for node in self._valid_nodes:
  223. node_name = self.GetCompatName(node)
  224. struct = structs[node_name]
  225. for name, prop in node.props.items():
  226. if name not in PROP_IGNORE_LIST and name[0] != '#':
  227. prop.Widen(struct[name])
  228. upto += 1
  229. return structs
  230. def GenerateStructs(self, structs):
  231. """Generate struct defintions for the platform data
  232. This writes out the body of a header file consisting of structure
  233. definitions for node in self._valid_nodes. See the documentation in
  234. README.of-plat for more information.
  235. """
  236. self.Out('#include <stdbool.h>\n')
  237. self.Out('#include <libfdt.h>\n')
  238. # Output the struct definition
  239. for name in sorted(structs):
  240. self.Out('struct %s%s {\n' % (STRUCT_PREFIX, name));
  241. for pname in sorted(structs[name]):
  242. prop = structs[name][pname]
  243. if self.IsPhandle(prop):
  244. # For phandles, include a reference to the target
  245. self.Out('\t%s%s[%d]' % (TabTo(2, 'struct phandle_2_cell'),
  246. Conv_name_to_c(prop.name),
  247. len(prop.value) / 2))
  248. else:
  249. ptype = TYPE_NAMES[prop.type]
  250. self.Out('\t%s%s' % (TabTo(2, ptype),
  251. Conv_name_to_c(prop.name)))
  252. if type(prop.value) == list:
  253. self.Out('[%d]' % len(prop.value))
  254. self.Out(';\n')
  255. self.Out('};\n')
  256. def OutputNode(self, node):
  257. """Output the C code for a node
  258. Args:
  259. node: node to output
  260. """
  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.items():
  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. def GenerateTables(self):
  304. """Generate device defintions for the platform data
  305. This writes out C platform data initialisation data and
  306. U_BOOT_DEVICE() declarations for each valid node. See the
  307. documentation in README.of-plat for more information.
  308. """
  309. self.Out('#include <common.h>\n')
  310. self.Out('#include <dm.h>\n')
  311. self.Out('#include <dt-structs.h>\n')
  312. self.Out('\n')
  313. node_txt_list = []
  314. for node in self._valid_nodes:
  315. self.OutputNode(node)
  316. # Output phandle target nodes first, since they may be referenced
  317. # by others
  318. if 'phandle' in node.props:
  319. self.Out(''.join(self.GetBuf()))
  320. else:
  321. node_txt_list.append(self.GetBuf())
  322. # Output all the nodes which are not phandle targets themselves, but
  323. # may reference them. This avoids the need for forward declarations.
  324. for node_txt in node_txt_list:
  325. self.Out(''.join(node_txt))
  326. if __name__ != "__main__":
  327. pass
  328. parser = OptionParser()
  329. parser.add_option('-d', '--dtb-file', action='store',
  330. help='Specify the .dtb input file')
  331. parser.add_option('--include-disabled', action='store_true',
  332. help='Include disabled nodes')
  333. parser.add_option('-o', '--output', action='store', default='-',
  334. help='Select output filename')
  335. (options, args) = parser.parse_args()
  336. if not args:
  337. raise ValueError('Please specify a command: struct, platdata')
  338. plat = DtbPlatdata(options.dtb_file, options)
  339. plat.ScanDtb()
  340. plat.ScanTree()
  341. plat.SetupOutput(options.output)
  342. structs = plat.ScanStructs()
  343. for cmd in args[0].split(','):
  344. if cmd == 'struct':
  345. plat.GenerateStructs(structs)
  346. elif cmd == 'platdata':
  347. plat.GenerateTables()
  348. else:
  349. raise ValueError("Unknown command '%s': (use: struct, platdata)" % cmd)