dtb_platdata.py 19 KB

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