blob: 9184af4fef65eb707af7d35b9b1ebc0ac9ed4b45 [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
Jordan Yates8e4107f2022-04-30 21:13:52 +100030sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'python-devicetree',
31 'src'))
Martí Bolívar53328472021-03-26 16:18:58 -070032
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ívar85837e12021-08-19 11:09:05 -070060 vendor_prefixes = {}
61 for prefixes_file in args.vendor_prefixes:
62 vendor_prefixes.update(edtlib.load_vendor_prefixes_txt(prefixes_file))
Martí Bolívarf261d772021-05-18 15:09:49 -070063
Martí Bolívardc85edd2020-02-28 15:26:52 -080064 try:
65 edt = edtlib.EDT(args.dts, args.bindings_dirs,
66 # Suppress this warning if it's suppressed in dtc
67 warn_reg_unit_address_mismatch=
Kumar Galabc48f1c2020-05-01 12:33:00 -050068 "-Wno-simple_bus_reg" not in args.dtc_flags,
Peter Bigot932532e2020-09-02 05:05:19 -050069 default_prop_types=True,
Martí Bolívardf5a55c2021-02-14 17:52:57 -080070 infer_binding_for_paths=["/zephyr,user"],
Martí Bolívarc4079e42021-07-30 15:43:27 -070071 werror=args.edtlib_Werror,
Martí Bolívarf261d772021-05-18 15:09:49 -070072 vendor_prefixes=vendor_prefixes)
Martí Bolívardc85edd2020-02-28 15:26:52 -080073 except edtlib.EDTError as e:
74 sys.exit(f"devicetree error: {e}")
75
Kumar Galabd973782020-05-06 20:54:29 -050076 flash_area_num = 0
77
Martí Bolívardc85edd2020-02-28 15:26:52 -080078 # Save merged DTS source, as a debugging aid
79 with open(args.dts_out, "w", encoding="utf-8") as f:
80 print(edt.dts_source, file=f)
81
Martí Bolívare96ca542020-05-07 12:07:02 -070082 # The raw index into edt.compat2nodes[compat] is used for node
83 # instance numbering within a compatible.
84 #
85 # As a way to satisfy people's intuitions about instance numbers,
86 # though, we sort this list so enabled instances come first.
87 #
88 # This might look like a hack, but it keeps drivers and
89 # applications which don't use instance numbers carefully working
90 # as expected, since e.g. instance number 0 is always the
91 # singleton instance if there's just one enabled node of a
92 # particular compatible.
93 #
94 # This doesn't violate any devicetree.h API guarantees about
95 # instance ordering, since we make no promises that instance
96 # numbers are stable across builds.
97 for compat, nodes in edt.compat2nodes.items():
98 edt.compat2nodes[compat] = sorted(
99 nodes, key=lambda node: 0 if node.status == "okay" else 1)
100
Martí Bolívar533f4512020-07-01 10:43:43 -0700101 # Create the generated header.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800102 with open(args.header_out, "w", encoding="utf-8") as header_file:
103 write_top_comment(edt)
104
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +0200105 write_utils()
106
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000107 # populate all z_path_id first so any children references will
108 # work correctly.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800109 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívar186bace2020-04-08 15:02:18 -0700110 node.z_path_id = node_z_path_id(node)
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000111
Jordan Yates9c98d4f2021-07-28 20:01:16 +1000112 # Check to see if we have duplicate "zephyr,memory-region" property values.
113 regions = dict()
114 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
115 if 'zephyr,memory-region' in node.props:
116 region = node.props['zephyr,memory-region'].val
117 if region in regions:
118 sys.exit(f"ERROR: Duplicate 'zephyr,memory-region' ({region}) properties "
119 f"between {regions[region].path} and {node.path}")
120 regions[region] = node
121
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000122 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800123 write_node_comment(node)
124
Kumar Gala270a05f2021-02-24 11:28:21 -0600125 out_comment("Node's full path:")
Martí Bolívar00ffc7e2020-12-13 12:27:04 -0800126 out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"')
127
Kumar Gala4aac9082021-02-24 10:44:07 -0600128 out_comment("Node's name with unit-address:")
129 out_dt_define(f"{node.z_path_id}_FULL_NAME",
130 f'"{escape(node.name)}"')
131
Martí Bolívar6e273432020-04-08 15:04:15 -0700132 if node.parent is not None:
133 out_comment(f"Node parent ({node.parent.path}) identifier:")
134 out_dt_define(f"{node.z_path_id}_PARENT",
135 f"DT_{node.parent.z_path_id}")
136
Martí Bolívar50f9b3c2022-03-23 13:41:09 -0700137 out_comment(f"Node's index in its parent's list of children:")
138 out_dt_define(f"{node.z_path_id}_CHILD_IDX",
139 node.parent.child_index(node))
140
Martí Bolívar355cc012022-03-23 13:26:24 -0700141 write_children(node)
Martí Bolívar305379e2020-06-08 14:59:19 -0700142 write_dep_info(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800143 write_idents_and_existence(node)
144 write_bus(node)
145 write_special_props(node)
146 write_vanilla_props(node)
147
148 write_chosen(edt)
Martí Bolívar190197e2022-07-20 13:10:33 -0700149 write_global_macros(edt)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800150
Martí Bolívar533f4512020-07-01 10:43:43 -0700151 if args.edt_pickle_out:
152 write_pickled_edt(edt, args.edt_pickle_out)
153
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600154
Martí Bolívar09858492020-12-08 09:41:49 -0800155def setup_edtlib_logging():
156 # The edtlib module emits logs using the standard 'logging' module.
157 # Configure it so that warnings and above are printed to stderr,
158 # using the LogFormatter class defined above to format each message.
159
160 handler = logging.StreamHandler(sys.stderr)
161 handler.setFormatter(LogFormatter())
162
163 logger = logging.getLogger('edtlib')
164 logger.setLevel(logging.WARNING)
165 logger.addHandler(handler)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800166
Martí Bolívar186bace2020-04-08 15:02:18 -0700167def node_z_path_id(node):
168 # Return the node specific bit of the node's path identifier:
169 #
170 # - the root node's path "/" has path identifier "N"
171 # - "/foo" has "N_S_foo"
172 # - "/foo/bar" has "N_S_foo_S_bar"
173 # - "/foo/bar@123" has "N_S_foo_S_bar_123"
174 #
175 # This is used throughout this file to generate macros related to
176 # the node.
177
178 components = ["N"]
179 if node.parent is not None:
180 components.extend(f"S_{str2ident(component)}" for component in
181 node.path.split("/")[1:])
182
183 return "_".join(components)
184
Martí Bolívardc85edd2020-02-28 15:26:52 -0800185def parse_args():
186 # Returns parsed command-line arguments
187
188 parser = argparse.ArgumentParser()
189 parser.add_argument("--dts", required=True, help="DTS file")
190 parser.add_argument("--dtc-flags",
191 help="'dtc' devicetree compiler flags, some of which "
192 "might be respected here")
193 parser.add_argument("--bindings-dirs", nargs='+', required=True,
194 help="directory with bindings in YAML format, "
195 "we allow multiple")
196 parser.add_argument("--header-out", required=True,
197 help="path to write header to")
198 parser.add_argument("--dts-out", required=True,
199 help="path to write merged DTS source code to (e.g. "
200 "as a debugging aid)")
Martí Bolívar533f4512020-07-01 10:43:43 -0700201 parser.add_argument("--edt-pickle-out",
202 help="path to write pickled edtlib.EDT object to")
Martí Bolívar85837e12021-08-19 11:09:05 -0700203 parser.add_argument("--vendor-prefixes", action='append', default=[],
204 help="vendor-prefixes.txt path; used for validation; "
205 "may be given multiple times")
Martí Bolívarc4079e42021-07-30 15:43:27 -0700206 parser.add_argument("--edtlib-Werror", action="store_true",
207 help="if set, edtlib-specific warnings become errors. "
208 "(this does not apply to warnings shared "
209 "with dtc.)")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800210
211 return parser.parse_args()
212
213
214def write_top_comment(edt):
215 # Writes an overview comment with misc. info at the top of the header and
216 # configuration file
217
218 s = f"""\
219Generated by gen_defines.py
220
221DTS input file:
222 {edt.dts_path}
223
224Directories with bindings:
225 {", ".join(map(relativize, edt.bindings_dirs))}
226
Martí Bolívar305379e2020-06-08 14:59:19 -0700227Node dependency ordering (ordinal and path):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800228"""
229
Martí Bolívarb6db2012020-08-24 13:33:53 -0700230 for scc in edt.scc_order:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800231 if len(scc) > 1:
232 err("cycle in devicetree involving "
233 + ", ".join(node.path for node in scc))
234 s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n"
235
236 s += """
237Definitions derived from these nodes in dependency order are next,
238followed by /chosen nodes.
239"""
240
241 out_comment(s, blank_before=False)
242
243
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +0200244def write_utils():
245 # Writes utility macros
246
247 out_comment("Used to remove brackets from around a single argument")
248 out_define("DT_DEBRACKET_INTERNAL(...)", "__VA_ARGS__")
249
250
Martí Bolívardc85edd2020-02-28 15:26:52 -0800251def write_node_comment(node):
252 # Writes a comment describing 'node' to the header and configuration file
253
254 s = f"""\
Martí Bolívarb6e6ba02020-04-08 15:09:46 -0700255Devicetree node: {node.path}
256
Martí Bolívar305379e2020-06-08 14:59:19 -0700257Node identifier: DT_{node.z_path_id}
Martí Bolívardc85edd2020-02-28 15:26:52 -0800258"""
259
260 if node.matching_compat:
Peter Bigot932532e2020-09-02 05:05:19 -0500261 if node.binding_path:
262 s += f"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800263Binding (compatible = {node.matching_compat}):
264 {relativize(node.binding_path)}
265"""
Peter Bigot932532e2020-09-02 05:05:19 -0500266 else:
267 s += f"""
268Binding (compatible = {node.matching_compat}):
269 No yaml (bindings inferred from properties)
270"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800271
Martí Bolívardc85edd2020-02-28 15:26:52 -0800272 if node.description:
Martí Bolívarf7d33f22020-10-30 17:45:27 -0700273 # We used to put descriptions in the generated file, but
274 # devicetree bindings now have pages in the HTML
275 # documentation. Let users who are accustomed to digging
276 # around in the generated file where to find the descriptions
277 # now.
278 #
279 # Keeping them here would mean that the descriptions
280 # themselves couldn't contain C multi-line comments, which is
281 # inconvenient when we want to do things like quote snippets
282 # of .dtsi files within the descriptions, or otherwise
283 # include the string "*/".
284 s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n"
285 "in the documentation.)\n")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800286
287 out_comment(s)
288
289
290def relativize(path):
291 # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE,
292 # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise,
293 # returns 'path' unchanged.
294
295 zbase = os.getenv("ZEPHYR_BASE")
296 if zbase is None:
297 return path
298
299 try:
300 return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase))
301 except ValueError:
302 # Not within ZEPHYR_BASE
303 return path
304
305
306def write_idents_and_existence(node):
307 # Writes macros related to the node's aliases, labels, etc.,
308 # as well as existence flags.
309
310 # Aliases
311 idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases]
312 # Instances
313 for compat in node.compats:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700314 instance_no = node.edt.compat2nodes[compat].index(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800315 idents.append(f"N_INST_{instance_no}_{str2ident(compat)}")
316 # Node labels
317 idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels)
318
319 out_comment("Existence and alternate IDs:")
320 out_dt_define(node.z_path_id + "_EXISTS", 1)
321
322 # Only determine maxlen if we have any idents
323 if idents:
324 maxlen = max(len("DT_" + ident) for ident in idents)
325 for ident in idents:
326 out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen)
327
328
329def write_bus(node):
330 # Macros about the node's bus controller, if there is one
331
332 bus = node.bus_node
333 if not bus:
334 return
335
Daniel Leung418c9152022-08-26 10:52:32 -0700336 out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_buses}')")
337
338 for one_bus in node.on_buses:
339 out_dt_define(f"{node.z_path_id}_BUS_{str2ident(one_bus)}", 1)
340
Martí Bolívardc85edd2020-02-28 15:26:52 -0800341 out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}")
342
343
344def write_special_props(node):
345 # Writes required macros for special case properties, when the
346 # data cannot otherwise be obtained from write_vanilla_props()
347 # results
348
Martí Bolívardc85edd2020-02-28 15:26:52 -0800349 # Macros that are special to the devicetree specification
Martí Bolívar7f69a032021-08-11 15:14:51 -0700350 out_comment("Macros for properties that are special in the specification:")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800351 write_regs(node)
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200352 write_ranges(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800353 write_interrupts(node)
354 write_compatibles(node)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700355 write_status(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800356
Martí Bolívar7f69a032021-08-11 15:14:51 -0700357 # Macros that are special to bindings inherited from Linux, which
358 # we can't capture with the current bindings language.
Martí Bolívar9df04932021-08-11 15:43:24 -0700359 write_pinctrls(node)
Martí Bolívar7f69a032021-08-11 15:14:51 -0700360 write_fixed_partitions(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800361
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200362def write_ranges(node):
363 # ranges property: edtlib knows the right #address-cells and
364 # #size-cells of parent and child, and can therefore pack the
365 # child & parent addresses and sizes correctly
366
367 idx_vals = []
368 path_id = node.z_path_id
369
370 if node.ranges is not None:
371 idx_vals.append((f"{path_id}_RANGES_NUM", len(node.ranges)))
372
373 for i,range in enumerate(node.ranges):
374 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_EXISTS", 1))
375
Daniel Leung418c9152022-08-26 10:52:32 -0700376 if "pcie" in node.buses:
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200377 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS_EXISTS", 1))
378 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS"
379 idx_value = range.child_bus_addr >> ((range.child_bus_cells - 1) * 32)
380 idx_vals.append((idx_macro,
381 f"{idx_value} /* {hex(idx_value)} */"))
382 if range.child_bus_addr is not None:
383 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_ADDRESS"
Daniel Leung418c9152022-08-26 10:52:32 -0700384 if "pcie" in node.buses:
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200385 idx_value = range.child_bus_addr & ((1 << (range.child_bus_cells - 1) * 32) - 1)
386 else:
387 idx_value = range.child_bus_addr
388 idx_vals.append((idx_macro,
389 f"{idx_value} /* {hex(idx_value)} */"))
390 if range.parent_bus_addr is not None:
391 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_PARENT_BUS_ADDRESS"
392 idx_vals.append((idx_macro,
393 f"{range.parent_bus_addr} /* {hex(range.parent_bus_addr)} */"))
394 if range.length is not None:
395 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_LENGTH"
396 idx_vals.append((idx_macro,
397 f"{range.length} /* {hex(range.length)} */"))
398
399 for macro, val in idx_vals:
400 out_dt_define(macro, val)
401
402 out_dt_define(f"{path_id}_FOREACH_RANGE(fn)",
403 " ".join(f"fn(DT_{path_id}, {i})" for i,range in enumerate(node.ranges)))
404
Martí Bolívardc85edd2020-02-28 15:26:52 -0800405def write_regs(node):
406 # reg property: edtlib knows the right #address-cells and
407 # #size-cells, and can therefore pack the register base addresses
408 # and sizes correctly
409
410 idx_vals = []
411 name_vals = []
412 path_id = node.z_path_id
413
414 if node.regs is not None:
415 idx_vals.append((f"{path_id}_REG_NUM", len(node.regs)))
416
417 for i, reg in enumerate(node.regs):
Kumar Gala4e2ad002020-04-14 14:27:20 -0500418 idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800419 if reg.addr is not None:
420 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS"
421 idx_vals.append((idx_macro,
422 f"{reg.addr} /* {hex(reg.addr)} */"))
423 if reg.name:
424 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS"
425 name_vals.append((name_macro, f"DT_{idx_macro}"))
426
427 if reg.size is not None:
428 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE"
429 idx_vals.append((idx_macro,
430 f"{reg.size} /* {hex(reg.size)} */"))
431 if reg.name:
432 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE"
433 name_vals.append((name_macro, f"DT_{idx_macro}"))
434
435 for macro, val in idx_vals:
436 out_dt_define(macro, val)
437 for macro, val in name_vals:
438 out_dt_define(macro, val)
439
440def write_interrupts(node):
441 # interrupts property: we have some hard-coded logic for interrupt
442 # mapping here.
443 #
444 # TODO: can we push map_arm_gic_irq_type() and
445 # encode_zephyr_multi_level_irq() out of Python and into C with
446 # macro magic in devicetree.h?
447
448 def map_arm_gic_irq_type(irq, irq_num):
449 # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number
450 if "type" not in irq.data:
451 err(f"Expected binding for {irq.controller!r} to have 'type' in "
452 "interrupt-cells")
453 irq_type = irq.data["type"]
454
455 if irq_type == 0: # GIC_SPI
456 return irq_num + 32
457 if irq_type == 1: # GIC_PPI
458 return irq_num + 16
459 err(f"Invalid interrupt type specified for {irq!r}")
460
461 def encode_zephyr_multi_level_irq(irq, irq_num):
462 # See doc/reference/kernel/other/interrupts.rst for details
463 # on how this encoding works
464
465 irq_ctrl = irq.controller
466 # Look for interrupt controller parent until we have none
467 while irq_ctrl.interrupts:
468 irq_num = (irq_num + 1) << 8
469 if "irq" not in irq_ctrl.interrupts[0].data:
470 err(f"Expected binding for {irq_ctrl!r} to have 'irq' in "
471 "interrupt-cells")
472 irq_num |= irq_ctrl.interrupts[0].data["irq"]
473 irq_ctrl = irq_ctrl.interrupts[0].controller
474 return irq_num
475
476 idx_vals = []
477 name_vals = []
478 path_id = node.z_path_id
479
480 if node.interrupts is not None:
481 idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts)))
482
483 for i, irq in enumerate(node.interrupts):
484 for cell_name, cell_value in irq.data.items():
485 name = str2ident(cell_name)
486
487 if cell_name == "irq":
488 if "arm,gic" in irq.controller.compats:
489 cell_value = map_arm_gic_irq_type(irq, cell_value)
490 cell_value = encode_zephyr_multi_level_irq(irq, cell_value)
491
Kumar Gala4e2ad002020-04-14 14:27:20 -0500492 idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800493 idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}"
494 idx_vals.append((idx_macro, cell_value))
495 idx_vals.append((idx_macro + "_EXISTS", 1))
496 if irq.name:
497 name_macro = \
498 f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
499 name_vals.append((name_macro, f"DT_{idx_macro}"))
500 name_vals.append((name_macro + "_EXISTS", 1))
501
502 for macro, val in idx_vals:
503 out_dt_define(macro, val)
504 for macro, val in name_vals:
505 out_dt_define(macro, val)
506
507
508def write_compatibles(node):
509 # Writes a macro for each of the node's compatibles. We don't care
510 # about whether edtlib / Zephyr's binding language recognizes
511 # them. The compatibles the node provides are what is important.
512
Maureen Helm5b5aa6e2022-08-24 13:44:51 -0500513 for i, compat in enumerate(node.compats):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800514 out_dt_define(
515 f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1)
516
Maureen Helm5b5aa6e2022-08-24 13:44:51 -0500517 if node.edt.compat2vendor[compat]:
518 out_dt_define(f"{node.z_path_id}_COMPAT_VENDOR_IDX_{i}_EXISTS", 1)
519 out_dt_define(f"{node.z_path_id}_COMPAT_VENDOR_IDX_{i}",
520 quote_str(node.edt.compat2vendor[compat]))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800521
Maureen Helme73c3632022-09-07 17:17:18 -0500522 if node.edt.compat2model[compat]:
523 out_dt_define(f"{node.z_path_id}_COMPAT_MODEL_IDX_{i}_EXISTS", 1)
524 out_dt_define(f"{node.z_path_id}_COMPAT_MODEL_IDX_{i}",
525 quote_str(node.edt.compat2model[compat]))
526
Martí Bolívar355cc012022-03-23 13:26:24 -0700527def write_children(node):
528 # Writes helper macros for dealing with node's children.
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000529
Martí Bolívar7b2a7282022-07-08 11:04:46 -0700530 out_comment("Helper macros for child nodes of this node.")
531
Kumar Gala4a5a90a2020-05-08 12:25:25 -0500532 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",
533 " ".join(f"fn(DT_{child.z_path_id})" for child in
534 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000535
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200536 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_SEP(fn, sep)",
537 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id})"
538 for child in node.children.values()))
539
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400540 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)",
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200541 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
542 for child in node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000543
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200544 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_SEP_VARGS(fn, sep, ...)",
545 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
546 for child in node.children.values()))
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800547
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200548 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)",
549 " ".join(f"fn(DT_{child.z_path_id})"
550 for child in node.children.values() if child.status == "okay"))
551
552 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_SEP(fn, sep)",
553 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id})"
554 for child in node.children.values() if child.status == "okay"))
555
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400556 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)",
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200557 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
558 for child in node.children.values() if child.status == "okay"))
559
560 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_SEP_VARGS(fn, sep, ...)",
561 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
562 for child in node.children.values() if child.status == "okay"))
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800563
564
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700565def write_status(node):
566 out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1)
567
568
Martí Bolívar9df04932021-08-11 15:43:24 -0700569def write_pinctrls(node):
570 # Write special macros for pinctrl-<index> and pinctrl-names properties.
571
572 out_comment("Pin control (pinctrl-<i>, pinctrl-names) properties:")
573
574 out_dt_define(f"{node.z_path_id}_PINCTRL_NUM", len(node.pinctrls))
575
576 if not node.pinctrls:
577 return
578
579 for pc_idx, pinctrl in enumerate(node.pinctrls):
580 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_EXISTS", 1)
581
582 if not pinctrl.name:
583 continue
584
585 name = pinctrl.name_as_token
586
587 # Below we rely on the fact that edtlib ensures the
588 # pinctrl-<pc_idx> properties are contiguous, start from 0,
589 # and contain only phandles.
590 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_TOKEN", name)
591 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_UPPER_TOKEN", name.upper())
592 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_EXISTS", 1)
593 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX", pc_idx)
594 for idx, ph in enumerate(pinctrl.conf_nodes):
595 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX_{idx}_PH",
596 f"DT_{ph.z_path_id}")
597
598
Martí Bolívar7f69a032021-08-11 15:14:51 -0700599def write_fixed_partitions(node):
600 # Macros for child nodes of each fixed-partitions node.
601
602 if not (node.parent and "fixed-partitions" in node.parent.compats):
603 return
604
605 global flash_area_num
606 out_comment("fixed-partitions identifier:")
607 out_dt_define(f"{node.z_path_id}_PARTITION_ID", flash_area_num)
608 flash_area_num += 1
609
610
Martí Bolívardc85edd2020-02-28 15:26:52 -0800611def write_vanilla_props(node):
612 # Writes macros for any and all properties defined in the
613 # "properties" section of the binding for the node.
614 #
615 # This does generate macros for special properties as well, like
616 # regs, etc. Just let that be rather than bothering to add
617 # never-ending amounts of special case code here to skip special
618 # properties. This function's macros can't conflict with
619 # write_special_props() macros, because they're in different
620 # namespaces. Special cases aren't special enough to break the rules.
621
622 macro2val = {}
623 for prop_name, prop in node.props.items():
Martí Bolívar9c229a42021-04-14 15:26:42 -0700624 prop_id = str2ident(prop_name)
625 macro = f"{node.z_path_id}_P_{prop_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800626 val = prop2value(prop)
627 if val is not None:
628 # DT_N_<node-id>_P_<prop-id>
629 macro2val[macro] = val
630
Carlo Caionef4db14f2021-05-17 17:24:27 +0200631 if prop.spec.type == 'string':
632 macro2val[macro + "_STRING_TOKEN"] = prop.val_as_token
633 macro2val[macro + "_STRING_UPPER_TOKEN"] = prop.val_as_token.upper()
634
Martí Bolívardc85edd2020-02-28 15:26:52 -0800635 if prop.enum_index is not None:
636 # DT_N_<node-id>_P_<prop-id>_ENUM_IDX
637 macro2val[macro + "_ENUM_IDX"] = prop.enum_index
Peter Bigot345da782020-12-02 09:04:27 -0600638 spec = prop.spec
639
640 if spec.enum_tokenizable:
641 as_token = prop.val_as_token
642
643 # DT_N_<node-id>_P_<prop-id>_ENUM_TOKEN
644 macro2val[macro + "_ENUM_TOKEN"] = as_token
645
646 if spec.enum_upper_tokenizable:
647 # DT_N_<node-id>_P_<prop-id>_ENUM_UPPER_TOKEN
648 macro2val[macro + "_ENUM_UPPER_TOKEN"] = as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800649
650 if "phandle" in prop.type:
651 macro2val.update(phandle_macros(prop, macro))
652 elif "array" in prop.type:
653 # DT_N_<node-id>_P_<prop-id>_IDX_<i>
Martí Bolívarffc03122020-11-12 20:27:20 -0800654 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
Martí Bolívardc85edd2020-02-28 15:26:52 -0800655 for i, subval in enumerate(prop.val):
656 if isinstance(subval, str):
657 macro2val[macro + f"_IDX_{i}"] = quote_str(subval)
Martí Bolívard6f68f02022-07-08 11:21:34 -0700658 subval_as_token = edtlib.str_as_token(subval)
Radosław Koppel76141102022-05-07 20:27:49 +0200659 macro2val[macro + f"_IDX_{i}_STRING_TOKEN"] = subval_as_token
660 macro2val[macro + f"_IDX_{i}_STRING_UPPER_TOKEN"] = subval_as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800661 else:
662 macro2val[macro + f"_IDX_{i}"] = subval
Martí Bolívarffc03122020-11-12 20:27:20 -0800663 macro2val[macro + f"_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800664
Martí Bolívar9c229a42021-04-14 15:26:42 -0700665 if prop.type in FOREACH_PROP_ELEM_TYPES:
666 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
667 macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200668 ' \\\n\t'.join(
669 f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
670 for i in range(len(prop.val)))
671
672 macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP(fn, sep)"] = \
673 ' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
674 f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
675 for i in range(len(prop.val)))
Martí Bolívar9c229a42021-04-14 15:26:42 -0700676
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400677 macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200678 ' \\\n\t'.join(
679 f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
680 for i in range(len(prop.val)))
681
682 macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP_VARGS(fn, sep, ...)"] = \
683 ' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
684 f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
685 for i in range(len(prop.val)))
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400686
Martí Bolívardc85edd2020-02-28 15:26:52 -0800687 plen = prop_len(prop)
688 if plen is not None:
689 # DT_N_<node-id>_P_<prop-id>_LEN
690 macro2val[macro + "_LEN"] = plen
691
692 macro2val[f"{macro}_EXISTS"] = 1
693
694 if macro2val:
695 out_comment("Generic property macros:")
696 for macro, val in macro2val.items():
697 out_dt_define(macro, val)
698 else:
699 out_comment("(No generic property macros)")
700
701
Martí Bolívar305379e2020-06-08 14:59:19 -0700702def write_dep_info(node):
703 # Write dependency-related information about the node.
704
705 def fmt_dep_list(dep_list):
706 if dep_list:
707 # Sort the list by dependency ordinal for predictability.
708 sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
709 return "\\\n\t" + \
710 " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
711 for n in sorted_list)
712 else:
713 return "/* nothing */"
714
715 out_comment("Node's dependency ordinal:")
716 out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal)
717
718 out_comment("Ordinals for what this node depends on directly:")
719 out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS",
720 fmt_dep_list(node.depends_on))
721
722 out_comment("Ordinals for what depends directly on this node:")
723 out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS",
724 fmt_dep_list(node.required_by))
725
726
Martí Bolívardc85edd2020-02-28 15:26:52 -0800727def prop2value(prop):
728 # Gets the macro value for property 'prop', if there is
729 # a single well-defined C rvalue that it can be represented as.
730 # Returns None if there isn't one.
731
732 if prop.type == "string":
733 return quote_str(prop.val)
734
735 if prop.type == "int":
736 return prop.val
737
738 if prop.type == "boolean":
739 return 1 if prop.val else 0
740
741 if prop.type in ["array", "uint8-array"]:
742 return list2init(f"{val} /* {hex(val)} */" for val in prop.val)
743
744 if prop.type == "string-array":
745 return list2init(quote_str(val) for val in prop.val)
746
747 # phandle, phandles, phandle-array, path, compound: nothing
748 return None
749
750
751def prop_len(prop):
752 # Returns the property's length if and only if we should generate
753 # a _LEN macro for the property. Otherwise, returns None.
754 #
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200755 # This deliberately excludes ranges, dma-ranges, reg and interrupts.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800756 # While they have array type, their lengths as arrays are
757 # basically nonsense semantically due to #address-cells and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200758 # #size-cells for "reg", #interrupt-cells for "interrupts"
759 # and #address-cells, #size-cells and the #address-cells from the
760 # parent node for "ranges" and "dma-ranges".
Martí Bolívardc85edd2020-02-28 15:26:52 -0800761 #
762 # We have special purpose macros for the number of register blocks
763 # / interrupt specifiers. Excluding them from this list means
764 # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer
765 # with a build error. This forces users to switch to the right
766 # macros.
767
768 if prop.type == "phandle":
769 return 1
770
771 if (prop.type in ["array", "uint8-array", "string-array",
772 "phandles", "phandle-array"] and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200773 prop.name not in ["ranges", "dma-ranges", "reg", "interrupts"]):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800774 return len(prop.val)
775
776 return None
777
778
779def phandle_macros(prop, macro):
780 # Returns a dict of macros for phandle or phandles property 'prop'.
781 #
782 # The 'macro' argument is the N_<node-id>_P_<prop-id> bit.
783 #
784 # These are currently special because we can't serialize their
785 # values without using label properties, which we're trying to get
786 # away from needing in Zephyr. (Label properties are great for
787 # humans, but have drawbacks for code size and boot time.)
788 #
789 # The names look a bit weird to make it easier for devicetree.h
790 # to use the same macros for phandle, phandles, and phandle-array.
791
792 ret = {}
793
794 if prop.type == "phandle":
795 # A phandle is treated as a phandles with fixed length 1.
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500796 ret[f"{macro}"] = f"DT_{prop.val.z_path_id}"
797 ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800798 ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800799 ret[f"{macro}_IDX_0_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800800 elif prop.type == "phandles":
801 for i, node in enumerate(prop.val):
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500802 ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800803 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800804 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800805 elif prop.type == "phandle-array":
806 for i, entry in enumerate(prop.val):
Martí Bolívar38ede5a2020-12-17 14:12:01 -0800807 if entry is None:
808 # Unspecified element. The phandle-array at this index
809 # does not point at a ControllerAndData value, but
810 # subsequent indices in the array may.
811 ret[f"{macro}_IDX_{i}_EXISTS"] = 0
812 continue
813
Martí Bolívardc85edd2020-02-28 15:26:52 -0800814 ret.update(controller_and_data_macros(entry, i, macro))
815
816 return ret
817
818
819def controller_and_data_macros(entry, i, macro):
820 # Helper procedure used by phandle_macros().
821 #
822 # Its purpose is to write the "controller" (i.e. label property of
823 # the phandle's node) and associated data macros for a
824 # ControllerAndData.
825
826 ret = {}
827 data = entry.data
828
Martí Bolívarffc03122020-11-12 20:27:20 -0800829 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
830 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800831 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH
832 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}"
833 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL>
834 for cell, val in data.items():
835 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val
836 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1
837
838 if not entry.name:
839 return ret
840
841 name = str2ident(entry.name)
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200842 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
843 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800844 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME
845 ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name)
846 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH
847 ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}"
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200848 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS
849 ret[f"{macro}_NAME_{name}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800850 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
851 for cell, val in data.items():
852 cell_ident = str2ident(cell)
853 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
854 f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
855 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1
856
857 return ret
858
859
860def write_chosen(edt):
861 # Tree-wide information such as chosen nodes is printed here.
862
863 out_comment("Chosen nodes\n")
864 chosen = {}
865 for name, node in edt.chosen_nodes.items():
866 chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}"
867 chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1
Kumar Gala299bfd02020-03-25 15:32:58 -0500868 max_len = max(map(len, chosen), default=0)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800869 for macro, value in chosen.items():
870 out_define(macro, value, width=max_len)
871
872
Martí Bolívar190197e2022-07-20 13:10:33 -0700873def write_global_macros(edt):
874 # Global or tree-wide information, such as number of instances
875 # with status "okay" for each compatible, is printed here.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800876
Martí Bolívarf0d11f72022-07-20 13:15:56 -0700877
878 out_comment("Macros for iterating over all nodes and enabled nodes")
879 out_dt_define("FOREACH_HELPER(fn)",
880 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes))
881 out_dt_define("FOREACH_OKAY_HELPER(fn)",
882 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes
883 if node.status == "okay"))
884
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700885 n_okay_macros = {}
886 for_each_macros = {}
887 compat2buses = defaultdict(list) # just for "okay" nodes
888 for compat, okay_nodes in edt.compat2okay.items():
889 for node in okay_nodes:
Daniel Leung418c9152022-08-26 10:52:32 -0700890 buses = node.on_buses
891 for bus in buses:
892 if bus is not None and bus not in compat2buses[compat]:
893 compat2buses[compat].append(bus)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800894
Martí Bolívar63d55292020-04-06 15:13:53 -0700895 ident = str2ident(compat)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700896 n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes)
Martí Bolívare7d42ff2021-08-05 15:24:50 -0700897
898 # Helpers for non-INST for-each macros that take node
899 # identifiers as arguments.
900 for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
901 " ".join(f"fn(DT_{node.z_path_id})"
902 for node in okay_nodes)
903 for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
904 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
905 for node in okay_nodes)
906
907 # Helpers for INST versions of for-each macros, which take
908 # instance numbers. We emit separate helpers for these because
909 # avoiding an intermediate node_id --> instance number
910 # conversion in the preprocessor helps to keep the macro
911 # expansions simpler. That hopefully eases debugging.
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700912 for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
913 " ".join(f"fn({edt.compat2nodes[compat].index(node)})"
914 for node in okay_nodes)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400915 for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
916 " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
917 for node in okay_nodes)
918
Kumar Galabd973782020-05-06 20:54:29 -0500919 for compat, nodes in edt.compat2nodes.items():
920 for node in nodes:
921 if compat == "fixed-partitions":
922 for child in node.children.values():
923 if "label" in child.props:
924 label = child.props["label"].val
925 macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}"
926 val = f"DT_{child.z_path_id}"
927
928 out_dt_define(macro, val)
929 out_dt_define(macro + "_EXISTS", 1)
930
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700931 out_comment('Macros for compatibles with status "okay" nodes\n')
932 for compat, okay_nodes in edt.compat2okay.items():
933 if okay_nodes:
934 out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1)
935
936 out_comment('Macros for status "okay" instances of each compatible\n')
937 for macro, value in n_okay_macros.items():
Martí Bolívar63d55292020-04-06 15:13:53 -0700938 out_define(macro, value)
939 for macro, value in for_each_macros.items():
940 out_define(macro, value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800941
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700942 out_comment('Bus information for status "okay" nodes of each compatible\n')
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700943 for compat, buses in compat2buses.items():
944 for bus in buses:
945 out_define(
946 f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800947
948def str2ident(s):
949 # Converts 's' to a form suitable for (part of) an identifier
950
951 return re.sub('[-,.@/+]', '_', s.lower())
952
953
954def list2init(l):
955 # Converts 'l', a Python list (or iterable), to a C array initializer
956
957 return "{" + ", ".join(l) + "}"
958
959
960def out_dt_define(macro, val, width=None, deprecation_msg=None):
961 # Writes "#define DT_<macro> <val>" to the header file
962 #
963 # The macro will be left-justified to 'width' characters if that
964 # is specified, and the value will follow immediately after in
965 # that case. Otherwise, this function decides how to add
966 # whitespace between 'macro' and 'val'.
967 #
968 # If a 'deprecation_msg' string is passed, the generated identifiers will
969 # generate a warning if used, via __WARN(<deprecation_msg>)).
970 #
971 # Returns the full generated macro for 'macro', with leading "DT_".
972 ret = "DT_" + macro
973 out_define(ret, val, width=width, deprecation_msg=deprecation_msg)
974 return ret
975
976
977def out_define(macro, val, width=None, deprecation_msg=None):
978 # Helper for out_dt_define(). Outputs "#define <macro> <val>",
979 # adds a deprecation message if given, and allocates whitespace
980 # unless told not to.
981
982 warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else ""
983
984 if width:
985 s = f"#define {macro.ljust(width)}{warn} {val}"
986 else:
987 s = f"#define {macro}{warn} {val}"
988
989 print(s, file=header_file)
990
991
992def out_comment(s, blank_before=True):
993 # Writes 's' as a comment to the header and configuration file. 's' is
994 # allowed to have multiple lines. blank_before=True adds a blank line
995 # before the comment.
996
997 if blank_before:
998 print(file=header_file)
999
1000 if "\n" in s:
1001 # Format multi-line comments like
1002 #
1003 # /*
1004 # * first line
1005 # * second line
1006 # *
1007 # * empty line before this line
1008 # */
1009 res = ["/*"]
1010 for line in s.splitlines():
1011 # Avoid an extra space after '*' for empty lines. They turn red in
1012 # Vim if space error checking is on, which is annoying.
1013 res.append(" *" if not line.strip() else " * " + line)
1014 res.append(" */")
1015 print("\n".join(res), file=header_file)
1016 else:
1017 # Format single-line comments like
1018 #
1019 # /* foo bar */
1020 print("/* " + s + " */", file=header_file)
1021
1022
1023def escape(s):
1024 # Backslash-escapes any double quotes and backslashes in 's'
1025
1026 # \ must be escaped before " to avoid double escaping
1027 return s.replace("\\", "\\\\").replace('"', '\\"')
1028
1029
1030def quote_str(s):
1031 # Puts quotes around 's' and escapes any double quotes and
1032 # backslashes within it
1033
1034 return f'"{escape(s)}"'
1035
1036
Martí Bolívar533f4512020-07-01 10:43:43 -07001037def write_pickled_edt(edt, out_file):
1038 # Writes the edt object in pickle format to out_file.
1039
1040 with open(out_file, 'wb') as f:
1041 # Pickle protocol version 4 is the default as of Python 3.8
1042 # and was introduced in 3.4, so it is both available and
1043 # recommended on all versions of Python that Zephyr supports
1044 # (at time of writing, Python 3.6 was Zephyr's minimum
1045 # version, and 3.8 the most recent CPython release).
1046 #
1047 # Using a common protocol version here will hopefully avoid
1048 # reproducibility issues in different Python installations.
1049 pickle.dump(edt, f, protocol=4)
1050
1051
Martí Bolívardc85edd2020-02-28 15:26:52 -08001052def err(s):
1053 raise Exception(s)
1054
1055
1056if __name__ == "__main__":
1057 main()