dtb_platdata.py 20 KB

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