dtb_platdata.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. #!/usr/bin/python
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Copyright (C) 2017 Google, Inc
  5. # Written by Simon Glass <sjg@chromium.org>
  6. #
  7. """Device tree to platform data class
  8. This supports converting device tree data to C structures definitions and
  9. static data.
  10. """
  11. import collections
  12. import copy
  13. import sys
  14. import fdt
  15. import fdt_util
  16. import tools
  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' % tools.ToByte(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. if not isinstance(prop.value, list):
  178. prop.value = [prop.value]
  179. val = prop.value
  180. i = 0
  181. max_args = 0
  182. args = []
  183. while i < len(val):
  184. phandle = fdt_util.fdt32_to_cpu(val[i])
  185. # If we get to the end of the list, stop. This can happen
  186. # since some nodes have more phandles in the list than others,
  187. # but we allocate enough space for the largest list. So those
  188. # nodes with shorter lists end up with zeroes at the end.
  189. if not phandle:
  190. break
  191. target = self._fdt.phandle_to_node.get(phandle)
  192. if not target:
  193. raise ValueError("Cannot parse '%s' in node '%s'" %
  194. (prop.name, node_name))
  195. prop_name = '#clock-cells'
  196. cells = target.props.get(prop_name)
  197. if not cells:
  198. raise ValueError("Node '%s' has no '%s' property" %
  199. (target.name, prop_name))
  200. num_args = fdt_util.fdt32_to_cpu(cells.value)
  201. max_args = max(max_args, num_args)
  202. args.append(num_args)
  203. i += 1 + num_args
  204. return PhandleInfo(max_args, args)
  205. return None
  206. def scan_dtb(self):
  207. """Scan the device tree to obtain a tree of nodes and properties
  208. Once this is done, self._fdt.GetRoot() can be called to obtain the
  209. device tree root node, and progress from there.
  210. """
  211. self._fdt = fdt.FdtScan(self._dtb_fname)
  212. def scan_node(self, root):
  213. """Scan a node and subnodes to build a tree of node and phandle info
  214. This adds each node to self._valid_nodes.
  215. Args:
  216. root: Root node for scan
  217. """
  218. for node in root.subnodes:
  219. if 'compatible' in node.props:
  220. status = node.props.get('status')
  221. if (not self._include_disabled and not status or
  222. status.value != 'disabled'):
  223. self._valid_nodes.append(node)
  224. # recurse to handle any subnodes
  225. self.scan_node(node)
  226. def scan_tree(self):
  227. """Scan the device tree for useful information
  228. This fills in the following properties:
  229. _valid_nodes: A list of nodes we wish to consider include in the
  230. platform data
  231. """
  232. self._valid_nodes = []
  233. return self.scan_node(self._fdt.GetRoot())
  234. @staticmethod
  235. def get_num_cells(node):
  236. """Get the number of cells in addresses and sizes for this node
  237. Args:
  238. node: Node to check
  239. Returns:
  240. Tuple:
  241. Number of address cells for this node
  242. Number of size cells for this node
  243. """
  244. parent = node.parent
  245. na, ns = 2, 2
  246. if parent:
  247. na_prop = parent.props.get('#address-cells')
  248. ns_prop = parent.props.get('#size-cells')
  249. if na_prop:
  250. na = fdt_util.fdt32_to_cpu(na_prop.value)
  251. if ns_prop:
  252. ns = fdt_util.fdt32_to_cpu(ns_prop.value)
  253. return na, ns
  254. def scan_reg_sizes(self):
  255. """Scan for 64-bit 'reg' properties and update the values
  256. This finds 'reg' properties with 64-bit data and converts the value to
  257. an array of 64-values. This allows it to be output in a way that the
  258. C code can read.
  259. """
  260. for node in self._valid_nodes:
  261. reg = node.props.get('reg')
  262. if not reg:
  263. continue
  264. na, ns = self.get_num_cells(node)
  265. total = na + ns
  266. if reg.type != fdt.TYPE_INT:
  267. raise ValueError("Node '%s' reg property is not an int" %
  268. node.name)
  269. if len(reg.value) % total:
  270. raise ValueError("Node '%s' reg property has %d cells "
  271. 'which is not a multiple of na + ns = %d + %d)' %
  272. (node.name, len(reg.value), na, ns))
  273. reg.na = na
  274. reg.ns = ns
  275. if na != 1 or ns != 1:
  276. reg.type = fdt.TYPE_INT64
  277. i = 0
  278. new_value = []
  279. val = reg.value
  280. if not isinstance(val, list):
  281. val = [val]
  282. while i < len(val):
  283. addr = fdt_util.fdt_cells_to_cpu(val[i:], reg.na)
  284. i += na
  285. size = fdt_util.fdt_cells_to_cpu(val[i:], reg.ns)
  286. i += ns
  287. new_value += [addr, size]
  288. reg.value = new_value
  289. def scan_structs(self):
  290. """Scan the device tree building up the C structures we will use.
  291. Build a dict keyed by C struct name containing a dict of Prop
  292. object for each struct field (keyed by property name). Where the
  293. same struct appears multiple times, try to use the 'widest'
  294. property, i.e. the one with a type which can express all others.
  295. Once the widest property is determined, all other properties are
  296. updated to match that width.
  297. """
  298. structs = {}
  299. for node in self._valid_nodes:
  300. node_name, _ = get_compat_name(node)
  301. fields = {}
  302. # Get a list of all the valid properties in this node.
  303. for name, prop in node.props.items():
  304. if name not in PROP_IGNORE_LIST and name[0] != '#':
  305. fields[name] = copy.deepcopy(prop)
  306. # If we've seen this node_name before, update the existing struct.
  307. if node_name in structs:
  308. struct = structs[node_name]
  309. for name, prop in fields.items():
  310. oldprop = struct.get(name)
  311. if oldprop:
  312. oldprop.Widen(prop)
  313. else:
  314. struct[name] = prop
  315. # Otherwise store this as a new struct.
  316. else:
  317. structs[node_name] = fields
  318. upto = 0
  319. for node in self._valid_nodes:
  320. node_name, _ = get_compat_name(node)
  321. struct = structs[node_name]
  322. for name, prop in node.props.items():
  323. if name not in PROP_IGNORE_LIST and name[0] != '#':
  324. prop.Widen(struct[name])
  325. upto += 1
  326. struct_name, aliases = get_compat_name(node)
  327. for alias in aliases:
  328. self._aliases[alias] = struct_name
  329. return structs
  330. def scan_phandles(self):
  331. """Figure out what phandles each node uses
  332. We need to be careful when outputing nodes that use phandles since
  333. they must come after the declaration of the phandles in the C file.
  334. Otherwise we get a compiler error since the phandle struct is not yet
  335. declared.
  336. This function adds to each node a list of phandle nodes that the node
  337. depends on. This allows us to output things in the right order.
  338. """
  339. for node in self._valid_nodes:
  340. node.phandles = set()
  341. for pname, prop in node.props.items():
  342. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  343. continue
  344. info = self.get_phandle_argc(prop, node.name)
  345. if info:
  346. # Process the list as pairs of (phandle, id)
  347. pos = 0
  348. for args in info.args:
  349. phandle_cell = prop.value[pos]
  350. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  351. target_node = self._fdt.phandle_to_node[phandle]
  352. node.phandles.add(target_node)
  353. pos += 1 + args
  354. def generate_structs(self, structs):
  355. """Generate struct defintions for the platform data
  356. This writes out the body of a header file consisting of structure
  357. definitions for node in self._valid_nodes. See the documentation in
  358. README.of-plat for more information.
  359. """
  360. self.out_header()
  361. self.out('#include <stdbool.h>\n')
  362. self.out('#include <linux/libfdt.h>\n')
  363. # Output the struct definition
  364. for name in sorted(structs):
  365. self.out('struct %s%s {\n' % (STRUCT_PREFIX, name))
  366. for pname in sorted(structs[name]):
  367. prop = structs[name][pname]
  368. info = self.get_phandle_argc(prop, structs[name])
  369. if info:
  370. # For phandles, include a reference to the target
  371. struct_name = 'struct phandle_%d_arg' % info.max_args
  372. self.out('\t%s%s[%d]' % (tab_to(2, struct_name),
  373. conv_name_to_c(prop.name),
  374. len(info.args)))
  375. else:
  376. ptype = TYPE_NAMES[prop.type]
  377. self.out('\t%s%s' % (tab_to(2, ptype),
  378. conv_name_to_c(prop.name)))
  379. if isinstance(prop.value, list):
  380. self.out('[%d]' % len(prop.value))
  381. self.out(';\n')
  382. self.out('};\n')
  383. for alias, struct_name in self._aliases.items():
  384. if alias not in sorted(structs):
  385. self.out('#define %s%s %s%s\n'% (STRUCT_PREFIX, alias,
  386. STRUCT_PREFIX, struct_name))
  387. def output_node(self, node):
  388. """Output the C code for a node
  389. Args:
  390. node: node to output
  391. """
  392. struct_name, _ = get_compat_name(node)
  393. var_name = conv_name_to_c(node.name)
  394. self.buf('static const struct %s%s %s%s = {\n' %
  395. (STRUCT_PREFIX, struct_name, VAL_PREFIX, var_name))
  396. for pname in sorted(node.props):
  397. prop = node.props[pname]
  398. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  399. continue
  400. member_name = conv_name_to_c(prop.name)
  401. self.buf('\t%s= ' % tab_to(3, '.' + member_name))
  402. # Special handling for lists
  403. if isinstance(prop.value, list):
  404. self.buf('{')
  405. vals = []
  406. # For phandles, output a reference to the platform data
  407. # of the target node.
  408. info = self.get_phandle_argc(prop, node.name)
  409. if info:
  410. # Process the list as pairs of (phandle, id)
  411. pos = 0
  412. for args in info.args:
  413. phandle_cell = prop.value[pos]
  414. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  415. target_node = self._fdt.phandle_to_node[phandle]
  416. name = conv_name_to_c(target_node.name)
  417. arg_values = []
  418. for i in range(args):
  419. arg_values.append(str(fdt_util.fdt32_to_cpu(prop.value[pos + 1 + i])))
  420. pos += 1 + args
  421. vals.append('\t{&%s%s, {%s}}' % (VAL_PREFIX, name,
  422. ', '.join(arg_values)))
  423. for val in vals:
  424. self.buf('\n\t\t%s,' % val)
  425. else:
  426. for val in prop.value:
  427. vals.append(get_value(prop.type, val))
  428. # Put 8 values per line to avoid very long lines.
  429. for i in range(0, len(vals), 8):
  430. if i:
  431. self.buf(',\n\t\t')
  432. self.buf(', '.join(vals[i:i + 8]))
  433. self.buf('}')
  434. else:
  435. self.buf(get_value(prop.type, prop.value))
  436. self.buf(',\n')
  437. self.buf('};\n')
  438. # Add a device declaration
  439. self.buf('U_BOOT_DEVICE(%s) = {\n' % var_name)
  440. self.buf('\t.name\t\t= "%s",\n' % struct_name)
  441. self.buf('\t.platdata\t= &%s%s,\n' % (VAL_PREFIX, var_name))
  442. self.buf('\t.platdata_size\t= sizeof(%s%s),\n' % (VAL_PREFIX, var_name))
  443. self.buf('};\n')
  444. self.buf('\n')
  445. self.out(''.join(self.get_buf()))
  446. def generate_tables(self):
  447. """Generate device defintions for the platform data
  448. This writes out C platform data initialisation data and
  449. U_BOOT_DEVICE() declarations for each valid node. Where a node has
  450. multiple compatible strings, a #define is used to make them equivalent.
  451. See the documentation in doc/driver-model/of-plat.txt for more
  452. information.
  453. """
  454. self.out_header()
  455. self.out('#include <common.h>\n')
  456. self.out('#include <dm.h>\n')
  457. self.out('#include <dt-structs.h>\n')
  458. self.out('\n')
  459. nodes_to_output = list(self._valid_nodes)
  460. # Keep outputing nodes until there is none left
  461. while nodes_to_output:
  462. node = nodes_to_output[0]
  463. # Output all the node's dependencies first
  464. for req_node in node.phandles:
  465. if req_node in nodes_to_output:
  466. self.output_node(req_node)
  467. nodes_to_output.remove(req_node)
  468. self.output_node(node)
  469. nodes_to_output.remove(node)
  470. def run_steps(args, dtb_file, include_disabled, output):
  471. """Run all the steps of the dtoc tool
  472. Args:
  473. args: List of non-option arguments provided to the problem
  474. dtb_file: Filename of dtb file to process
  475. include_disabled: True to include disabled nodes
  476. output: Name of output file
  477. """
  478. if not args:
  479. raise ValueError('Please specify a command: struct, platdata')
  480. plat = DtbPlatdata(dtb_file, include_disabled)
  481. plat.scan_dtb()
  482. plat.scan_tree()
  483. plat.scan_reg_sizes()
  484. plat.setup_output(output)
  485. structs = plat.scan_structs()
  486. plat.scan_phandles()
  487. for cmd in args[0].split(','):
  488. if cmd == 'struct':
  489. plat.generate_structs(structs)
  490. elif cmd == 'platdata':
  491. plat.generate_tables()
  492. else:
  493. raise ValueError("Unknown command '%s': (use: struct, platdata)" %
  494. cmd)