blob: b30fe80e10fbaa8952ed5297d92a720cbf265173 [file] [log] [blame]
Martí Bolívardc85edd2020-02-28 15:26:52 -08001#!/usr/bin/env python3
2
3# Copyright (c) 2019 - 2020 Nordic Semiconductor ASA
4# Copyright (c) 2019 Linaro Limited
5# SPDX-License-Identifier: BSD-3-Clause
6
7# This script uses edtlib to generate a header file from a devicetree
8# (.dts) file. Information from binding files in YAML format is used
9# as well.
10#
11# Bindings are files that describe devicetree nodes. Devicetree nodes are
12# usually mapped to bindings via their 'compatible = "..."' property.
13#
14# See Zephyr's Devicetree user guide for details.
15#
16# Note: Do not access private (_-prefixed) identifiers from edtlib here (and
17# also note that edtlib is not meant to expose the dtlib API directly).
18# Instead, think of what API you need, and add it as a public documented API in
19# edtlib. This will keep this script simple.
20
21import argparse
Martí Bolívara3fae2f2020-03-25 14:18:27 -070022from collections import defaultdict
Martí Bolívar09858492020-12-08 09:41:49 -080023import logging
Martí Bolívardc85edd2020-02-28 15:26:52 -080024import os
25import pathlib
Martí Bolívar533f4512020-07-01 10:43:43 -070026import pickle
Martí Bolívardc85edd2020-02-28 15:26:52 -080027import re
28import sys
29
Martí Bolívar53328472021-03-26 16:18:58 -070030sys.path.append(os.path.join(os.path.dirname(__file__), 'python-devicetree',
31 'src'))
32
33from devicetree import edtlib
Martí Bolívardc85edd2020-02-28 15:26:52 -080034
Martí Bolívar9c229a42021-04-14 15:26:42 -070035# The set of binding types whose values can be iterated over with
36# DT_FOREACH_PROP_ELEM(). If you change this, make sure to update the
37# doxygen string for that macro.
38FOREACH_PROP_ELEM_TYPES = set(['string', 'array', 'uint8-array', 'string-array',
39 'phandles', 'phandle-array'])
40
Martí Bolívar09858492020-12-08 09:41:49 -080041class LogFormatter(logging.Formatter):
42 '''A log formatter that prints the level name in lower case,
43 for compatibility with earlier versions of edtlib.'''
44
45 def __init__(self):
46 super().__init__(fmt='%(levelnamelower)s: %(message)s')
47
48 def format(self, record):
49 record.levelnamelower = record.levelname.lower()
50 return super().format(record)
51
Martí Bolívardc85edd2020-02-28 15:26:52 -080052def main():
53 global header_file
Kumar Galabd973782020-05-06 20:54:29 -050054 global flash_area_num
Martí Bolívardc85edd2020-02-28 15:26:52 -080055
56 args = parse_args()
57
Martí Bolívar09858492020-12-08 09:41:49 -080058 setup_edtlib_logging()
59
Martí Bolívarf261d772021-05-18 15:09:49 -070060 if args.vendor_prefixes:
61 vendor_prefixes = edtlib.load_vendor_prefixes_txt(args.vendor_prefixes)
62 else:
63 vendor_prefixes = None
64
Martí Bolívardc85edd2020-02-28 15:26:52 -080065 try:
66 edt = edtlib.EDT(args.dts, args.bindings_dirs,
67 # Suppress this warning if it's suppressed in dtc
68 warn_reg_unit_address_mismatch=
Kumar Galabc48f1c2020-05-01 12:33:00 -050069 "-Wno-simple_bus_reg" not in args.dtc_flags,
Peter Bigot932532e2020-09-02 05:05:19 -050070 default_prop_types=True,
Martí Bolívardf5a55c2021-02-14 17:52:57 -080071 infer_binding_for_paths=["/zephyr,user"],
Martí Bolívarc4079e42021-07-30 15:43:27 -070072 werror=args.edtlib_Werror,
Martí Bolívarf261d772021-05-18 15:09:49 -070073 vendor_prefixes=vendor_prefixes)
Martí Bolívardc85edd2020-02-28 15:26:52 -080074 except edtlib.EDTError as e:
75 sys.exit(f"devicetree error: {e}")
76
Kumar Galabd973782020-05-06 20:54:29 -050077 flash_area_num = 0
78
Martí Bolívardc85edd2020-02-28 15:26:52 -080079 # Save merged DTS source, as a debugging aid
80 with open(args.dts_out, "w", encoding="utf-8") as f:
81 print(edt.dts_source, file=f)
82
Martí Bolívare96ca542020-05-07 12:07:02 -070083 # The raw index into edt.compat2nodes[compat] is used for node
84 # instance numbering within a compatible.
85 #
86 # As a way to satisfy people's intuitions about instance numbers,
87 # though, we sort this list so enabled instances come first.
88 #
89 # This might look like a hack, but it keeps drivers and
90 # applications which don't use instance numbers carefully working
91 # as expected, since e.g. instance number 0 is always the
92 # singleton instance if there's just one enabled node of a
93 # particular compatible.
94 #
95 # This doesn't violate any devicetree.h API guarantees about
96 # instance ordering, since we make no promises that instance
97 # numbers are stable across builds.
98 for compat, nodes in edt.compat2nodes.items():
99 edt.compat2nodes[compat] = sorted(
100 nodes, key=lambda node: 0 if node.status == "okay" else 1)
101
Martí Bolívar533f4512020-07-01 10:43:43 -0700102 # Create the generated header.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800103 with open(args.header_out, "w", encoding="utf-8") as header_file:
104 write_top_comment(edt)
105
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000106 # populate all z_path_id first so any children references will
107 # work correctly.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800108 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívar186bace2020-04-08 15:02:18 -0700109 node.z_path_id = node_z_path_id(node)
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000110
111 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800112 write_node_comment(node)
113
Kumar Gala270a05f2021-02-24 11:28:21 -0600114 out_comment("Node's full path:")
Martí Bolívar00ffc7e2020-12-13 12:27:04 -0800115 out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"')
116
Kumar Gala4aac9082021-02-24 10:44:07 -0600117 out_comment("Node's name with unit-address:")
118 out_dt_define(f"{node.z_path_id}_FULL_NAME",
119 f'"{escape(node.name)}"')
120
Martí Bolívar6e273432020-04-08 15:04:15 -0700121 if node.parent is not None:
122 out_comment(f"Node parent ({node.parent.path}) identifier:")
123 out_dt_define(f"{node.z_path_id}_PARENT",
124 f"DT_{node.parent.z_path_id}")
125
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000126 write_child_functions(node)
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800127 write_child_functions_status_okay(node)
Martí Bolívar305379e2020-06-08 14:59:19 -0700128 write_dep_info(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800129 write_idents_and_existence(node)
130 write_bus(node)
131 write_special_props(node)
132 write_vanilla_props(node)
133
134 write_chosen(edt)
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700135 write_global_compat_info(edt)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800136
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600137 write_device_extern_header(args.device_header_out, edt)
138
Martí Bolívar533f4512020-07-01 10:43:43 -0700139 if args.edt_pickle_out:
140 write_pickled_edt(edt, args.edt_pickle_out)
141
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600142
143def write_device_extern_header(device_header_out, edt):
144 # Generate header that will extern devicetree struct device's
145
146 with open(device_header_out, "w", encoding="utf-8") as dev_header_file:
147 print("#ifndef DEVICE_EXTERN_GEN_H", file=dev_header_file)
148 print("#define DEVICE_EXTERN_GEN_H", file=dev_header_file)
149 print("", file=dev_header_file)
150 print("#ifdef __cplusplus", file=dev_header_file)
151 print('extern "C" {', file=dev_header_file)
152 print("#endif", file=dev_header_file)
153 print("", file=dev_header_file)
154
155 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Peter Bigotf91e9fb2021-01-23 07:56:09 -0600156 print(f"extern const struct device DEVICE_DT_NAME_GET(DT_{node.z_path_id}); /* dts_ord_{node.dep_ordinal} */",
157 file=dev_header_file)
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600158
159 print("", file=dev_header_file)
160 print("#ifdef __cplusplus", file=dev_header_file)
161 print("}", file=dev_header_file)
162 print("#endif", file=dev_header_file)
163 print("", file=dev_header_file)
164 print("#endif /* DEVICE_EXTERN_GEN_H */", file=dev_header_file)
165
166
Martí Bolívar09858492020-12-08 09:41:49 -0800167def setup_edtlib_logging():
168 # The edtlib module emits logs using the standard 'logging' module.
169 # Configure it so that warnings and above are printed to stderr,
170 # using the LogFormatter class defined above to format each message.
171
172 handler = logging.StreamHandler(sys.stderr)
173 handler.setFormatter(LogFormatter())
174
175 logger = logging.getLogger('edtlib')
176 logger.setLevel(logging.WARNING)
177 logger.addHandler(handler)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800178
Martí Bolívar186bace2020-04-08 15:02:18 -0700179def node_z_path_id(node):
180 # Return the node specific bit of the node's path identifier:
181 #
182 # - the root node's path "/" has path identifier "N"
183 # - "/foo" has "N_S_foo"
184 # - "/foo/bar" has "N_S_foo_S_bar"
185 # - "/foo/bar@123" has "N_S_foo_S_bar_123"
186 #
187 # This is used throughout this file to generate macros related to
188 # the node.
189
190 components = ["N"]
191 if node.parent is not None:
192 components.extend(f"S_{str2ident(component)}" for component in
193 node.path.split("/")[1:])
194
195 return "_".join(components)
196
Martí Bolívardc85edd2020-02-28 15:26:52 -0800197def parse_args():
198 # Returns parsed command-line arguments
199
200 parser = argparse.ArgumentParser()
201 parser.add_argument("--dts", required=True, help="DTS file")
202 parser.add_argument("--dtc-flags",
203 help="'dtc' devicetree compiler flags, some of which "
204 "might be respected here")
205 parser.add_argument("--bindings-dirs", nargs='+', required=True,
206 help="directory with bindings in YAML format, "
207 "we allow multiple")
208 parser.add_argument("--header-out", required=True,
209 help="path to write header to")
210 parser.add_argument("--dts-out", required=True,
211 help="path to write merged DTS source code to (e.g. "
212 "as a debugging aid)")
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600213 parser.add_argument("--device-header-out", required=True,
214 help="path to write device struct extern header to")
Martí Bolívar533f4512020-07-01 10:43:43 -0700215 parser.add_argument("--edt-pickle-out",
216 help="path to write pickled edtlib.EDT object to")
Martí Bolívarf261d772021-05-18 15:09:49 -0700217 parser.add_argument("--vendor-prefixes",
218 help="vendor-prefixes.txt path; used for validation")
Martí Bolívarc4079e42021-07-30 15:43:27 -0700219 parser.add_argument("--edtlib-Werror", action="store_true",
220 help="if set, edtlib-specific warnings become errors. "
221 "(this does not apply to warnings shared "
222 "with dtc.)")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800223
224 return parser.parse_args()
225
226
227def write_top_comment(edt):
228 # Writes an overview comment with misc. info at the top of the header and
229 # configuration file
230
231 s = f"""\
232Generated by gen_defines.py
233
234DTS input file:
235 {edt.dts_path}
236
237Directories with bindings:
238 {", ".join(map(relativize, edt.bindings_dirs))}
239
Martí Bolívar305379e2020-06-08 14:59:19 -0700240Node dependency ordering (ordinal and path):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800241"""
242
Martí Bolívarb6db2012020-08-24 13:33:53 -0700243 for scc in edt.scc_order:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800244 if len(scc) > 1:
245 err("cycle in devicetree involving "
246 + ", ".join(node.path for node in scc))
247 s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n"
248
249 s += """
250Definitions derived from these nodes in dependency order are next,
251followed by /chosen nodes.
252"""
253
254 out_comment(s, blank_before=False)
255
256
257def write_node_comment(node):
258 # Writes a comment describing 'node' to the header and configuration file
259
260 s = f"""\
Martí Bolívarb6e6ba02020-04-08 15:09:46 -0700261Devicetree node: {node.path}
262
Martí Bolívar305379e2020-06-08 14:59:19 -0700263Node identifier: DT_{node.z_path_id}
Martí Bolívardc85edd2020-02-28 15:26:52 -0800264"""
265
266 if node.matching_compat:
Peter Bigot932532e2020-09-02 05:05:19 -0500267 if node.binding_path:
268 s += f"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800269Binding (compatible = {node.matching_compat}):
270 {relativize(node.binding_path)}
271"""
Peter Bigot932532e2020-09-02 05:05:19 -0500272 else:
273 s += f"""
274Binding (compatible = {node.matching_compat}):
275 No yaml (bindings inferred from properties)
276"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800277
Martí Bolívardc85edd2020-02-28 15:26:52 -0800278 if node.description:
Martí Bolívarf7d33f22020-10-30 17:45:27 -0700279 # We used to put descriptions in the generated file, but
280 # devicetree bindings now have pages in the HTML
281 # documentation. Let users who are accustomed to digging
282 # around in the generated file where to find the descriptions
283 # now.
284 #
285 # Keeping them here would mean that the descriptions
286 # themselves couldn't contain C multi-line comments, which is
287 # inconvenient when we want to do things like quote snippets
288 # of .dtsi files within the descriptions, or otherwise
289 # include the string "*/".
290 s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n"
291 "in the documentation.)\n")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800292
293 out_comment(s)
294
295
296def relativize(path):
297 # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE,
298 # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise,
299 # returns 'path' unchanged.
300
301 zbase = os.getenv("ZEPHYR_BASE")
302 if zbase is None:
303 return path
304
305 try:
306 return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase))
307 except ValueError:
308 # Not within ZEPHYR_BASE
309 return path
310
311
312def write_idents_and_existence(node):
313 # Writes macros related to the node's aliases, labels, etc.,
314 # as well as existence flags.
315
316 # Aliases
317 idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases]
318 # Instances
319 for compat in node.compats:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700320 instance_no = node.edt.compat2nodes[compat].index(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800321 idents.append(f"N_INST_{instance_no}_{str2ident(compat)}")
322 # Node labels
323 idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels)
324
325 out_comment("Existence and alternate IDs:")
326 out_dt_define(node.z_path_id + "_EXISTS", 1)
327
328 # Only determine maxlen if we have any idents
329 if idents:
330 maxlen = max(len("DT_" + ident) for ident in idents)
331 for ident in idents:
332 out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen)
333
334
335def write_bus(node):
336 # Macros about the node's bus controller, if there is one
337
338 bus = node.bus_node
339 if not bus:
340 return
341
342 if not bus.label:
343 err(f"missing 'label' property on bus node {bus!r}")
344
345 out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_bus}')")
346 out_dt_define(f"{node.z_path_id}_BUS_{str2ident(node.on_bus)}", 1)
347 out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}")
348
349
350def write_special_props(node):
351 # Writes required macros for special case properties, when the
352 # data cannot otherwise be obtained from write_vanilla_props()
353 # results
354
Kumar Galabd973782020-05-06 20:54:29 -0500355 global flash_area_num
356
Martí Bolívardc85edd2020-02-28 15:26:52 -0800357 out_comment("Special property macros:")
358
359 # Macros that are special to the devicetree specification
360 write_regs(node)
361 write_interrupts(node)
362 write_compatibles(node)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700363 write_status(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800364
Kumar Galabd973782020-05-06 20:54:29 -0500365 if node.parent and "fixed-partitions" in node.parent.compats:
366 macro = f"{node.z_path_id}_PARTITION_ID"
367 out_dt_define(macro, flash_area_num)
368 flash_area_num += 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800369
370def write_regs(node):
371 # reg property: edtlib knows the right #address-cells and
372 # #size-cells, and can therefore pack the register base addresses
373 # and sizes correctly
374
375 idx_vals = []
376 name_vals = []
377 path_id = node.z_path_id
378
379 if node.regs is not None:
380 idx_vals.append((f"{path_id}_REG_NUM", len(node.regs)))
381
382 for i, reg in enumerate(node.regs):
Kumar Gala4e2ad002020-04-14 14:27:20 -0500383 idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800384 if reg.addr is not None:
385 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS"
386 idx_vals.append((idx_macro,
387 f"{reg.addr} /* {hex(reg.addr)} */"))
388 if reg.name:
389 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS"
390 name_vals.append((name_macro, f"DT_{idx_macro}"))
391
392 if reg.size is not None:
393 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE"
394 idx_vals.append((idx_macro,
395 f"{reg.size} /* {hex(reg.size)} */"))
396 if reg.name:
397 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE"
398 name_vals.append((name_macro, f"DT_{idx_macro}"))
399
400 for macro, val in idx_vals:
401 out_dt_define(macro, val)
402 for macro, val in name_vals:
403 out_dt_define(macro, val)
404
405def write_interrupts(node):
406 # interrupts property: we have some hard-coded logic for interrupt
407 # mapping here.
408 #
409 # TODO: can we push map_arm_gic_irq_type() and
410 # encode_zephyr_multi_level_irq() out of Python and into C with
411 # macro magic in devicetree.h?
412
413 def map_arm_gic_irq_type(irq, irq_num):
414 # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number
415 if "type" not in irq.data:
416 err(f"Expected binding for {irq.controller!r} to have 'type' in "
417 "interrupt-cells")
418 irq_type = irq.data["type"]
419
420 if irq_type == 0: # GIC_SPI
421 return irq_num + 32
422 if irq_type == 1: # GIC_PPI
423 return irq_num + 16
424 err(f"Invalid interrupt type specified for {irq!r}")
425
426 def encode_zephyr_multi_level_irq(irq, irq_num):
427 # See doc/reference/kernel/other/interrupts.rst for details
428 # on how this encoding works
429
430 irq_ctrl = irq.controller
431 # Look for interrupt controller parent until we have none
432 while irq_ctrl.interrupts:
433 irq_num = (irq_num + 1) << 8
434 if "irq" not in irq_ctrl.interrupts[0].data:
435 err(f"Expected binding for {irq_ctrl!r} to have 'irq' in "
436 "interrupt-cells")
437 irq_num |= irq_ctrl.interrupts[0].data["irq"]
438 irq_ctrl = irq_ctrl.interrupts[0].controller
439 return irq_num
440
441 idx_vals = []
442 name_vals = []
443 path_id = node.z_path_id
444
445 if node.interrupts is not None:
446 idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts)))
447
448 for i, irq in enumerate(node.interrupts):
449 for cell_name, cell_value in irq.data.items():
450 name = str2ident(cell_name)
451
452 if cell_name == "irq":
453 if "arm,gic" in irq.controller.compats:
454 cell_value = map_arm_gic_irq_type(irq, cell_value)
455 cell_value = encode_zephyr_multi_level_irq(irq, cell_value)
456
Kumar Gala4e2ad002020-04-14 14:27:20 -0500457 idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800458 idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}"
459 idx_vals.append((idx_macro, cell_value))
460 idx_vals.append((idx_macro + "_EXISTS", 1))
461 if irq.name:
462 name_macro = \
463 f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
464 name_vals.append((name_macro, f"DT_{idx_macro}"))
465 name_vals.append((name_macro + "_EXISTS", 1))
466
467 for macro, val in idx_vals:
468 out_dt_define(macro, val)
469 for macro, val in name_vals:
470 out_dt_define(macro, val)
471
472
473def write_compatibles(node):
474 # Writes a macro for each of the node's compatibles. We don't care
475 # about whether edtlib / Zephyr's binding language recognizes
476 # them. The compatibles the node provides are what is important.
477
478 for compat in node.compats:
479 out_dt_define(
480 f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1)
481
482
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000483def write_child_functions(node):
484 # Writes macro that are helpers that will call a macro/function
485 # for each child node.
486
Kumar Gala4a5a90a2020-05-08 12:25:25 -0500487 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",
488 " ".join(f"fn(DT_{child.z_path_id})" for child in
489 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000490
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400491 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)",
492 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)" for child in
493 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000494
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800495def write_child_functions_status_okay(node):
496 # Writes macro that are helpers that will call a macro/function
497 # for each child node with status "okay".
498
499 functions = ''
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400500 functions_args = ''
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800501 for child in node.children.values():
502 if child.status == "okay":
503 functions = functions + f"fn(DT_{child.z_path_id}) "
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400504 functions_args = functions_args + f"fn(DT_{child.z_path_id}, " \
505 "__VA_ARGS__) "
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800506
507 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)", functions)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400508 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)",
509 functions_args)
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800510
511
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700512def write_status(node):
513 out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1)
514
515
Martí Bolívardc85edd2020-02-28 15:26:52 -0800516def write_vanilla_props(node):
517 # Writes macros for any and all properties defined in the
518 # "properties" section of the binding for the node.
519 #
520 # This does generate macros for special properties as well, like
521 # regs, etc. Just let that be rather than bothering to add
522 # never-ending amounts of special case code here to skip special
523 # properties. This function's macros can't conflict with
524 # write_special_props() macros, because they're in different
525 # namespaces. Special cases aren't special enough to break the rules.
526
527 macro2val = {}
528 for prop_name, prop in node.props.items():
Martí Bolívar9c229a42021-04-14 15:26:42 -0700529 prop_id = str2ident(prop_name)
530 macro = f"{node.z_path_id}_P_{prop_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800531 val = prop2value(prop)
532 if val is not None:
533 # DT_N_<node-id>_P_<prop-id>
534 macro2val[macro] = val
535
Carlo Caionef4db14f2021-05-17 17:24:27 +0200536 if prop.spec.type == 'string':
537 macro2val[macro + "_STRING_TOKEN"] = prop.val_as_token
538 macro2val[macro + "_STRING_UPPER_TOKEN"] = prop.val_as_token.upper()
539
Martí Bolívardc85edd2020-02-28 15:26:52 -0800540 if prop.enum_index is not None:
541 # DT_N_<node-id>_P_<prop-id>_ENUM_IDX
542 macro2val[macro + "_ENUM_IDX"] = prop.enum_index
Peter Bigot345da782020-12-02 09:04:27 -0600543 spec = prop.spec
544
545 if spec.enum_tokenizable:
546 as_token = prop.val_as_token
547
548 # DT_N_<node-id>_P_<prop-id>_ENUM_TOKEN
549 macro2val[macro + "_ENUM_TOKEN"] = as_token
550
551 if spec.enum_upper_tokenizable:
552 # DT_N_<node-id>_P_<prop-id>_ENUM_UPPER_TOKEN
553 macro2val[macro + "_ENUM_UPPER_TOKEN"] = as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800554
555 if "phandle" in prop.type:
556 macro2val.update(phandle_macros(prop, macro))
557 elif "array" in prop.type:
558 # DT_N_<node-id>_P_<prop-id>_IDX_<i>
Martí Bolívarffc03122020-11-12 20:27:20 -0800559 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
Martí Bolívardc85edd2020-02-28 15:26:52 -0800560 for i, subval in enumerate(prop.val):
561 if isinstance(subval, str):
562 macro2val[macro + f"_IDX_{i}"] = quote_str(subval)
563 else:
564 macro2val[macro + f"_IDX_{i}"] = subval
Martí Bolívarffc03122020-11-12 20:27:20 -0800565 macro2val[macro + f"_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800566
Martí Bolívar9c229a42021-04-14 15:26:42 -0700567 if prop.type in FOREACH_PROP_ELEM_TYPES:
568 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
569 macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
570 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
571 for i in range(len(prop.val)))
572
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400573 macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
574 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i},'
575 ' __VA_ARGS__)'
576 for i in range(len(prop.val)))
577
Martí Bolívardc85edd2020-02-28 15:26:52 -0800578 plen = prop_len(prop)
579 if plen is not None:
580 # DT_N_<node-id>_P_<prop-id>_LEN
581 macro2val[macro + "_LEN"] = plen
582
583 macro2val[f"{macro}_EXISTS"] = 1
584
585 if macro2val:
586 out_comment("Generic property macros:")
587 for macro, val in macro2val.items():
588 out_dt_define(macro, val)
589 else:
590 out_comment("(No generic property macros)")
591
592
Martí Bolívar305379e2020-06-08 14:59:19 -0700593def write_dep_info(node):
594 # Write dependency-related information about the node.
595
596 def fmt_dep_list(dep_list):
597 if dep_list:
598 # Sort the list by dependency ordinal for predictability.
599 sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
600 return "\\\n\t" + \
601 " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
602 for n in sorted_list)
603 else:
604 return "/* nothing */"
605
606 out_comment("Node's dependency ordinal:")
607 out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal)
608
609 out_comment("Ordinals for what this node depends on directly:")
610 out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS",
611 fmt_dep_list(node.depends_on))
612
613 out_comment("Ordinals for what depends directly on this node:")
614 out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS",
615 fmt_dep_list(node.required_by))
616
617
Martí Bolívardc85edd2020-02-28 15:26:52 -0800618def prop2value(prop):
619 # Gets the macro value for property 'prop', if there is
620 # a single well-defined C rvalue that it can be represented as.
621 # Returns None if there isn't one.
622
623 if prop.type == "string":
624 return quote_str(prop.val)
625
626 if prop.type == "int":
627 return prop.val
628
629 if prop.type == "boolean":
630 return 1 if prop.val else 0
631
632 if prop.type in ["array", "uint8-array"]:
633 return list2init(f"{val} /* {hex(val)} */" for val in prop.val)
634
635 if prop.type == "string-array":
636 return list2init(quote_str(val) for val in prop.val)
637
638 # phandle, phandles, phandle-array, path, compound: nothing
639 return None
640
641
642def prop_len(prop):
643 # Returns the property's length if and only if we should generate
644 # a _LEN macro for the property. Otherwise, returns None.
645 #
646 # This deliberately excludes reg and interrupts.
647 # While they have array type, their lengths as arrays are
648 # basically nonsense semantically due to #address-cells and
649 # #size-cells for "reg" and #interrupt-cells for "interrupts".
650 #
651 # We have special purpose macros for the number of register blocks
652 # / interrupt specifiers. Excluding them from this list means
653 # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer
654 # with a build error. This forces users to switch to the right
655 # macros.
656
657 if prop.type == "phandle":
658 return 1
659
660 if (prop.type in ["array", "uint8-array", "string-array",
661 "phandles", "phandle-array"] and
662 prop.name not in ["reg", "interrupts"]):
663 return len(prop.val)
664
665 return None
666
667
668def phandle_macros(prop, macro):
669 # Returns a dict of macros for phandle or phandles property 'prop'.
670 #
671 # The 'macro' argument is the N_<node-id>_P_<prop-id> bit.
672 #
673 # These are currently special because we can't serialize their
674 # values without using label properties, which we're trying to get
675 # away from needing in Zephyr. (Label properties are great for
676 # humans, but have drawbacks for code size and boot time.)
677 #
678 # The names look a bit weird to make it easier for devicetree.h
679 # to use the same macros for phandle, phandles, and phandle-array.
680
681 ret = {}
682
683 if prop.type == "phandle":
684 # A phandle is treated as a phandles with fixed length 1.
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500685 ret[f"{macro}"] = f"DT_{prop.val.z_path_id}"
686 ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800687 ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800688 ret[f"{macro}_IDX_0_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800689 elif prop.type == "phandles":
690 for i, node in enumerate(prop.val):
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500691 ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800692 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800693 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800694 elif prop.type == "phandle-array":
695 for i, entry in enumerate(prop.val):
Martí Bolívar38ede5a2020-12-17 14:12:01 -0800696 if entry is None:
697 # Unspecified element. The phandle-array at this index
698 # does not point at a ControllerAndData value, but
699 # subsequent indices in the array may.
700 ret[f"{macro}_IDX_{i}_EXISTS"] = 0
701 continue
702
Martí Bolívardc85edd2020-02-28 15:26:52 -0800703 ret.update(controller_and_data_macros(entry, i, macro))
704
705 return ret
706
707
708def controller_and_data_macros(entry, i, macro):
709 # Helper procedure used by phandle_macros().
710 #
711 # Its purpose is to write the "controller" (i.e. label property of
712 # the phandle's node) and associated data macros for a
713 # ControllerAndData.
714
715 ret = {}
716 data = entry.data
717
Martí Bolívarffc03122020-11-12 20:27:20 -0800718 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
719 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800720 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH
721 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}"
722 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL>
723 for cell, val in data.items():
724 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val
725 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1
726
727 if not entry.name:
728 return ret
729
730 name = str2ident(entry.name)
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200731 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
732 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800733 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME
734 ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name)
735 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH
736 ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}"
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200737 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS
738 ret[f"{macro}_NAME_{name}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800739 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
740 for cell, val in data.items():
741 cell_ident = str2ident(cell)
742 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
743 f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
744 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1
745
746 return ret
747
748
749def write_chosen(edt):
750 # Tree-wide information such as chosen nodes is printed here.
751
752 out_comment("Chosen nodes\n")
753 chosen = {}
754 for name, node in edt.chosen_nodes.items():
755 chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}"
756 chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1
Kumar Gala299bfd02020-03-25 15:32:58 -0500757 max_len = max(map(len, chosen), default=0)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800758 for macro, value in chosen.items():
759 out_define(macro, value, width=max_len)
760
761
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700762def write_global_compat_info(edt):
763 # Tree-wide information related to each compatible, such as number
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700764 # of instances with status "okay", is printed here.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800765
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700766 n_okay_macros = {}
767 for_each_macros = {}
768 compat2buses = defaultdict(list) # just for "okay" nodes
769 for compat, okay_nodes in edt.compat2okay.items():
770 for node in okay_nodes:
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700771 bus = node.on_bus
772 if bus is not None and bus not in compat2buses[compat]:
773 compat2buses[compat].append(bus)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800774
Martí Bolívar63d55292020-04-06 15:13:53 -0700775 ident = str2ident(compat)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700776 n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes)
Martí Bolívare7d42ff2021-08-05 15:24:50 -0700777
778 # Helpers for non-INST for-each macros that take node
779 # identifiers as arguments.
780 for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
781 " ".join(f"fn(DT_{node.z_path_id})"
782 for node in okay_nodes)
783 for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
784 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
785 for node in okay_nodes)
786
787 # Helpers for INST versions of for-each macros, which take
788 # instance numbers. We emit separate helpers for these because
789 # avoiding an intermediate node_id --> instance number
790 # conversion in the preprocessor helps to keep the macro
791 # expansions simpler. That hopefully eases debugging.
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700792 for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
793 " ".join(f"fn({edt.compat2nodes[compat].index(node)})"
794 for node in okay_nodes)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400795 for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
796 " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
797 for node in okay_nodes)
798
Kumar Galabd973782020-05-06 20:54:29 -0500799 for compat, nodes in edt.compat2nodes.items():
800 for node in nodes:
801 if compat == "fixed-partitions":
802 for child in node.children.values():
803 if "label" in child.props:
804 label = child.props["label"].val
805 macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}"
806 val = f"DT_{child.z_path_id}"
807
808 out_dt_define(macro, val)
809 out_dt_define(macro + "_EXISTS", 1)
810
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700811 out_comment('Macros for compatibles with status "okay" nodes\n')
812 for compat, okay_nodes in edt.compat2okay.items():
813 if okay_nodes:
814 out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1)
815
816 out_comment('Macros for status "okay" instances of each compatible\n')
817 for macro, value in n_okay_macros.items():
Martí Bolívar63d55292020-04-06 15:13:53 -0700818 out_define(macro, value)
819 for macro, value in for_each_macros.items():
820 out_define(macro, value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800821
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700822 out_comment('Bus information for status "okay" nodes of each compatible\n')
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700823 for compat, buses in compat2buses.items():
824 for bus in buses:
825 out_define(
826 f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800827
828def str2ident(s):
829 # Converts 's' to a form suitable for (part of) an identifier
830
831 return re.sub('[-,.@/+]', '_', s.lower())
832
833
834def list2init(l):
835 # Converts 'l', a Python list (or iterable), to a C array initializer
836
837 return "{" + ", ".join(l) + "}"
838
839
840def out_dt_define(macro, val, width=None, deprecation_msg=None):
841 # Writes "#define DT_<macro> <val>" to the header file
842 #
843 # The macro will be left-justified to 'width' characters if that
844 # is specified, and the value will follow immediately after in
845 # that case. Otherwise, this function decides how to add
846 # whitespace between 'macro' and 'val'.
847 #
848 # If a 'deprecation_msg' string is passed, the generated identifiers will
849 # generate a warning if used, via __WARN(<deprecation_msg>)).
850 #
851 # Returns the full generated macro for 'macro', with leading "DT_".
852 ret = "DT_" + macro
853 out_define(ret, val, width=width, deprecation_msg=deprecation_msg)
854 return ret
855
856
857def out_define(macro, val, width=None, deprecation_msg=None):
858 # Helper for out_dt_define(). Outputs "#define <macro> <val>",
859 # adds a deprecation message if given, and allocates whitespace
860 # unless told not to.
861
862 warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else ""
863
864 if width:
865 s = f"#define {macro.ljust(width)}{warn} {val}"
866 else:
867 s = f"#define {macro}{warn} {val}"
868
869 print(s, file=header_file)
870
871
872def out_comment(s, blank_before=True):
873 # Writes 's' as a comment to the header and configuration file. 's' is
874 # allowed to have multiple lines. blank_before=True adds a blank line
875 # before the comment.
876
877 if blank_before:
878 print(file=header_file)
879
880 if "\n" in s:
881 # Format multi-line comments like
882 #
883 # /*
884 # * first line
885 # * second line
886 # *
887 # * empty line before this line
888 # */
889 res = ["/*"]
890 for line in s.splitlines():
891 # Avoid an extra space after '*' for empty lines. They turn red in
892 # Vim if space error checking is on, which is annoying.
893 res.append(" *" if not line.strip() else " * " + line)
894 res.append(" */")
895 print("\n".join(res), file=header_file)
896 else:
897 # Format single-line comments like
898 #
899 # /* foo bar */
900 print("/* " + s + " */", file=header_file)
901
902
903def escape(s):
904 # Backslash-escapes any double quotes and backslashes in 's'
905
906 # \ must be escaped before " to avoid double escaping
907 return s.replace("\\", "\\\\").replace('"', '\\"')
908
909
910def quote_str(s):
911 # Puts quotes around 's' and escapes any double quotes and
912 # backslashes within it
913
914 return f'"{escape(s)}"'
915
916
Martí Bolívar533f4512020-07-01 10:43:43 -0700917def write_pickled_edt(edt, out_file):
918 # Writes the edt object in pickle format to out_file.
919
920 with open(out_file, 'wb') as f:
921 # Pickle protocol version 4 is the default as of Python 3.8
922 # and was introduced in 3.4, so it is both available and
923 # recommended on all versions of Python that Zephyr supports
924 # (at time of writing, Python 3.6 was Zephyr's minimum
925 # version, and 3.8 the most recent CPython release).
926 #
927 # Using a common protocol version here will hopefully avoid
928 # reproducibility issues in different Python installations.
929 pickle.dump(edt, f, protocol=4)
930
931
Martí Bolívardc85edd2020-02-28 15:26:52 -0800932def err(s):
933 raise Exception(s)
934
935
936if __name__ == "__main__":
937 main()