dtb_platdata.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2017 Google, Inc
  4. # Written by Simon Glass <sjg@chromium.org>
  5. #
  6. # SPDX-License-Identifier: GPL-2.0+
  7. #
  8. """Device tree to platform data class
  9. This supports converting device tree data to C structures definitions and
  10. static data.
  11. """
  12. import copy
  13. import sys
  14. import fdt
  15. import fdt_util
  16. # When we see these properties we ignore them - i.e. do not create a structure member
  17. PROP_IGNORE_LIST = [
  18. '#address-cells',
  19. '#gpio-cells',
  20. '#size-cells',
  21. 'compatible',
  22. 'linux,phandle',
  23. "status",
  24. 'phandle',
  25. 'u-boot,dm-pre-reloc',
  26. 'u-boot,dm-tpl',
  27. 'u-boot,dm-spl',
  28. ]
  29. # C type declarations for the tyues we support
  30. TYPE_NAMES = {
  31. fdt.TYPE_INT: 'fdt32_t',
  32. fdt.TYPE_BYTE: 'unsigned char',
  33. fdt.TYPE_STRING: 'const char *',
  34. fdt.TYPE_BOOL: 'bool',
  35. fdt.TYPE_INT64: 'fdt64_t',
  36. }
  37. STRUCT_PREFIX = 'dtd_'
  38. VAL_PREFIX = 'dtv_'
  39. def conv_name_to_c(name):
  40. """Convert a device-tree name to a C identifier
  41. This uses multiple replace() calls instead of re.sub() since it is faster
  42. (400ms for 1m calls versus 1000ms for the 're' version).
  43. Args:
  44. name: Name to convert
  45. Return:
  46. String containing the C version of this name
  47. """
  48. new = name.replace('@', '_at_')
  49. new = new.replace('-', '_')
  50. new = new.replace(',', '_')
  51. new = new.replace('.', '_')
  52. return new
  53. def tab_to(num_tabs, line):
  54. """Append tabs to a line of text to reach a tab stop.
  55. Args:
  56. num_tabs: Tab stop to obtain (0 = column 0, 1 = column 8, etc.)
  57. line: Line of text to append to
  58. Returns:
  59. line with the correct number of tabs appeneded. If the line already
  60. extends past that tab stop then a single space is appended.
  61. """
  62. if len(line) >= num_tabs * 8:
  63. return line + ' '
  64. return line + '\t' * (num_tabs - len(line) // 8)
  65. def get_value(ftype, value):
  66. """Get a value as a C expression
  67. For integers this returns a byte-swapped (little-endian) hex string
  68. For bytes this returns a hex string, e.g. 0x12
  69. For strings this returns a literal string enclosed in quotes
  70. For booleans this return 'true'
  71. Args:
  72. type: Data type (fdt_util)
  73. value: Data value, as a string of bytes
  74. """
  75. if ftype == fdt.TYPE_INT:
  76. return '%#x' % fdt_util.fdt32_to_cpu(value)
  77. elif ftype == fdt.TYPE_BYTE:
  78. return '%#x' % ord(value[0])
  79. elif ftype == fdt.TYPE_STRING:
  80. return '"%s"' % value
  81. elif ftype == fdt.TYPE_BOOL:
  82. return 'true'
  83. elif ftype == fdt.TYPE_INT64:
  84. return '%#x' % value
  85. def get_compat_name(node):
  86. """Get a node's first compatible string as a C identifier
  87. Args:
  88. node: Node object to check
  89. Return:
  90. Tuple:
  91. C identifier for the first compatible string
  92. List of C identifiers for all the other compatible strings
  93. (possibly empty)
  94. """
  95. compat = node.props['compatible'].value
  96. aliases = []
  97. if isinstance(compat, list):
  98. compat, aliases = compat[0], compat[1:]
  99. return conv_name_to_c(compat), [conv_name_to_c(a) for a in aliases]
  100. def is_phandle(prop):
  101. """Check if a node contains phandles
  102. We have no reliable way of detecting whether a node uses a phandle
  103. or not. As an interim measure, use a list of known property names.
  104. Args:
  105. prop: Prop object to check
  106. Return:
  107. True if the object value contains phandles, else False
  108. """
  109. if prop.name in ['clocks']:
  110. return True
  111. return False
  112. class DtbPlatdata(object):
  113. """Provide a means to convert device tree binary data to platform data
  114. The output of this process is C structures which can be used in space-
  115. constrained encvironments where the ~3KB code overhead of device tree
  116. code is not affordable.
  117. Properties:
  118. _fdt: Fdt object, referencing the device tree
  119. _dtb_fname: Filename of the input device tree binary file
  120. _valid_nodes: A list of Node object with compatible strings
  121. _include_disabled: true to include nodes marked status = "disabled"
  122. _outfile: The current output file (sys.stdout or a real file)
  123. _lines: Stashed list of output lines for outputting in the future
  124. """
  125. def __init__(self, dtb_fname, include_disabled):
  126. self._fdt = None
  127. self._dtb_fname = dtb_fname
  128. self._valid_nodes = None
  129. self._include_disabled = include_disabled
  130. self._outfile = None
  131. self._lines = []
  132. self._aliases = {}
  133. def setup_output(self, fname):
  134. """Set up the output destination
  135. Once this is done, future calls to self.out() will output to this
  136. file.
  137. Args:
  138. fname: Filename to send output to, or '-' for stdout
  139. """
  140. if fname == '-':
  141. self._outfile = sys.stdout
  142. else:
  143. self._outfile = open(fname, 'w')
  144. def out(self, line):
  145. """Output a string to the output file
  146. Args:
  147. line: String to output
  148. """
  149. self._outfile.write(line)
  150. def buf(self, line):
  151. """Buffer up a string to send later
  152. Args:
  153. line: String to add to our 'buffer' list
  154. """
  155. self._lines.append(line)
  156. def get_buf(self):
  157. """Get the contents of the output buffer, and clear it
  158. Returns:
  159. The output buffer, which is then cleared for future use
  160. """
  161. lines = self._lines
  162. self._lines = []
  163. return lines
  164. def scan_dtb(self):
  165. """Scan the device tree to obtain a tree of nodes and properties
  166. Once this is done, self._fdt.GetRoot() can be called to obtain the
  167. device tree root node, and progress from there.
  168. """
  169. self._fdt = fdt.FdtScan(self._dtb_fname)
  170. def scan_node(self, root):
  171. """Scan a node and subnodes to build a tree of node and phandle info
  172. This adds each node to self._valid_nodes.
  173. Args:
  174. root: Root node for scan
  175. """
  176. for node in root.subnodes:
  177. if 'compatible' in node.props:
  178. status = node.props.get('status')
  179. if (not self._include_disabled and not status or
  180. status.value != 'disabled'):
  181. self._valid_nodes.append(node)
  182. # recurse to handle any subnodes
  183. self.scan_node(node)
  184. def scan_tree(self):
  185. """Scan the device tree for useful information
  186. This fills in the following properties:
  187. _valid_nodes: A list of nodes we wish to consider include in the
  188. platform data
  189. """
  190. self._valid_nodes = []
  191. return self.scan_node(self._fdt.GetRoot())
  192. @staticmethod
  193. def get_num_cells(node):
  194. """Get the number of cells in addresses and sizes for this node
  195. Args:
  196. node: Node to check
  197. Returns:
  198. Tuple:
  199. Number of address cells for this node
  200. Number of size cells for this node
  201. """
  202. parent = node.parent
  203. na, ns = 2, 2
  204. if parent:
  205. na_prop = parent.props.get('#address-cells')
  206. ns_prop = parent.props.get('#size-cells')
  207. if na_prop:
  208. na = fdt_util.fdt32_to_cpu(na_prop.value)
  209. if ns_prop:
  210. ns = fdt_util.fdt32_to_cpu(ns_prop.value)
  211. return na, ns
  212. def scan_reg_sizes(self):
  213. """Scan for 64-bit 'reg' properties and update the values
  214. This finds 'reg' properties with 64-bit data and converts the value to
  215. an array of 64-values. This allows it to be output in a way that the
  216. C code can read.
  217. """
  218. for node in self._valid_nodes:
  219. reg = node.props.get('reg')
  220. if not reg:
  221. continue
  222. na, ns = self.get_num_cells(node)
  223. total = na + ns
  224. if reg.type != fdt.TYPE_INT:
  225. raise ValueError("Node '%s' reg property is not an int")
  226. if len(reg.value) % total:
  227. raise ValueError("Node '%s' reg property has %d cells "
  228. 'which is not a multiple of na + ns = %d + %d)' %
  229. (node.name, len(reg.value), na, ns))
  230. reg.na = na
  231. reg.ns = ns
  232. if na != 1 or ns != 1:
  233. reg.type = fdt.TYPE_INT64
  234. i = 0
  235. new_value = []
  236. val = reg.value
  237. if not isinstance(val, list):
  238. val = [val]
  239. while i < len(val):
  240. addr = fdt_util.fdt_cells_to_cpu(val[i:], reg.na)
  241. i += na
  242. size = fdt_util.fdt_cells_to_cpu(val[i:], reg.ns)
  243. i += ns
  244. new_value += [addr, size]
  245. reg.value = new_value
  246. def scan_structs(self):
  247. """Scan the device tree building up the C structures we will use.
  248. Build a dict keyed by C struct name containing a dict of Prop
  249. object for each struct field (keyed by property name). Where the
  250. same struct appears multiple times, try to use the 'widest'
  251. property, i.e. the one with a type which can express all others.
  252. Once the widest property is determined, all other properties are
  253. updated to match that width.
  254. """
  255. structs = {}
  256. for node in self._valid_nodes:
  257. node_name, _ = get_compat_name(node)
  258. fields = {}
  259. # Get a list of all the valid properties in this node.
  260. for name, prop in node.props.items():
  261. if name not in PROP_IGNORE_LIST and name[0] != '#':
  262. fields[name] = copy.deepcopy(prop)
  263. # If we've seen this node_name before, update the existing struct.
  264. if node_name in structs:
  265. struct = structs[node_name]
  266. for name, prop in fields.items():
  267. oldprop = struct.get(name)
  268. if oldprop:
  269. oldprop.Widen(prop)
  270. else:
  271. struct[name] = prop
  272. # Otherwise store this as a new struct.
  273. else:
  274. structs[node_name] = fields
  275. upto = 0
  276. for node in self._valid_nodes:
  277. node_name, _ = get_compat_name(node)
  278. struct = structs[node_name]
  279. for name, prop in node.props.items():
  280. if name not in PROP_IGNORE_LIST and name[0] != '#':
  281. prop.Widen(struct[name])
  282. upto += 1
  283. struct_name, aliases = get_compat_name(node)
  284. for alias in aliases:
  285. self._aliases[alias] = struct_name
  286. return structs
  287. def scan_phandles(self):
  288. """Figure out what phandles each node uses
  289. We need to be careful when outputing nodes that use phandles since
  290. they must come after the declaration of the phandles in the C file.
  291. Otherwise we get a compiler error since the phandle struct is not yet
  292. declared.
  293. This function adds to each node a list of phandle nodes that the node
  294. depends on. This allows us to output things in the right order.
  295. """
  296. for node in self._valid_nodes:
  297. node.phandles = set()
  298. for pname, prop in node.props.items():
  299. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  300. continue
  301. if isinstance(prop.value, list):
  302. if is_phandle(prop):
  303. # Process the list as pairs of (phandle, id)
  304. value_it = iter(prop.value)
  305. for phandle_cell, _ in zip(value_it, value_it):
  306. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  307. target_node = self._fdt.phandle_to_node[phandle]
  308. node.phandles.add(target_node)
  309. def generate_structs(self, structs):
  310. """Generate struct defintions for the platform data
  311. This writes out the body of a header file consisting of structure
  312. definitions for node in self._valid_nodes. See the documentation in
  313. README.of-plat for more information.
  314. """
  315. self.out('#include <stdbool.h>\n')
  316. self.out('#include <libfdt.h>\n')
  317. # Output the struct definition
  318. for name in sorted(structs):
  319. self.out('struct %s%s {\n' % (STRUCT_PREFIX, name))
  320. for pname in sorted(structs[name]):
  321. prop = structs[name][pname]
  322. if is_phandle(prop):
  323. # For phandles, include a reference to the target
  324. self.out('\t%s%s[%d]' % (tab_to(2, 'struct phandle_2_cell'),
  325. conv_name_to_c(prop.name),
  326. len(prop.value) / 2))
  327. else:
  328. ptype = TYPE_NAMES[prop.type]
  329. self.out('\t%s%s' % (tab_to(2, ptype),
  330. conv_name_to_c(prop.name)))
  331. if isinstance(prop.value, list):
  332. self.out('[%d]' % len(prop.value))
  333. self.out(';\n')
  334. self.out('};\n')
  335. for alias, struct_name in self._aliases.iteritems():
  336. self.out('#define %s%s %s%s\n'% (STRUCT_PREFIX, alias,
  337. STRUCT_PREFIX, struct_name))
  338. def output_node(self, node):
  339. """Output the C code for a node
  340. Args:
  341. node: node to output
  342. """
  343. struct_name, _ = get_compat_name(node)
  344. var_name = conv_name_to_c(node.name)
  345. self.buf('static struct %s%s %s%s = {\n' %
  346. (STRUCT_PREFIX, struct_name, VAL_PREFIX, var_name))
  347. for pname, prop in node.props.items():
  348. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  349. continue
  350. member_name = conv_name_to_c(prop.name)
  351. self.buf('\t%s= ' % tab_to(3, '.' + member_name))
  352. # Special handling for lists
  353. if isinstance(prop.value, list):
  354. self.buf('{')
  355. vals = []
  356. # For phandles, output a reference to the platform data
  357. # of the target node.
  358. if is_phandle(prop):
  359. # Process the list as pairs of (phandle, id)
  360. value_it = iter(prop.value)
  361. for phandle_cell, id_cell in zip(value_it, value_it):
  362. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  363. id_num = fdt_util.fdt32_to_cpu(id_cell)
  364. target_node = self._fdt.phandle_to_node[phandle]
  365. name = conv_name_to_c(target_node.name)
  366. vals.append('{&%s%s, %d}' % (VAL_PREFIX, name, id_num))
  367. else:
  368. for val in prop.value:
  369. vals.append(get_value(prop.type, val))
  370. # Put 8 values per line to avoid very long lines.
  371. for i in xrange(0, len(vals), 8):
  372. if i:
  373. self.buf(',\n\t\t')
  374. self.buf(', '.join(vals[i:i + 8]))
  375. self.buf('}')
  376. else:
  377. self.buf(get_value(prop.type, prop.value))
  378. self.buf(',\n')
  379. self.buf('};\n')
  380. # Add a device declaration
  381. self.buf('U_BOOT_DEVICE(%s) = {\n' % var_name)
  382. self.buf('\t.name\t\t= "%s",\n' % struct_name)
  383. self.buf('\t.platdata\t= &%s%s,\n' % (VAL_PREFIX, var_name))
  384. self.buf('\t.platdata_size\t= sizeof(%s%s),\n' % (VAL_PREFIX, var_name))
  385. self.buf('};\n')
  386. self.buf('\n')
  387. self.out(''.join(self.get_buf()))
  388. def generate_tables(self):
  389. """Generate device defintions for the platform data
  390. This writes out C platform data initialisation data and
  391. U_BOOT_DEVICE() declarations for each valid node. Where a node has
  392. multiple compatible strings, a #define is used to make them equivalent.
  393. See the documentation in doc/driver-model/of-plat.txt for more
  394. information.
  395. """
  396. self.out('#include <common.h>\n')
  397. self.out('#include <dm.h>\n')
  398. self.out('#include <dt-structs.h>\n')
  399. self.out('\n')
  400. nodes_to_output = list(self._valid_nodes)
  401. # Keep outputing nodes until there is none left
  402. while nodes_to_output:
  403. node = nodes_to_output[0]
  404. # Output all the node's dependencies first
  405. for req_node in node.phandles:
  406. if req_node in nodes_to_output:
  407. self.output_node(req_node)
  408. nodes_to_output.remove(req_node)
  409. self.output_node(node)
  410. nodes_to_output.remove(node)
  411. def run_steps(args, dtb_file, include_disabled, output):
  412. """Run all the steps of the dtoc tool
  413. Args:
  414. args: List of non-option arguments provided to the problem
  415. dtb_file: Filename of dtb file to process
  416. include_disabled: True to include disabled nodes
  417. output: Name of output file
  418. """
  419. if not args:
  420. raise ValueError('Please specify a command: struct, platdata')
  421. plat = DtbPlatdata(dtb_file, include_disabled)
  422. plat.scan_dtb()
  423. plat.scan_tree()
  424. plat.scan_reg_sizes()
  425. plat.setup_output(output)
  426. structs = plat.scan_structs()
  427. plat.scan_phandles()
  428. for cmd in args[0].split(','):
  429. if cmd == 'struct':
  430. plat.generate_structs(structs)
  431. elif cmd == 'platdata':
  432. plat.generate_tables()
  433. else:
  434. raise ValueError("Unknown command '%s': (use: struct, platdata)" %
  435. cmd)