dtb_platdata.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 os
  14. import re
  15. import sys
  16. from dtoc import fdt
  17. from dtoc import fdt_util
  18. from patman import tools
  19. # When we see these properties we ignore them - i.e. do not create a structure member
  20. PROP_IGNORE_LIST = [
  21. '#address-cells',
  22. '#gpio-cells',
  23. '#size-cells',
  24. 'compatible',
  25. 'linux,phandle',
  26. "status",
  27. 'phandle',
  28. 'u-boot,dm-pre-reloc',
  29. 'u-boot,dm-tpl',
  30. 'u-boot,dm-spl',
  31. ]
  32. # C type declarations for the types we support
  33. TYPE_NAMES = {
  34. fdt.Type.INT: 'fdt32_t',
  35. fdt.Type.BYTE: 'unsigned char',
  36. fdt.Type.STRING: 'const char *',
  37. fdt.Type.BOOL: 'bool',
  38. fdt.Type.INT64: 'fdt64_t',
  39. }
  40. STRUCT_PREFIX = 'dtd_'
  41. VAL_PREFIX = 'dtv_'
  42. # This holds information about a property which includes phandles.
  43. #
  44. # max_args: integer: Maximum number or arguments that any phandle uses (int).
  45. # args: Number of args for each phandle in the property. The total number of
  46. # phandles is len(args). This is a list of integers.
  47. PhandleInfo = collections.namedtuple('PhandleInfo', ['max_args', 'args'])
  48. # Holds a single phandle link, allowing a C struct value to be assigned to point
  49. # to a device
  50. #
  51. # var_node: C variable to assign (e.g. 'dtv_mmc.clocks[0].node')
  52. # dev_name: Name of device to assign to (e.g. 'clock')
  53. PhandleLink = collections.namedtuple('PhandleLink', ['var_node', 'dev_name'])
  54. def conv_name_to_c(name):
  55. """Convert a device-tree name to a C identifier
  56. This uses multiple replace() calls instead of re.sub() since it is faster
  57. (400ms for 1m calls versus 1000ms for the 're' version).
  58. Args:
  59. name: Name to convert
  60. Return:
  61. String containing the C version of this name
  62. """
  63. new = name.replace('@', '_at_')
  64. new = new.replace('-', '_')
  65. new = new.replace(',', '_')
  66. new = new.replace('.', '_')
  67. return new
  68. def tab_to(num_tabs, line):
  69. """Append tabs to a line of text to reach a tab stop.
  70. Args:
  71. num_tabs: Tab stop to obtain (0 = column 0, 1 = column 8, etc.)
  72. line: Line of text to append to
  73. Returns:
  74. line with the correct number of tabs appeneded. If the line already
  75. extends past that tab stop then a single space is appended.
  76. """
  77. if len(line) >= num_tabs * 8:
  78. return line + ' '
  79. return line + '\t' * (num_tabs - len(line) // 8)
  80. def get_value(ftype, value):
  81. """Get a value as a C expression
  82. For integers this returns a byte-swapped (little-endian) hex string
  83. For bytes this returns a hex string, e.g. 0x12
  84. For strings this returns a literal string enclosed in quotes
  85. For booleans this return 'true'
  86. Args:
  87. type: Data type (fdt_util)
  88. value: Data value, as a string of bytes
  89. """
  90. if ftype == fdt.Type.INT:
  91. return '%#x' % fdt_util.fdt32_to_cpu(value)
  92. elif ftype == fdt.Type.BYTE:
  93. return '%#x' % tools.ToByte(value[0])
  94. elif ftype == fdt.Type.STRING:
  95. # Handle evil ACPI backslashes by adding another backslash before them.
  96. # So "\\_SB.GPO0" in the device tree effectively stays like that in C
  97. return '"%s"' % value.replace('\\', '\\\\')
  98. elif ftype == fdt.Type.BOOL:
  99. return 'true'
  100. elif ftype == fdt.Type.INT64:
  101. return '%#x' % value
  102. def get_compat_name(node):
  103. """Get the node's list of compatible string as a C identifiers
  104. Args:
  105. node: Node object to check
  106. Return:
  107. List of C identifiers for all the compatible strings
  108. """
  109. compat = node.props['compatible'].value
  110. if not isinstance(compat, list):
  111. compat = [compat]
  112. return [conv_name_to_c(c) for c in compat]
  113. class DtbPlatdata(object):
  114. """Provide a means to convert device tree binary data to platform data
  115. The output of this process is C structures which can be used in space-
  116. constrained encvironments where the ~3KB code overhead of device tree
  117. code is not affordable.
  118. Properties:
  119. _fdt: Fdt object, referencing the device tree
  120. _dtb_fname: Filename of the input device tree binary file
  121. _valid_nodes: A list of Node object with compatible strings. The list
  122. is ordered by conv_name_to_c(node.name)
  123. _include_disabled: true to include nodes marked status = "disabled"
  124. _outfile: The current output file (sys.stdout or a real file)
  125. _warning_disabled: true to disable warnings about driver names not found
  126. _lines: Stashed list of output lines for outputting in the future
  127. _drivers: List of valid driver names found in drivers/
  128. _driver_aliases: Dict that holds aliases for driver names
  129. key: Driver alias declared with
  130. U_BOOT_DRIVER_ALIAS(driver_alias, driver_name)
  131. value: Driver name declared with U_BOOT_DRIVER(driver_name)
  132. _drivers_additional: List of additional drivers to use during scanning
  133. """
  134. def __init__(self, dtb_fname, include_disabled, warning_disabled,
  135. drivers_additional=[]):
  136. self._fdt = None
  137. self._dtb_fname = dtb_fname
  138. self._valid_nodes = None
  139. self._include_disabled = include_disabled
  140. self._outfile = None
  141. self._warning_disabled = warning_disabled
  142. self._lines = []
  143. self._drivers = []
  144. self._driver_aliases = {}
  145. self._drivers_additional = drivers_additional
  146. def get_normalized_compat_name(self, node):
  147. """Get a node's normalized compat name
  148. Returns a valid driver name by retrieving node's list of compatible
  149. string as a C identifier and performing a check against _drivers
  150. and a lookup in driver_aliases printing a warning in case of failure.
  151. Args:
  152. node: Node object to check
  153. Return:
  154. Tuple:
  155. Driver name associated with the first compatible string
  156. List of C identifiers for all the other compatible strings
  157. (possibly empty)
  158. In case of no match found, the return will be the same as
  159. get_compat_name()
  160. """
  161. compat_list_c = get_compat_name(node)
  162. for compat_c in compat_list_c:
  163. if not compat_c in self._drivers:
  164. compat_c = self._driver_aliases.get(compat_c)
  165. if not compat_c:
  166. continue
  167. aliases_c = compat_list_c
  168. if compat_c in aliases_c:
  169. aliases_c.remove(compat_c)
  170. return compat_c, aliases_c
  171. if not self._warning_disabled:
  172. print('WARNING: the driver %s was not found in the driver list'
  173. % (compat_list_c[0]))
  174. return compat_list_c[0], compat_list_c[1:]
  175. def setup_output(self, fname):
  176. """Set up the output destination
  177. Once this is done, future calls to self.out() will output to this
  178. file.
  179. Args:
  180. fname: Filename to send output to, or '-' for stdout
  181. """
  182. if fname == '-':
  183. self._outfile = sys.stdout
  184. else:
  185. self._outfile = open(fname, 'w')
  186. def out(self, line):
  187. """Output a string to the output file
  188. Args:
  189. line: String to output
  190. """
  191. self._outfile.write(line)
  192. def buf(self, line):
  193. """Buffer up a string to send later
  194. Args:
  195. line: String to add to our 'buffer' list
  196. """
  197. self._lines.append(line)
  198. def get_buf(self):
  199. """Get the contents of the output buffer, and clear it
  200. Returns:
  201. The output buffer, which is then cleared for future use
  202. """
  203. lines = self._lines
  204. self._lines = []
  205. return lines
  206. def out_header(self):
  207. """Output a message indicating that this is an auto-generated file"""
  208. self.out('''/*
  209. * DO NOT MODIFY
  210. *
  211. * This file was generated by dtoc from a .dtb (device tree binary) file.
  212. */
  213. ''')
  214. def get_phandle_argc(self, prop, node_name):
  215. """Check if a node contains phandles
  216. We have no reliable way of detecting whether a node uses a phandle
  217. or not. As an interim measure, use a list of known property names.
  218. Args:
  219. prop: Prop object to check
  220. Return:
  221. Number of argument cells is this is a phandle, else None
  222. """
  223. if prop.name in ['clocks', 'cd-gpios']:
  224. if not isinstance(prop.value, list):
  225. prop.value = [prop.value]
  226. val = prop.value
  227. i = 0
  228. max_args = 0
  229. args = []
  230. while i < len(val):
  231. phandle = fdt_util.fdt32_to_cpu(val[i])
  232. # If we get to the end of the list, stop. This can happen
  233. # since some nodes have more phandles in the list than others,
  234. # but we allocate enough space for the largest list. So those
  235. # nodes with shorter lists end up with zeroes at the end.
  236. if not phandle:
  237. break
  238. target = self._fdt.phandle_to_node.get(phandle)
  239. if not target:
  240. raise ValueError("Cannot parse '%s' in node '%s'" %
  241. (prop.name, node_name))
  242. cells = None
  243. for prop_name in ['#clock-cells', '#gpio-cells']:
  244. cells = target.props.get(prop_name)
  245. if cells:
  246. break
  247. if not cells:
  248. raise ValueError("Node '%s' has no cells property" %
  249. (target.name))
  250. num_args = fdt_util.fdt32_to_cpu(cells.value)
  251. max_args = max(max_args, num_args)
  252. args.append(num_args)
  253. i += 1 + num_args
  254. return PhandleInfo(max_args, args)
  255. return None
  256. def scan_driver(self, fn):
  257. """Scan a driver file to build a list of driver names and aliases
  258. This procedure will populate self._drivers and self._driver_aliases
  259. Args
  260. fn: Driver filename to scan
  261. """
  262. with open(fn, encoding='utf-8') as fd:
  263. try:
  264. buff = fd.read()
  265. except UnicodeDecodeError:
  266. # This seems to happen on older Python versions
  267. print("Skipping file '%s' due to unicode error" % fn)
  268. return
  269. # The following re will search for driver names declared as
  270. # U_BOOT_DRIVER(driver_name)
  271. drivers = re.findall('U_BOOT_DRIVER\((.*)\)', buff)
  272. for driver in drivers:
  273. self._drivers.append(driver)
  274. # The following re will search for driver aliases declared as
  275. # U_BOOT_DRIVER_ALIAS(alias, driver_name)
  276. driver_aliases = re.findall('U_BOOT_DRIVER_ALIAS\(\s*(\w+)\s*,\s*(\w+)\s*\)',
  277. buff)
  278. for alias in driver_aliases: # pragma: no cover
  279. if len(alias) != 2:
  280. continue
  281. self._driver_aliases[alias[1]] = alias[0]
  282. def scan_drivers(self):
  283. """Scan the driver folders to build a list of driver names and aliases
  284. This procedure will populate self._drivers and self._driver_aliases
  285. """
  286. basedir = sys.argv[0].replace('tools/dtoc/dtoc', '')
  287. if basedir == '':
  288. basedir = './'
  289. for (dirpath, dirnames, filenames) in os.walk(basedir):
  290. for fn in filenames:
  291. if not fn.endswith('.c'):
  292. continue
  293. self.scan_driver(dirpath + '/' + fn)
  294. for fn in self._drivers_additional:
  295. if not isinstance(fn, str) or len(fn) == 0:
  296. continue
  297. if fn[0] == '/':
  298. self.scan_driver(fn)
  299. else:
  300. self.scan_driver(basedir + '/' + fn)
  301. def scan_dtb(self):
  302. """Scan the device tree to obtain a tree of nodes and properties
  303. Once this is done, self._fdt.GetRoot() can be called to obtain the
  304. device tree root node, and progress from there.
  305. """
  306. self._fdt = fdt.FdtScan(self._dtb_fname)
  307. def scan_node(self, root, valid_nodes):
  308. """Scan a node and subnodes to build a tree of node and phandle info
  309. This adds each node to self._valid_nodes.
  310. Args:
  311. root: Root node for scan
  312. valid_nodes: List of Node objects to add to
  313. """
  314. for node in root.subnodes:
  315. if 'compatible' in node.props:
  316. status = node.props.get('status')
  317. if (not self._include_disabled and not status or
  318. status.value != 'disabled'):
  319. valid_nodes.append(node)
  320. # recurse to handle any subnodes
  321. self.scan_node(node, valid_nodes)
  322. def scan_tree(self):
  323. """Scan the device tree for useful information
  324. This fills in the following properties:
  325. _valid_nodes: A list of nodes we wish to consider include in the
  326. platform data
  327. """
  328. valid_nodes = []
  329. self.scan_node(self._fdt.GetRoot(), valid_nodes)
  330. self._valid_nodes = sorted(valid_nodes,
  331. key=lambda x: conv_name_to_c(x.name))
  332. for idx, node in enumerate(self._valid_nodes):
  333. node.idx = idx
  334. @staticmethod
  335. def get_num_cells(node):
  336. """Get the number of cells in addresses and sizes for this node
  337. Args:
  338. node: Node to check
  339. Returns:
  340. Tuple:
  341. Number of address cells for this node
  342. Number of size cells for this node
  343. """
  344. parent = node.parent
  345. na, ns = 2, 2
  346. if parent:
  347. na_prop = parent.props.get('#address-cells')
  348. ns_prop = parent.props.get('#size-cells')
  349. if na_prop:
  350. na = fdt_util.fdt32_to_cpu(na_prop.value)
  351. if ns_prop:
  352. ns = fdt_util.fdt32_to_cpu(ns_prop.value)
  353. return na, ns
  354. def scan_reg_sizes(self):
  355. """Scan for 64-bit 'reg' properties and update the values
  356. This finds 'reg' properties with 64-bit data and converts the value to
  357. an array of 64-values. This allows it to be output in a way that the
  358. C code can read.
  359. """
  360. for node in self._valid_nodes:
  361. reg = node.props.get('reg')
  362. if not reg:
  363. continue
  364. na, ns = self.get_num_cells(node)
  365. total = na + ns
  366. if reg.type != fdt.Type.INT:
  367. raise ValueError("Node '%s' reg property is not an int" %
  368. node.name)
  369. if len(reg.value) % total:
  370. raise ValueError("Node '%s' reg property has %d cells "
  371. 'which is not a multiple of na + ns = %d + %d)' %
  372. (node.name, len(reg.value), na, ns))
  373. reg.na = na
  374. reg.ns = ns
  375. if na != 1 or ns != 1:
  376. reg.type = fdt.Type.INT64
  377. i = 0
  378. new_value = []
  379. val = reg.value
  380. if not isinstance(val, list):
  381. val = [val]
  382. while i < len(val):
  383. addr = fdt_util.fdt_cells_to_cpu(val[i:], reg.na)
  384. i += na
  385. size = fdt_util.fdt_cells_to_cpu(val[i:], reg.ns)
  386. i += ns
  387. new_value += [addr, size]
  388. reg.value = new_value
  389. def scan_structs(self):
  390. """Scan the device tree building up the C structures we will use.
  391. Build a dict keyed by C struct name containing a dict of Prop
  392. object for each struct field (keyed by property name). Where the
  393. same struct appears multiple times, try to use the 'widest'
  394. property, i.e. the one with a type which can express all others.
  395. Once the widest property is determined, all other properties are
  396. updated to match that width.
  397. Returns:
  398. dict containing structures:
  399. key (str): Node name, as a C identifier
  400. value: dict containing structure fields:
  401. key (str): Field name
  402. value: Prop object with field information
  403. """
  404. structs = collections.OrderedDict()
  405. for node in self._valid_nodes:
  406. node_name, _ = self.get_normalized_compat_name(node)
  407. fields = {}
  408. # Get a list of all the valid properties in this node.
  409. for name, prop in node.props.items():
  410. if name not in PROP_IGNORE_LIST and name[0] != '#':
  411. fields[name] = copy.deepcopy(prop)
  412. # If we've seen this node_name before, update the existing struct.
  413. if node_name in structs:
  414. struct = structs[node_name]
  415. for name, prop in fields.items():
  416. oldprop = struct.get(name)
  417. if oldprop:
  418. oldprop.Widen(prop)
  419. else:
  420. struct[name] = prop
  421. # Otherwise store this as a new struct.
  422. else:
  423. structs[node_name] = fields
  424. upto = 0
  425. for node in self._valid_nodes:
  426. node_name, _ = self.get_normalized_compat_name(node)
  427. struct = structs[node_name]
  428. for name, prop in node.props.items():
  429. if name not in PROP_IGNORE_LIST and name[0] != '#':
  430. prop.Widen(struct[name])
  431. upto += 1
  432. return structs
  433. def scan_phandles(self):
  434. """Figure out what phandles each node uses
  435. We need to be careful when outputing nodes that use phandles since
  436. they must come after the declaration of the phandles in the C file.
  437. Otherwise we get a compiler error since the phandle struct is not yet
  438. declared.
  439. This function adds to each node a list of phandle nodes that the node
  440. depends on. This allows us to output things in the right order.
  441. """
  442. for node in self._valid_nodes:
  443. node.phandles = set()
  444. for pname, prop in node.props.items():
  445. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  446. continue
  447. info = self.get_phandle_argc(prop, node.name)
  448. if info:
  449. # Process the list as pairs of (phandle, id)
  450. pos = 0
  451. for args in info.args:
  452. phandle_cell = prop.value[pos]
  453. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  454. target_node = self._fdt.phandle_to_node[phandle]
  455. node.phandles.add(target_node)
  456. pos += 1 + args
  457. def generate_structs(self, structs):
  458. """Generate struct defintions for the platform data
  459. This writes out the body of a header file consisting of structure
  460. definitions for node in self._valid_nodes. See the documentation in
  461. doc/driver-model/of-plat.rst for more information.
  462. Args:
  463. structs: dict containing structures:
  464. key (str): Node name, as a C identifier
  465. value: dict containing structure fields:
  466. key (str): Field name
  467. value: Prop object with field information
  468. """
  469. self.out_header()
  470. self.out('#include <stdbool.h>\n')
  471. self.out('#include <linux/libfdt.h>\n')
  472. # Output the struct definition
  473. for name in sorted(structs):
  474. self.out('struct %s%s {\n' % (STRUCT_PREFIX, name))
  475. for pname in sorted(structs[name]):
  476. prop = structs[name][pname]
  477. info = self.get_phandle_argc(prop, structs[name])
  478. if info:
  479. # For phandles, include a reference to the target
  480. struct_name = 'struct phandle_%d_arg' % info.max_args
  481. self.out('\t%s%s[%d]' % (tab_to(2, struct_name),
  482. conv_name_to_c(prop.name),
  483. len(info.args)))
  484. else:
  485. ptype = TYPE_NAMES[prop.type]
  486. self.out('\t%s%s' % (tab_to(2, ptype),
  487. conv_name_to_c(prop.name)))
  488. if isinstance(prop.value, list):
  489. self.out('[%d]' % len(prop.value))
  490. self.out(';\n')
  491. self.out('};\n')
  492. def output_node(self, node):
  493. """Output the C code for a node
  494. Args:
  495. node: node to output
  496. """
  497. def _output_list(node, prop):
  498. """Output the C code for a devicetree property that holds a list
  499. Args:
  500. node (fdt.Node): Node to output
  501. prop (fdt.Prop): Prop to output
  502. """
  503. self.buf('{')
  504. vals = []
  505. # For phandles, output a reference to the platform data
  506. # of the target node.
  507. info = self.get_phandle_argc(prop, node.name)
  508. if info:
  509. # Process the list as pairs of (phandle, id)
  510. pos = 0
  511. item = 0
  512. for args in info.args:
  513. phandle_cell = prop.value[pos]
  514. phandle = fdt_util.fdt32_to_cpu(phandle_cell)
  515. target_node = self._fdt.phandle_to_node[phandle]
  516. name = conv_name_to_c(target_node.name)
  517. arg_values = []
  518. for i in range(args):
  519. arg_values.append(
  520. str(fdt_util.fdt32_to_cpu(prop.value[pos + 1 + i])))
  521. pos += 1 + args
  522. vals.append('\t{%d, {%s}}' % (target_node.idx,
  523. ', '.join(arg_values)))
  524. item += 1
  525. for val in vals:
  526. self.buf('\n\t\t%s,' % val)
  527. else:
  528. for val in prop.value:
  529. vals.append(get_value(prop.type, val))
  530. # Put 8 values per line to avoid very long lines.
  531. for i in range(0, len(vals), 8):
  532. if i:
  533. self.buf(',\n\t\t')
  534. self.buf(', '.join(vals[i:i + 8]))
  535. self.buf('}')
  536. struct_name, _ = self.get_normalized_compat_name(node)
  537. var_name = conv_name_to_c(node.name)
  538. self.buf('/* Node %s index %d */\n' % (node.path, node.idx))
  539. self.buf('static struct %s%s %s%s = {\n' %
  540. (STRUCT_PREFIX, struct_name, VAL_PREFIX, var_name))
  541. for pname in sorted(node.props):
  542. prop = node.props[pname]
  543. if pname in PROP_IGNORE_LIST or pname[0] == '#':
  544. continue
  545. member_name = conv_name_to_c(prop.name)
  546. self.buf('\t%s= ' % tab_to(3, '.' + member_name))
  547. # Special handling for lists
  548. if isinstance(prop.value, list):
  549. _output_list(node, prop)
  550. else:
  551. self.buf(get_value(prop.type, prop.value))
  552. self.buf(',\n')
  553. self.buf('};\n')
  554. # Add a device declaration
  555. self.buf('U_BOOT_DEVICE(%s) = {\n' % var_name)
  556. self.buf('\t.name\t\t= "%s",\n' % struct_name)
  557. self.buf('\t.platdata\t= &%s%s,\n' % (VAL_PREFIX, var_name))
  558. self.buf('\t.platdata_size\t= sizeof(%s%s),\n' % (VAL_PREFIX, var_name))
  559. idx = -1
  560. if node.parent and node.parent in self._valid_nodes:
  561. idx = node.parent.idx
  562. self.buf('\t.parent_idx\t= %d,\n' % idx)
  563. self.buf('};\n')
  564. self.buf('\n')
  565. self.out(''.join(self.get_buf()))
  566. def generate_tables(self):
  567. """Generate device defintions for the platform data
  568. This writes out C platform data initialisation data and
  569. U_BOOT_DEVICE() declarations for each valid node. Where a node has
  570. multiple compatible strings, a #define is used to make them equivalent.
  571. See the documentation in doc/driver-model/of-plat.rst for more
  572. information.
  573. """
  574. self.out_header()
  575. self.out('/* Allow use of U_BOOT_DEVICE() in this file */\n')
  576. self.out('#define DT_PLATDATA_C\n')
  577. self.out('\n')
  578. self.out('#include <common.h>\n')
  579. self.out('#include <dm.h>\n')
  580. self.out('#include <dt-structs.h>\n')
  581. self.out('\n')
  582. nodes_to_output = list(self._valid_nodes)
  583. # Keep outputing nodes until there is none left
  584. while nodes_to_output:
  585. node = nodes_to_output[0]
  586. # Output all the node's dependencies first
  587. for req_node in node.phandles:
  588. if req_node in nodes_to_output:
  589. self.output_node(req_node)
  590. nodes_to_output.remove(req_node)
  591. self.output_node(node)
  592. nodes_to_output.remove(node)
  593. # Define dm_populate_phandle_data() which will add the linking between
  594. # nodes using DM_GET_DEVICE
  595. # dtv_dmc_at_xxx.clocks[0].node = DM_GET_DEVICE(clock_controller_at_xxx)
  596. self.buf('void dm_populate_phandle_data(void) {\n')
  597. self.buf('}\n')
  598. self.out(''.join(self.get_buf()))
  599. def run_steps(args, dtb_file, include_disabled, output, warning_disabled=False,
  600. drivers_additional=[]):
  601. """Run all the steps of the dtoc tool
  602. Args:
  603. args: List of non-option arguments provided to the problem
  604. dtb_file: Filename of dtb file to process
  605. include_disabled: True to include disabled nodes
  606. output: Name of output file
  607. """
  608. if not args:
  609. raise ValueError('Please specify a command: struct, platdata')
  610. plat = DtbPlatdata(dtb_file, include_disabled, warning_disabled, drivers_additional)
  611. plat.scan_drivers()
  612. plat.scan_dtb()
  613. plat.scan_tree()
  614. plat.scan_reg_sizes()
  615. plat.setup_output(output)
  616. structs = plat.scan_structs()
  617. plat.scan_phandles()
  618. for cmd in args[0].split(','):
  619. if cmd == 'struct':
  620. plat.generate_structs(structs)
  621. elif cmd == 'platdata':
  622. plat.generate_tables()
  623. else:
  624. raise ValueError("Unknown command '%s': (use: struct, platdata)" %
  625. cmd)