dtb_platdata.py 31 KB

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