dtb_platdata.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. _phandle_nodes: A dict of nodes indexed by phandle number (1, 2...)
  123. _outfile: The current output file (sys.stdout or a real file)
  124. _lines: Stashed list of output lines for outputting in the future
  125. _phandle_nodes: A dict of Nodes indexed by phandle (an integer)
  126. """
  127. def __init__(self, dtb_fname, include_disabled):
  128. self._fdt = None
  129. self._dtb_fname = dtb_fname
  130. self._valid_nodes = None
  131. self._include_disabled = include_disabled
  132. self._phandle_nodes = {}
  133. self._outfile = None
  134. self._lines = []
  135. self._aliases = {}
  136. def setup_output(self, fname):
  137. """Set up the output destination
  138. Once this is done, future calls to self.out() will output to this
  139. file.
  140. Args:
  141. fname: Filename to send output to, or '-' for stdout
  142. """
  143. if fname == '-':
  144. self._outfile = sys.stdout
  145. else:
  146. self._outfile = open(fname, 'w')
  147. def out(self, line):
  148. """Output a string to the output file
  149. Args:
  150. line: String to output
  151. """
  152. self._outfile.write(line)
  153. def buf(self, line):
  154. """Buffer up a string to send later
  155. Args:
  156. line: String to add to our 'buffer' list
  157. """
  158. self._lines.append(line)
  159. def get_buf(self):
  160. """Get the contents of the output buffer, and clear it
  161. Returns:
  162. The output buffer, which is then cleared for future use
  163. """
  164. lines = self._lines
  165. self._lines = []
  166. return lines
  167. def scan_dtb(self):
  168. """Scan the device tree to obtain a tree of nodes and properties
  169. Once this is done, self._fdt.GetRoot() can be called to obtain the
  170. device tree root node, and progress from there.
  171. """
  172. self._fdt = fdt.FdtScan(self._dtb_fname)
  173. def scan_node(self, root):
  174. """Scan a node and subnodes to build a tree of node and phandle info
  175. This adds each node to self._valid_nodes and each phandle to
  176. self._phandle_nodes.
  177. Args:
  178. root: Root node for scan
  179. """
  180. for node in root.subnodes:
  181. if 'compatible' in node.props:
  182. status = node.props.get('status')
  183. if (not self._include_disabled and not status or
  184. status.value != 'disabled'):
  185. self._valid_nodes.append(node)
  186. phandle_prop = node.props.get('phandle')
  187. if phandle_prop:
  188. phandle = phandle_prop.GetPhandle()
  189. self._phandle_nodes[phandle] = node
  190. # recurse to handle any subnodes
  191. self.scan_node(node)
  192. def scan_tree(self):
  193. """Scan the device tree for useful information
  194. This fills in the following properties:
  195. _phandle_nodes: A dict of Nodes indexed by phandle (an integer)
  196. _valid_nodes: A list of nodes we wish to consider include in the
  197. platform data
  198. """
  199. self._phandle_nodes = {}
  200. self._valid_nodes = []
  201. return self.scan_node(self._fdt.GetRoot())
  202. @staticmethod
  203. def get_num_cells(node):
  204. """Get the number of cells in addresses and sizes for this node
  205. Args:
  206. node: Node to check
  207. Returns:
  208. Tuple:
  209. Number of address cells for this node
  210. Number of size cells for this node
  211. """
  212. parent = node.parent
  213. na, ns = 2, 2
  214. if parent:
  215. na_prop = parent.props.get('#address-cells')
  216. ns_prop = parent.props.get('#size-cells')
  217. if na_prop:
  218. na = fdt_util.fdt32_to_cpu(na_prop.value)
  219. if ns_prop:
  220. ns = fdt_util.fdt32_to_cpu(ns_prop.value)
  221. return na, ns
  222. def scan_reg_sizes(self):
  223. """Scan for 64-bit 'reg' properties and update the values
  224. This finds 'reg' properties with 64-bit data and converts the value to
  225. an array of 64-values. This allows it to be output in a way that the
  226. C code can read.
  227. """
  228. for node in self._valid_nodes:
  229. reg = node.props.get('reg')
  230. if not reg:
  231. continue
  232. na, ns = self.get_num_cells(node)
  233. total = na + ns
  234. if reg.type != fdt.TYPE_INT:
  235. raise ValueError("Node '%s' reg property is not an int")
  236. if len(reg.value) % total:
  237. raise ValueError("Node '%s' reg property has %d cells "
  238. 'which is not a multiple of na + ns = %d + %d)' %
  239. (node.name, len(reg.value), na, ns))
  240. reg.na = na
  241. reg.ns = ns
  242. if na != 1 or ns != 1:
  243. reg.type = fdt.TYPE_INT64
  244. i = 0
  245. new_value = []
  246. val = reg.value
  247. if not isinstance(val, list):
  248. val = [val]
  249. while i < len(val):
  250. addr = fdt_util.fdt_cells_to_cpu(val[i:], reg.na)
  251. i += na
  252. size = fdt_util.fdt_cells_to_cpu(val[i:], reg.ns)
  253. i += ns
  254. new_value += [addr, size]
  255. reg.value = new_value
  256. def scan_structs(self):
  257. """Scan the device tree building up the C structures we will use.
  258. Build a dict keyed by C struct name containing a dict of Prop
  259. object for each struct field (keyed by property name). Where the
  260. same struct appears multiple times, try to use the 'widest'
  261. property, i.e. the one with a type which can express all others.
  262. Once the widest property is determined, all other properties are
  263. updated to match that width.
  264. """
  265. structs = {}
  266. for node in self._valid_nodes:
  267. node_name, _ = get_compat_name(node)
  268. fields = {}
  269. # Get a list of all the valid properties in this node.
  270. for name, prop in node.props.items():
  271. if name not in PROP_IGNORE_LIST and name[0] != '#':
  272. fields[name] = copy.deepcopy(prop)
  273. # If we've seen this node_name before, update the existing struct.
  274. if node_name in structs:
  275. struct = structs[node_name]
  276. for name, prop in fields.items():
  277. oldprop = struct.get(name)
  278. if oldprop:
  279. oldprop.Widen(prop)
  280. else:
  281. struct[name] = prop
  282. # Otherwise store this as a new struct.
  283. else:
  284. structs[node_name] = fields
  285. upto = 0
  286. for node in self._valid_nodes:
  287. node_name, _ = get_compat_name(node)
  288. struct = structs[node_name]
  289. for name, prop in node.props.items():
  290. if name not in PROP_IGNORE_LIST and name[0] != '#':
  291. prop.Widen(struct[name])
  292. upto += 1
  293. struct_name, aliases = get_compat_name(node)
  294. for alias in aliases:
  295. self._aliases[alias] = struct_name
  296. return structs
  297. def scan_phandles(self):
  298. """Figure out what phandles each node uses
  299. We need to be careful when outputing nodes that use phandles since
  300. they must come after the declaration of the phandles in the C file.
  301. Otherwise we get a compiler error since the phandle struct is not yet
  302. declared.
  303. This function adds to each node a list of phandle nodes that the node
  304. depends on. This allows us to output things in the right order.
  305. """
  306. for node in self._valid_nodes:
  307. node.phandles = set()
  308. for pname, prop in node.props.items():
  309. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  310. continue
  311. if isinstance(prop.value, list):
  312. if is_phandle(prop):
  313. # Process the list as pairs of (phandle, id)
  314. value_it = iter(prop.value)
  315. for phandle_cell, _ in zip(value_it, value_it):
  316. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  317. target_node = self._phandle_nodes[phandle]
  318. node.phandles.add(target_node)
  319. def generate_structs(self, structs):
  320. """Generate struct defintions for the platform data
  321. This writes out the body of a header file consisting of structure
  322. definitions for node in self._valid_nodes. See the documentation in
  323. README.of-plat for more information.
  324. """
  325. self.out('#include <stdbool.h>\n')
  326. self.out('#include <libfdt.h>\n')
  327. # Output the struct definition
  328. for name in sorted(structs):
  329. self.out('struct %s%s {\n' % (STRUCT_PREFIX, name))
  330. for pname in sorted(structs[name]):
  331. prop = structs[name][pname]
  332. if is_phandle(prop):
  333. # For phandles, include a reference to the target
  334. self.out('\t%s%s[%d]' % (tab_to(2, 'struct phandle_2_cell'),
  335. conv_name_to_c(prop.name),
  336. len(prop.value) / 2))
  337. else:
  338. ptype = TYPE_NAMES[prop.type]
  339. self.out('\t%s%s' % (tab_to(2, ptype),
  340. conv_name_to_c(prop.name)))
  341. if isinstance(prop.value, list):
  342. self.out('[%d]' % len(prop.value))
  343. self.out(';\n')
  344. self.out('};\n')
  345. for alias, struct_name in self._aliases.iteritems():
  346. self.out('#define %s%s %s%s\n'% (STRUCT_PREFIX, alias,
  347. STRUCT_PREFIX, struct_name))
  348. def output_node(self, node):
  349. """Output the C code for a node
  350. Args:
  351. node: node to output
  352. """
  353. struct_name, _ = get_compat_name(node)
  354. var_name = conv_name_to_c(node.name)
  355. self.buf('static struct %s%s %s%s = {\n' %
  356. (STRUCT_PREFIX, struct_name, VAL_PREFIX, var_name))
  357. for pname, prop in node.props.items():
  358. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  359. continue
  360. member_name = conv_name_to_c(prop.name)
  361. self.buf('\t%s= ' % tab_to(3, '.' + member_name))
  362. # Special handling for lists
  363. if isinstance(prop.value, list):
  364. self.buf('{')
  365. vals = []
  366. # For phandles, output a reference to the platform data
  367. # of the target node.
  368. if is_phandle(prop):
  369. # Process the list as pairs of (phandle, id)
  370. value_it = iter(prop.value)
  371. for phandle_cell, id_cell in zip(value_it, value_it):
  372. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  373. id_num = fdt_util.fdt32_to_cpu(id_cell)
  374. target_node = self._phandle_nodes[phandle]
  375. name = conv_name_to_c(target_node.name)
  376. vals.append('{&%s%s, %d}' % (VAL_PREFIX, name, id_num))
  377. else:
  378. for val in prop.value:
  379. vals.append(get_value(prop.type, val))
  380. # Put 8 values per line to avoid very long lines.
  381. for i in xrange(0, len(vals), 8):
  382. if i:
  383. self.buf(',\n\t\t')
  384. self.buf(', '.join(vals[i:i + 8]))
  385. self.buf('}')
  386. else:
  387. self.buf(get_value(prop.type, prop.value))
  388. self.buf(',\n')
  389. self.buf('};\n')
  390. # Add a device declaration
  391. self.buf('U_BOOT_DEVICE(%s) = {\n' % var_name)
  392. self.buf('\t.name\t\t= "%s",\n' % struct_name)
  393. self.buf('\t.platdata\t= &%s%s,\n' % (VAL_PREFIX, var_name))
  394. self.buf('\t.platdata_size\t= sizeof(%s%s),\n' % (VAL_PREFIX, var_name))
  395. self.buf('};\n')
  396. self.buf('\n')
  397. self.out(''.join(self.get_buf()))
  398. def generate_tables(self):
  399. """Generate device defintions for the platform data
  400. This writes out C platform data initialisation data and
  401. U_BOOT_DEVICE() declarations for each valid node. Where a node has
  402. multiple compatible strings, a #define is used to make them equivalent.
  403. See the documentation in doc/driver-model/of-plat.txt for more
  404. information.
  405. """
  406. self.out('#include <common.h>\n')
  407. self.out('#include <dm.h>\n')
  408. self.out('#include <dt-structs.h>\n')
  409. self.out('\n')
  410. nodes_to_output = list(self._valid_nodes)
  411. # Keep outputing nodes until there is none left
  412. while nodes_to_output:
  413. node = nodes_to_output[0]
  414. # Output all the node's dependencies first
  415. for req_node in node.phandles:
  416. if req_node in nodes_to_output:
  417. self.output_node(req_node)
  418. nodes_to_output.remove(req_node)
  419. self.output_node(node)
  420. nodes_to_output.remove(node)
  421. def run_steps(args, dtb_file, include_disabled, output):
  422. """Run all the steps of the dtoc tool
  423. Args:
  424. args: List of non-option arguments provided to the problem
  425. dtb_file: Filename of dtb file to process
  426. include_disabled: True to include disabled nodes
  427. output: Name of output file
  428. """
  429. if not args:
  430. raise ValueError('Please specify a command: struct, platdata')
  431. plat = DtbPlatdata(dtb_file, include_disabled)
  432. plat.scan_dtb()
  433. plat.scan_tree()
  434. plat.scan_reg_sizes()
  435. plat.setup_output(output)
  436. structs = plat.scan_structs()
  437. plat.scan_phandles()
  438. for cmd in args[0].split(','):
  439. if cmd == 'struct':
  440. plat.generate_structs(structs)
  441. elif cmd == 'platdata':
  442. plat.generate_tables()
  443. else:
  444. raise ValueError("Unknown command '%s': (use: struct, platdata)" %
  445. cmd)