blob: 9fdb3cda5778c59599199cbd5f3bbfc7b068659b [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
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +02005# Copyright (c) 2024 SILA Embedded Solutions GmbH
Martí Bolívardc85edd2020-02-28 15:26:52 -08006# SPDX-License-Identifier: BSD-3-Clause
7
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +02008# This script uses edtlib to generate a header file from a pickled
9# edt file.
Martí Bolívardc85edd2020-02-28 15:26:52 -080010#
11# Note: Do not access private (_-prefixed) identifiers from edtlib here (and
12# also note that edtlib is not meant to expose the dtlib API directly).
13# Instead, think of what API you need, and add it as a public documented API in
14# edtlib. This will keep this script simple.
15
16import argparse
Martí Bolívara3fae2f2020-03-25 14:18:27 -070017from collections import defaultdict
Martí Bolívardc85edd2020-02-28 15:26:52 -080018import os
19import pathlib
Martí Bolívar533f4512020-07-01 10:43:43 -070020import pickle
Martí Bolívardc85edd2020-02-28 15:26:52 -080021import re
22import sys
Florian Grandelde846c72024-09-06 10:15:55 +020023from typing import Iterable, NoReturn, Optional
Martí Bolívardc85edd2020-02-28 15:26:52 -080024
Jordan Yates8e4107f2022-04-30 21:13:52 +100025sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'python-devicetree',
26 'src'))
Martí Bolívar53328472021-03-26 16:18:58 -070027
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +020028import edtlib_logger
Martí Bolívar53328472021-03-26 16:18:58 -070029from devicetree import edtlib
Martí Bolívardc85edd2020-02-28 15:26:52 -080030
Martí Bolívar09858492020-12-08 09:41:49 -080031
Martí Bolívardc85edd2020-02-28 15:26:52 -080032def main():
33 global header_file
Kumar Galabd973782020-05-06 20:54:29 -050034 global flash_area_num
Martí Bolívardc85edd2020-02-28 15:26:52 -080035
36 args = parse_args()
37
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +020038 edtlib_logger.setup_edtlib_logging()
Martí Bolívar09858492020-12-08 09:41:49 -080039
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +020040 with open(args.edt_pickle, 'rb') as f:
41 edt = pickle.load(f)
Martí Bolívardc85edd2020-02-28 15:26:52 -080042
Kumar Galabd973782020-05-06 20:54:29 -050043 flash_area_num = 0
44
Martí Bolívar533f4512020-07-01 10:43:43 -070045 # Create the generated header.
Martí Bolívardc85edd2020-02-28 15:26:52 -080046 with open(args.header_out, "w", encoding="utf-8") as header_file:
47 write_top_comment(edt)
48
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +020049 write_utils()
50
Florian Grandel945925b2024-09-06 10:17:26 +020051 sorted_nodes = sorted(edt.nodes, key=lambda node: node.dep_ordinal)
52
Dominik Ermelba8b74d2020-04-17 06:32:28 +000053 # populate all z_path_id first so any children references will
54 # work correctly.
Florian Grandel945925b2024-09-06 10:17:26 +020055 for node in sorted_nodes:
Martí Bolívar186bace2020-04-08 15:02:18 -070056 node.z_path_id = node_z_path_id(node)
Dominik Ermelba8b74d2020-04-17 06:32:28 +000057
Jordan Yates9c98d4f2021-07-28 20:01:16 +100058 # Check to see if we have duplicate "zephyr,memory-region" property values.
59 regions = dict()
Florian Grandel945925b2024-09-06 10:17:26 +020060 for node in sorted_nodes:
Jordan Yates9c98d4f2021-07-28 20:01:16 +100061 if 'zephyr,memory-region' in node.props:
62 region = node.props['zephyr,memory-region'].val
63 if region in regions:
64 sys.exit(f"ERROR: Duplicate 'zephyr,memory-region' ({region}) properties "
65 f"between {regions[region].path} and {node.path}")
66 regions[region] = node
67
Florian Grandel945925b2024-09-06 10:17:26 +020068 for node in sorted_nodes:
Martí Bolívardc85edd2020-02-28 15:26:52 -080069 write_node_comment(node)
70
Kumar Gala270a05f2021-02-24 11:28:21 -060071 out_comment("Node's full path:")
Martí Bolívar00ffc7e2020-12-13 12:27:04 -080072 out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"')
73
Kumar Gala4aac9082021-02-24 10:44:07 -060074 out_comment("Node's name with unit-address:")
75 out_dt_define(f"{node.z_path_id}_FULL_NAME",
76 f'"{escape(node.name)}"')
TOKITA Hiroshi767d1ce2024-09-12 22:58:53 +090077 out_dt_define(f"{node.z_path_id}_FULL_NAME_UNQUOTED",
78 f'{escape(node.name)}')
79 out_dt_define(f"{node.z_path_id}_FULL_NAME_TOKEN",
80 f'{edtlib.str_as_token(escape(node.name))}')
81 out_dt_define(f"{node.z_path_id}_FULL_NAME_UPPER_TOKEN",
82 f'{edtlib.str_as_token(escape(node.name)).upper()}')
Kumar Gala4aac9082021-02-24 10:44:07 -060083
Martí Bolívar6e273432020-04-08 15:04:15 -070084 if node.parent is not None:
85 out_comment(f"Node parent ({node.parent.path}) identifier:")
86 out_dt_define(f"{node.z_path_id}_PARENT",
87 f"DT_{node.parent.z_path_id}")
88
Martí Bolívar50f9b3c2022-03-23 13:41:09 -070089 out_comment(f"Node's index in its parent's list of children:")
90 out_dt_define(f"{node.z_path_id}_CHILD_IDX",
91 node.parent.child_index(node))
92
Martí Bolívar74abb2b2024-04-24 19:22:42 -060093 out_comment("Helpers for dealing with node labels:")
94 out_dt_define(f"{node.z_path_id}_NODELABEL_NUM", len(node.labels))
95 out_dt_define(f"{node.z_path_id}_FOREACH_NODELABEL(fn)",
96 " ".join(f"fn({nodelabel})" for nodelabel in node.labels))
97 out_dt_define(f"{node.z_path_id}_FOREACH_NODELABEL_VARGS(fn, ...)",
98 " ".join(f"fn({nodelabel}, __VA_ARGS__)" for nodelabel in node.labels))
99
Martí Bolívar355cc012022-03-23 13:26:24 -0700100 write_children(node)
Martí Bolívar305379e2020-06-08 14:59:19 -0700101 write_dep_info(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800102 write_idents_and_existence(node)
103 write_bus(node)
104 write_special_props(node)
105 write_vanilla_props(node)
106
107 write_chosen(edt)
Martí Bolívar190197e2022-07-20 13:10:33 -0700108 write_global_macros(edt)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800109
Florian Grandelde846c72024-09-06 10:15:55 +0200110
111def node_z_path_id(node: edtlib.Node) -> str:
Martí Bolívar186bace2020-04-08 15:02:18 -0700112 # Return the node specific bit of the node's path identifier:
113 #
114 # - the root node's path "/" has path identifier "N"
115 # - "/foo" has "N_S_foo"
116 # - "/foo/bar" has "N_S_foo_S_bar"
117 # - "/foo/bar@123" has "N_S_foo_S_bar_123"
118 #
119 # This is used throughout this file to generate macros related to
120 # the node.
121
122 components = ["N"]
123 if node.parent is not None:
124 components.extend(f"S_{str2ident(component)}" for component in
125 node.path.split("/")[1:])
126
127 return "_".join(components)
128
Florian Grandelde846c72024-09-06 10:15:55 +0200129
130def parse_args() -> argparse.Namespace:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800131 # Returns parsed command-line arguments
132
Jamie McCraeec704442023-01-04 16:08:36 +0000133 parser = argparse.ArgumentParser(allow_abbrev=False)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800134 parser.add_argument("--header-out", required=True,
135 help="path to write header to")
Benedikt Schmidtfe3287a2024-09-09 11:18:56 +0200136 parser.add_argument("--edt-pickle",
137 help="path to read pickled edtlib.EDT object from")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800138
139 return parser.parse_args()
140
141
Florian Grandelde846c72024-09-06 10:15:55 +0200142def write_top_comment(edt: edtlib.EDT) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800143 # Writes an overview comment with misc. info at the top of the header and
144 # configuration file
145
146 s = f"""\
147Generated by gen_defines.py
148
149DTS input file:
150 {edt.dts_path}
151
152Directories with bindings:
153 {", ".join(map(relativize, edt.bindings_dirs))}
154
Martí Bolívar305379e2020-06-08 14:59:19 -0700155Node dependency ordering (ordinal and path):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800156"""
157
Martí Bolívarb6db2012020-08-24 13:33:53 -0700158 for scc in edt.scc_order:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800159 if len(scc) > 1:
160 err("cycle in devicetree involving "
161 + ", ".join(node.path for node in scc))
162 s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n"
163
164 s += """
165Definitions derived from these nodes in dependency order are next,
166followed by /chosen nodes.
167"""
168
169 out_comment(s, blank_before=False)
170
171
Florian Grandelde846c72024-09-06 10:15:55 +0200172def write_utils() -> None:
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +0200173 # Writes utility macros
174
175 out_comment("Used to remove brackets from around a single argument")
176 out_define("DT_DEBRACKET_INTERNAL(...)", "__VA_ARGS__")
177
178
Florian Grandelde846c72024-09-06 10:15:55 +0200179def write_node_comment(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800180 # Writes a comment describing 'node' to the header and configuration file
181
182 s = f"""\
Martí Bolívarb6e6ba02020-04-08 15:09:46 -0700183Devicetree node: {node.path}
184
Martí Bolívar305379e2020-06-08 14:59:19 -0700185Node identifier: DT_{node.z_path_id}
Martí Bolívardc85edd2020-02-28 15:26:52 -0800186"""
187
188 if node.matching_compat:
Peter Bigot932532e2020-09-02 05:05:19 -0500189 if node.binding_path:
190 s += f"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800191Binding (compatible = {node.matching_compat}):
192 {relativize(node.binding_path)}
193"""
Peter Bigot932532e2020-09-02 05:05:19 -0500194 else:
195 s += f"""
196Binding (compatible = {node.matching_compat}):
197 No yaml (bindings inferred from properties)
198"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800199
Martí Bolívardc85edd2020-02-28 15:26:52 -0800200 if node.description:
Martí Bolívarf7d33f22020-10-30 17:45:27 -0700201 # We used to put descriptions in the generated file, but
202 # devicetree bindings now have pages in the HTML
203 # documentation. Let users who are accustomed to digging
204 # around in the generated file where to find the descriptions
205 # now.
206 #
207 # Keeping them here would mean that the descriptions
208 # themselves couldn't contain C multi-line comments, which is
209 # inconvenient when we want to do things like quote snippets
210 # of .dtsi files within the descriptions, or otherwise
211 # include the string "*/".
212 s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n"
213 "in the documentation.)\n")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800214
215 out_comment(s)
216
217
Florian Grandelde846c72024-09-06 10:15:55 +0200218def relativize(path) -> Optional[str]:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800219 # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE,
220 # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise,
221 # returns 'path' unchanged.
222
223 zbase = os.getenv("ZEPHYR_BASE")
224 if zbase is None:
225 return path
226
227 try:
228 return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase))
229 except ValueError:
230 # Not within ZEPHYR_BASE
231 return path
232
233
Florian Grandelde846c72024-09-06 10:15:55 +0200234def write_idents_and_existence(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800235 # Writes macros related to the node's aliases, labels, etc.,
236 # as well as existence flags.
237
238 # Aliases
239 idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases]
240 # Instances
241 for compat in node.compats:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700242 instance_no = node.edt.compat2nodes[compat].index(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800243 idents.append(f"N_INST_{instance_no}_{str2ident(compat)}")
244 # Node labels
245 idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels)
246
247 out_comment("Existence and alternate IDs:")
248 out_dt_define(node.z_path_id + "_EXISTS", 1)
249
250 # Only determine maxlen if we have any idents
251 if idents:
252 maxlen = max(len("DT_" + ident) for ident in idents)
253 for ident in idents:
254 out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen)
255
256
Florian Grandelde846c72024-09-06 10:15:55 +0200257def write_bus(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800258 # Macros about the node's bus controller, if there is one
259
260 bus = node.bus_node
261 if not bus:
262 return
263
Daniel Leung418c9152022-08-26 10:52:32 -0700264 out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_buses}')")
265
266 for one_bus in node.on_buses:
267 out_dt_define(f"{node.z_path_id}_BUS_{str2ident(one_bus)}", 1)
268
Martí Bolívardc85edd2020-02-28 15:26:52 -0800269 out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}")
270
271
Florian Grandelde846c72024-09-06 10:15:55 +0200272def write_special_props(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800273 # Writes required macros for special case properties, when the
274 # data cannot otherwise be obtained from write_vanilla_props()
275 # results
276
Martí Bolívardc85edd2020-02-28 15:26:52 -0800277 # Macros that are special to the devicetree specification
Martí Bolívar7f69a032021-08-11 15:14:51 -0700278 out_comment("Macros for properties that are special in the specification:")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800279 write_regs(node)
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200280 write_ranges(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800281 write_interrupts(node)
282 write_compatibles(node)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700283 write_status(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800284
Martí Bolívar7f69a032021-08-11 15:14:51 -0700285 # Macros that are special to bindings inherited from Linux, which
286 # we can't capture with the current bindings language.
Martí Bolívar9df04932021-08-11 15:43:24 -0700287 write_pinctrls(node)
Martí Bolívar7f69a032021-08-11 15:14:51 -0700288 write_fixed_partitions(node)
Henrik Brix Andersen28819152023-01-13 11:32:27 +0100289 write_gpio_hogs(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800290
Florian Grandelde846c72024-09-06 10:15:55 +0200291
292def write_ranges(node: edtlib.Node) -> None:
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200293 # ranges property: edtlib knows the right #address-cells and
294 # #size-cells of parent and child, and can therefore pack the
295 # child & parent addresses and sizes correctly
296
297 idx_vals = []
298 path_id = node.z_path_id
299
300 if node.ranges is not None:
301 idx_vals.append((f"{path_id}_RANGES_NUM", len(node.ranges)))
302
303 for i,range in enumerate(node.ranges):
304 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_EXISTS", 1))
305
Daniel Leung418c9152022-08-26 10:52:32 -0700306 if "pcie" in node.buses:
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200307 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS_EXISTS", 1))
308 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS"
309 idx_value = range.child_bus_addr >> ((range.child_bus_cells - 1) * 32)
310 idx_vals.append((idx_macro,
311 f"{idx_value} /* {hex(idx_value)} */"))
312 if range.child_bus_addr is not None:
313 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_ADDRESS"
Daniel Leung418c9152022-08-26 10:52:32 -0700314 if "pcie" in node.buses:
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200315 idx_value = range.child_bus_addr & ((1 << (range.child_bus_cells - 1) * 32) - 1)
316 else:
317 idx_value = range.child_bus_addr
318 idx_vals.append((idx_macro,
319 f"{idx_value} /* {hex(idx_value)} */"))
320 if range.parent_bus_addr is not None:
321 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_PARENT_BUS_ADDRESS"
322 idx_vals.append((idx_macro,
323 f"{range.parent_bus_addr} /* {hex(range.parent_bus_addr)} */"))
324 if range.length is not None:
325 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_LENGTH"
326 idx_vals.append((idx_macro,
327 f"{range.length} /* {hex(range.length)} */"))
328
329 for macro, val in idx_vals:
330 out_dt_define(macro, val)
331
332 out_dt_define(f"{path_id}_FOREACH_RANGE(fn)",
333 " ".join(f"fn(DT_{path_id}, {i})" for i,range in enumerate(node.ranges)))
334
Florian Grandelde846c72024-09-06 10:15:55 +0200335
336def write_regs(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800337 # reg property: edtlib knows the right #address-cells and
338 # #size-cells, and can therefore pack the register base addresses
339 # and sizes correctly
340
341 idx_vals = []
342 name_vals = []
343 path_id = node.z_path_id
344
345 if node.regs is not None:
346 idx_vals.append((f"{path_id}_REG_NUM", len(node.regs)))
347
348 for i, reg in enumerate(node.regs):
Kumar Gala4e2ad002020-04-14 14:27:20 -0500349 idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800350 if reg.addr is not None:
351 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS"
352 idx_vals.append((idx_macro,
353 f"{reg.addr} /* {hex(reg.addr)} */"))
354 if reg.name:
Fin Maaßfb8b30d2024-05-28 11:56:42 +0200355 name_vals.append((f"{path_id}_REG_NAME_{reg.name}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800356 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS"
357 name_vals.append((name_macro, f"DT_{idx_macro}"))
358
359 if reg.size is not None:
360 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE"
361 idx_vals.append((idx_macro,
362 f"{reg.size} /* {hex(reg.size)} */"))
363 if reg.name:
364 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE"
365 name_vals.append((name_macro, f"DT_{idx_macro}"))
366
367 for macro, val in idx_vals:
368 out_dt_define(macro, val)
369 for macro, val in name_vals:
370 out_dt_define(macro, val)
371
Florian Grandelde846c72024-09-06 10:15:55 +0200372
373def write_interrupts(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800374 # interrupts property: we have some hard-coded logic for interrupt
375 # mapping here.
376 #
Yong Cong Sindf2c0682023-10-02 12:42:24 +0800377 # TODO: can we push map_arm_gic_irq_type() out of Python and into C with
Martí Bolívardc85edd2020-02-28 15:26:52 -0800378 # macro magic in devicetree.h?
379
380 def map_arm_gic_irq_type(irq, irq_num):
381 # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number
382 if "type" not in irq.data:
383 err(f"Expected binding for {irq.controller!r} to have 'type' in "
384 "interrupt-cells")
385 irq_type = irq.data["type"]
386
387 if irq_type == 0: # GIC_SPI
388 return irq_num + 32
389 if irq_type == 1: # GIC_PPI
390 return irq_num + 16
391 err(f"Invalid interrupt type specified for {irq!r}")
392
Martí Bolívardc85edd2020-02-28 15:26:52 -0800393 idx_vals = []
394 name_vals = []
395 path_id = node.z_path_id
396
397 if node.interrupts is not None:
398 idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts)))
399
400 for i, irq in enumerate(node.interrupts):
401 for cell_name, cell_value in irq.data.items():
402 name = str2ident(cell_name)
403
404 if cell_name == "irq":
405 if "arm,gic" in irq.controller.compats:
406 cell_value = map_arm_gic_irq_type(irq, cell_value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800407
Kumar Gala4e2ad002020-04-14 14:27:20 -0500408 idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800409 idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}"
410 idx_vals.append((idx_macro, cell_value))
411 idx_vals.append((idx_macro + "_EXISTS", 1))
412 if irq.name:
413 name_macro = \
414 f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
415 name_vals.append((name_macro, f"DT_{idx_macro}"))
416 name_vals.append((name_macro + "_EXISTS", 1))
417
Bjarki Arge Andreasen08d6ff02023-11-26 11:34:06 +0100418 idx_controller_macro = f"{path_id}_IRQ_IDX_{i}_CONTROLLER"
419 idx_controller_path = f"DT_{irq.controller.z_path_id}"
420 idx_vals.append((idx_controller_macro, idx_controller_path))
421 if irq.name:
422 name_controller_macro = f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_CONTROLLER"
423 name_vals.append((name_controller_macro, f"DT_{idx_controller_macro}"))
424
Yong Cong Sin450a66f2023-12-22 16:20:10 +0800425 # Interrupt controller info
426 irqs = []
427 while node.interrupts is not None and len(node.interrupts) > 0:
428 irq = node.interrupts[0]
429 irqs.append(irq)
430 if node == irq.controller:
431 break
432 node = irq.controller
433 idx_vals.append((f"{path_id}_IRQ_LEVEL", len(irqs)))
434
Martí Bolívardc85edd2020-02-28 15:26:52 -0800435 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
440
Florian Grandelde846c72024-09-06 10:15:55 +0200441def write_compatibles(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800442 # Writes a macro for each of the node's compatibles. We don't care
443 # about whether edtlib / Zephyr's binding language recognizes
444 # them. The compatibles the node provides are what is important.
445
Maureen Helm5b5aa6e2022-08-24 13:44:51 -0500446 for i, compat in enumerate(node.compats):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800447 out_dt_define(
448 f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1)
449
Maureen Helm5b5aa6e2022-08-24 13:44:51 -0500450 if node.edt.compat2vendor[compat]:
451 out_dt_define(f"{node.z_path_id}_COMPAT_VENDOR_IDX_{i}_EXISTS", 1)
452 out_dt_define(f"{node.z_path_id}_COMPAT_VENDOR_IDX_{i}",
453 quote_str(node.edt.compat2vendor[compat]))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800454
Maureen Helme73c3632022-09-07 17:17:18 -0500455 if node.edt.compat2model[compat]:
456 out_dt_define(f"{node.z_path_id}_COMPAT_MODEL_IDX_{i}_EXISTS", 1)
457 out_dt_define(f"{node.z_path_id}_COMPAT_MODEL_IDX_{i}",
458 quote_str(node.edt.compat2model[compat]))
459
Florian Grandelde846c72024-09-06 10:15:55 +0200460
461def write_children(node: edtlib.Node) -> None:
Martí Bolívar355cc012022-03-23 13:26:24 -0700462 # Writes helper macros for dealing with node's children.
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000463
Martí Bolívar7b2a7282022-07-08 11:04:46 -0700464 out_comment("Helper macros for child nodes of this node.")
465
Swift Tian5871ff02024-04-25 18:52:22 +0800466 out_dt_define(f"{node.z_path_id}_CHILD_NUM", len(node.children))
467
468 ok_nodes_num = 0
469 for child in node.children.values():
470 if child.status == "okay":
471 ok_nodes_num = ok_nodes_num + 1
472
473 out_dt_define(f"{node.z_path_id}_CHILD_NUM_STATUS_OKAY", ok_nodes_num)
474
Kumar Gala4a5a90a2020-05-08 12:25:25 -0500475 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",
476 " ".join(f"fn(DT_{child.z_path_id})" for child in
477 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000478
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200479 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_SEP(fn, sep)",
480 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id})"
481 for child in node.children.values()))
482
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400483 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)",
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200484 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
485 for child in node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000486
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200487 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_SEP_VARGS(fn, sep, ...)",
488 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
489 for child in node.children.values()))
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800490
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200491 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)",
492 " ".join(f"fn(DT_{child.z_path_id})"
493 for child in node.children.values() if child.status == "okay"))
494
495 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_SEP(fn, sep)",
496 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id})"
497 for child in node.children.values() if child.status == "okay"))
498
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400499 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)",
Gerard Marull-Paretasfff9ecb2022-07-05 16:52:36 +0200500 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
501 for child in node.children.values() if child.status == "okay"))
502
503 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_SEP_VARGS(fn, sep, ...)",
504 " DT_DEBRACKET_INTERNAL sep ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)"
505 for child in node.children.values() if child.status == "okay"))
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800506
507
Florian Grandelde846c72024-09-06 10:15:55 +0200508def write_status(node: edtlib.Node) -> None:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700509 out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1)
510
511
Florian Grandelde846c72024-09-06 10:15:55 +0200512def write_pinctrls(node: edtlib.Node) -> None:
Martí Bolívar9df04932021-08-11 15:43:24 -0700513 # Write special macros for pinctrl-<index> and pinctrl-names properties.
514
515 out_comment("Pin control (pinctrl-<i>, pinctrl-names) properties:")
516
517 out_dt_define(f"{node.z_path_id}_PINCTRL_NUM", len(node.pinctrls))
518
519 if not node.pinctrls:
520 return
521
522 for pc_idx, pinctrl in enumerate(node.pinctrls):
523 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_EXISTS", 1)
524
525 if not pinctrl.name:
526 continue
527
528 name = pinctrl.name_as_token
529
530 # Below we rely on the fact that edtlib ensures the
531 # pinctrl-<pc_idx> properties are contiguous, start from 0,
532 # and contain only phandles.
533 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_TOKEN", name)
534 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_UPPER_TOKEN", name.upper())
535 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_EXISTS", 1)
536 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX", pc_idx)
537 for idx, ph in enumerate(pinctrl.conf_nodes):
538 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX_{idx}_PH",
539 f"DT_{ph.z_path_id}")
540
541
Florian Grandelde846c72024-09-06 10:15:55 +0200542def write_fixed_partitions(node: edtlib.Node) -> None:
Martí Bolívar7f69a032021-08-11 15:14:51 -0700543 # Macros for child nodes of each fixed-partitions node.
544
545 if not (node.parent and "fixed-partitions" in node.parent.compats):
546 return
547
548 global flash_area_num
549 out_comment("fixed-partitions identifier:")
550 out_dt_define(f"{node.z_path_id}_PARTITION_ID", flash_area_num)
551 flash_area_num += 1
552
553
Florian Grandelde846c72024-09-06 10:15:55 +0200554def write_gpio_hogs(node: edtlib.Node) -> None:
Henrik Brix Andersen28819152023-01-13 11:32:27 +0100555 # Write special macros for gpio-hog node properties.
556
557 macro = f"{node.z_path_id}_GPIO_HOGS"
558 macro2val = {}
559 for i, entry in enumerate(node.gpio_hogs):
560 macro2val.update(controller_and_data_macros(entry, i, macro))
561
562 if macro2val:
563 out_comment("GPIO hog properties:")
564 out_dt_define(f"{macro}_EXISTS", 1)
565 out_dt_define(f"{macro}_NUM", len(node.gpio_hogs))
566 for macro, val in macro2val.items():
567 out_dt_define(macro, val)
568
Florian Grandelde846c72024-09-06 10:15:55 +0200569
570def write_vanilla_props(node: edtlib.Node) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800571 # Writes macros for any and all properties defined in the
572 # "properties" section of the binding for the node.
573 #
574 # This does generate macros for special properties as well, like
575 # regs, etc. Just let that be rather than bothering to add
576 # never-ending amounts of special case code here to skip special
577 # properties. This function's macros can't conflict with
578 # write_special_props() macros, because they're in different
579 # namespaces. Special cases aren't special enough to break the rules.
580
581 macro2val = {}
582 for prop_name, prop in node.props.items():
Martí Bolívar9c229a42021-04-14 15:26:42 -0700583 prop_id = str2ident(prop_name)
584 macro = f"{node.z_path_id}_P_{prop_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800585 val = prop2value(prop)
586 if val is not None:
587 # DT_N_<node-id>_P_<prop-id>
588 macro2val[macro] = val
589
Carlo Caionef4db14f2021-05-17 17:24:27 +0200590 if prop.spec.type == 'string':
Joel Hirsbrunner8b02bc92024-10-04 21:29:37 +0200591 macro2val.update(string_macros(macro, prop.val))
Martí Bolívar0c29e072023-05-06 14:42:15 -0700592 # DT_N_<node-id>_P_<prop-id>_IDX_0:
593 # DT_N_<node-id>_P_<prop-id>_IDX_0_EXISTS:
594 # Allows treating the string like a degenerate case of a
595 # string-array of length 1.
596 macro2val[macro + "_IDX_0"] = quote_str(prop.val)
597 macro2val[macro + "_IDX_0_EXISTS"] = 1
Carlo Caionef4db14f2021-05-17 17:24:27 +0200598
Joel Hirsbrunner8b02bc92024-10-04 21:29:37 +0200599 if prop.enum_indices is not None:
600 macro2val.update(enum_macros(prop, macro))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800601
602 if "phandle" in prop.type:
603 macro2val.update(phandle_macros(prop, macro))
604 elif "array" in prop.type:
Joel Hirsbrunner8b02bc92024-10-04 21:29:37 +0200605 macro2val.update(array_macros(prop, macro))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800606
Martí Bolívar0c29e072023-05-06 14:42:15 -0700607 plen = prop_len(prop)
608 if plen is not None:
Martí Bolívar9c229a42021-04-14 15:26:42 -0700609 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
610 macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200611 ' \\\n\t'.join(
612 f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
Martí Bolívar0c29e072023-05-06 14:42:15 -0700613 for i in range(plen))
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200614
Martí Bolívar52043692023-05-05 15:30:38 -0700615 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_SEP
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200616 macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP(fn, sep)"] = \
617 ' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
618 f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
Martí Bolívar0c29e072023-05-06 14:42:15 -0700619 for i in range(plen))
Martí Bolívar9c229a42021-04-14 15:26:42 -0700620
Martí Bolívar52043692023-05-05 15:30:38 -0700621 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_VARGS
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400622 macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200623 ' \\\n\t'.join(
624 f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
Martí Bolívar0c29e072023-05-06 14:42:15 -0700625 for i in range(plen))
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200626
Martí Bolívar52043692023-05-05 15:30:38 -0700627 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_SEP_VARGS
Gerard Marull-Paretasfdea3c92022-09-06 15:31:15 +0200628 macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP_VARGS(fn, sep, ...)"] = \
629 ' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
630 f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
Martí Bolívar0c29e072023-05-06 14:42:15 -0700631 for i in range(plen))
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400632
Martí Bolívardc85edd2020-02-28 15:26:52 -0800633 # DT_N_<node-id>_P_<prop-id>_LEN
634 macro2val[macro + "_LEN"] = plen
635
Martí Bolívar52043692023-05-05 15:30:38 -0700636 # DT_N_<node-id>_P_<prop-id>_EXISTS
Martí Bolívardc85edd2020-02-28 15:26:52 -0800637 macro2val[f"{macro}_EXISTS"] = 1
638
639 if macro2val:
640 out_comment("Generic property macros:")
641 for macro, val in macro2val.items():
642 out_dt_define(macro, val)
643 else:
644 out_comment("(No generic property macros)")
645
646
Joel Hirsbrunner8b02bc92024-10-04 21:29:37 +0200647def string_macros(macro: str, val: str):
648 # Returns a dict of macros for a string 'val'.
649 # The 'macro' argument is the N_<node-id>_P_<prop-id>... part.
650
651 as_token = edtlib.str_as_token(val)
652 return {
653 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_STRING_UNQUOTED
654 f"{macro}_STRING_UNQUOTED": escape_unquoted(val),
655 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_STRING_TOKEN
656 f"{macro}_STRING_TOKEN": as_token,
657 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_STRING_UPPER_TOKEN
658 f"{macro}_STRING_UPPER_TOKEN": as_token.upper()}
659
660
661def enum_macros(prop: edtlib.Property, macro: str):
662 # Returns a dict of macros for property 'prop' with a defined enum in their dt-binding.
663 # The 'macro' argument is the N_<node-id>_P_<prop-id> part.
664
665 spec = prop.spec
666 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_ENUM_IDX
667 ret = {f"{macro}_IDX_{i}_ENUM_IDX": index for i, index in enumerate(prop.enum_indices)}
668 val = prop.val_as_tokens if spec.enum_tokenizable else (prop.val if isinstance(prop.val, list) else [prop.val])
669
670 for i, subval in enumerate(val):
671 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
672 ret[macro + f"_IDX_{i}_EXISTS"] = 1
673 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_ENUM_VAL_<val>_EXISTS 1
674 ret[macro + f"_IDX_{i}_ENUM_VAL_{subval}_EXISTS"] = 1
Joel Hirsbrunner8b02bc92024-10-04 21:29:37 +0200675
676 return ret
677
678
679def array_macros(prop: edtlib.Property, macro: str):
680 # Returns a dict of macros for array property 'prop'.
681 # The 'macro' argument is the N_<node-id>_P_<prop-id> part.
682
683 ret = {}
684 for i, subval in enumerate(prop.val):
685 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
686 ret[macro + f"_IDX_{i}_EXISTS"] = 1
687
688 # DT_N_<node-id>_P_<prop-id>_IDX_<i>
689 if isinstance(subval, str):
690 ret[macro + f"_IDX_{i}"] = quote_str(subval)
691 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_STRING_...
692 ret.update(string_macros(macro + f"_IDX_{i}", subval))
693 else:
694 ret[macro + f"_IDX_{i}"] = subval
695
696 return ret
697
698
Florian Grandelde846c72024-09-06 10:15:55 +0200699def write_dep_info(node: edtlib.Node) -> None:
Martí Bolívar305379e2020-06-08 14:59:19 -0700700 # Write dependency-related information about the node.
701
702 def fmt_dep_list(dep_list):
703 if dep_list:
704 # Sort the list by dependency ordinal for predictability.
705 sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
706 return "\\\n\t" + \
707 " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
708 for n in sorted_list)
709 else:
710 return "/* nothing */"
711
712 out_comment("Node's dependency ordinal:")
713 out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal)
Jordan Yatesb6e03412023-07-15 21:47:02 +1000714 out_dt_define(f"{node.z_path_id}_ORD_STR_SORTABLE", f"{node.dep_ordinal:0>5}")
Martí Bolívar305379e2020-06-08 14:59:19 -0700715
716 out_comment("Ordinals for what this node depends on directly:")
717 out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS",
718 fmt_dep_list(node.depends_on))
719
720 out_comment("Ordinals for what depends directly on this node:")
721 out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS",
722 fmt_dep_list(node.required_by))
723
724
Florian Grandelde846c72024-09-06 10:15:55 +0200725def prop2value(prop: edtlib.Property) -> edtlib.PropertyValType:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800726 # Gets the macro value for property 'prop', if there is
727 # a single well-defined C rvalue that it can be represented as.
728 # Returns None if there isn't one.
729
730 if prop.type == "string":
731 return quote_str(prop.val)
732
733 if prop.type == "int":
734 return prop.val
735
736 if prop.type == "boolean":
737 return 1 if prop.val else 0
738
739 if prop.type in ["array", "uint8-array"]:
740 return list2init(f"{val} /* {hex(val)} */" for val in prop.val)
741
742 if prop.type == "string-array":
743 return list2init(quote_str(val) for val in prop.val)
744
745 # phandle, phandles, phandle-array, path, compound: nothing
746 return None
747
748
Florian Grandelde846c72024-09-06 10:15:55 +0200749def prop_len(prop: edtlib.Property) -> Optional[int]:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800750 # Returns the property's length if and only if we should generate
751 # a _LEN macro for the property. Otherwise, returns None.
752 #
Martí Bolívar0c29e072023-05-06 14:42:15 -0700753 # The set of types handled here coincides with the allowable types
754 # that can be used with DT_PROP_LEN(). If you change this set,
755 # make sure to update the doxygen string for that macro, and make
756 # sure that DT_FOREACH_PROP_ELEM() works for the new types too.
757 #
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200758 # This deliberately excludes ranges, dma-ranges, reg and interrupts.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800759 # While they have array type, their lengths as arrays are
760 # basically nonsense semantically due to #address-cells and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200761 # #size-cells for "reg", #interrupt-cells for "interrupts"
762 # and #address-cells, #size-cells and the #address-cells from the
763 # parent node for "ranges" and "dma-ranges".
Martí Bolívardc85edd2020-02-28 15:26:52 -0800764 #
765 # We have special purpose macros for the number of register blocks
766 # / interrupt specifiers. Excluding them from this list means
767 # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer
768 # with a build error. This forces users to switch to the right
769 # macros.
770
Martí Bolívar8aa83f62023-05-05 15:48:53 -0700771 if prop.type in ["phandle", "string"]:
772 # phandle is treated as a phandles of length 1.
773 # string is treated as a string-array of length 1.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800774 return 1
775
776 if (prop.type in ["array", "uint8-array", "string-array",
777 "phandles", "phandle-array"] and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200778 prop.name not in ["ranges", "dma-ranges", "reg", "interrupts"]):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800779 return len(prop.val)
780
781 return None
782
783
Florian Grandelde846c72024-09-06 10:15:55 +0200784def phandle_macros(prop: edtlib.Property, macro: str) -> dict:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800785 # Returns a dict of macros for phandle or phandles property 'prop'.
786 #
787 # The 'macro' argument is the N_<node-id>_P_<prop-id> bit.
788 #
789 # These are currently special because we can't serialize their
790 # values without using label properties, which we're trying to get
791 # away from needing in Zephyr. (Label properties are great for
792 # humans, but have drawbacks for code size and boot time.)
793 #
794 # The names look a bit weird to make it easier for devicetree.h
795 # to use the same macros for phandle, phandles, and phandle-array.
796
797 ret = {}
798
799 if prop.type == "phandle":
800 # A phandle is treated as a phandles with fixed length 1.
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500801 ret[f"{macro}"] = f"DT_{prop.val.z_path_id}"
802 ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800803 ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800804 ret[f"{macro}_IDX_0_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800805 elif prop.type == "phandles":
806 for i, node in enumerate(prop.val):
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500807 ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800808 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800809 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800810 elif prop.type == "phandle-array":
811 for i, entry in enumerate(prop.val):
Martí Bolívar38ede5a2020-12-17 14:12:01 -0800812 if entry is None:
813 # Unspecified element. The phandle-array at this index
814 # does not point at a ControllerAndData value, but
815 # subsequent indices in the array may.
816 ret[f"{macro}_IDX_{i}_EXISTS"] = 0
817 continue
818
Martí Bolívardc85edd2020-02-28 15:26:52 -0800819 ret.update(controller_and_data_macros(entry, i, macro))
820
821 return ret
822
823
Florian Grandelde846c72024-09-06 10:15:55 +0200824def controller_and_data_macros(entry: edtlib.ControllerAndData, i: int, macro: str):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800825 # Helper procedure used by phandle_macros().
826 #
827 # Its purpose is to write the "controller" (i.e. label property of
828 # the phandle's node) and associated data macros for a
829 # ControllerAndData.
830
831 ret = {}
832 data = entry.data
833
Martí Bolívarffc03122020-11-12 20:27:20 -0800834 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
835 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800836 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH
837 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}"
838 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL>
839 for cell, val in data.items():
840 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val
841 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1
842
843 if not entry.name:
844 return ret
845
846 name = str2ident(entry.name)
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200847 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
848 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800849 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME
850 ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name)
851 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH
852 ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}"
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200853 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS
854 ret[f"{macro}_NAME_{name}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800855 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
856 for cell, val in data.items():
857 cell_ident = str2ident(cell)
858 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
859 f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
860 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1
861
862 return ret
863
864
Florian Grandelde846c72024-09-06 10:15:55 +0200865def write_chosen(edt: edtlib.EDT):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800866 # Tree-wide information such as chosen nodes is printed here.
867
868 out_comment("Chosen nodes\n")
869 chosen = {}
870 for name, node in edt.chosen_nodes.items():
871 chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}"
872 chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1
Kumar Gala299bfd02020-03-25 15:32:58 -0500873 max_len = max(map(len, chosen), default=0)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800874 for macro, value in chosen.items():
875 out_define(macro, value, width=max_len)
876
877
Florian Grandelde846c72024-09-06 10:15:55 +0200878def write_global_macros(edt: edtlib.EDT):
Martí Bolívar190197e2022-07-20 13:10:33 -0700879 # Global or tree-wide information, such as number of instances
880 # with status "okay" for each compatible, is printed here.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800881
Martí Bolívarf0d11f72022-07-20 13:15:56 -0700882
883 out_comment("Macros for iterating over all nodes and enabled nodes")
884 out_dt_define("FOREACH_HELPER(fn)",
885 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes))
886 out_dt_define("FOREACH_OKAY_HELPER(fn)",
887 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes
888 if node.status == "okay"))
Carlo Caione935268e2023-07-04 17:50:12 +0200889 out_dt_define("FOREACH_VARGS_HELPER(fn, ...)",
890 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)" for node in edt.nodes))
891 out_dt_define("FOREACH_OKAY_VARGS_HELPER(fn, ...)",
892 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)" for node in edt.nodes
893 if node.status == "okay"))
Martí Bolívarf0d11f72022-07-20 13:15:56 -0700894
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700895 n_okay_macros = {}
896 for_each_macros = {}
897 compat2buses = defaultdict(list) # just for "okay" nodes
898 for compat, okay_nodes in edt.compat2okay.items():
899 for node in okay_nodes:
Daniel Leung418c9152022-08-26 10:52:32 -0700900 buses = node.on_buses
901 for bus in buses:
902 if bus is not None and bus not in compat2buses[compat]:
903 compat2buses[compat].append(bus)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800904
Martí Bolívar63d55292020-04-06 15:13:53 -0700905 ident = str2ident(compat)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700906 n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes)
Martí Bolívare7d42ff2021-08-05 15:24:50 -0700907
908 # Helpers for non-INST for-each macros that take node
909 # identifiers as arguments.
910 for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
911 " ".join(f"fn(DT_{node.z_path_id})"
912 for node in okay_nodes)
913 for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
914 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
915 for node in okay_nodes)
916
917 # Helpers for INST versions of for-each macros, which take
918 # instance numbers. We emit separate helpers for these because
919 # avoiding an intermediate node_id --> instance number
920 # conversion in the preprocessor helps to keep the macro
921 # expansions simpler. That hopefully eases debugging.
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700922 for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
923 " ".join(f"fn({edt.compat2nodes[compat].index(node)})"
924 for node in okay_nodes)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400925 for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
926 " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
927 for node in okay_nodes)
928
Kumar Galabd973782020-05-06 20:54:29 -0500929 for compat, nodes in edt.compat2nodes.items():
930 for node in nodes:
931 if compat == "fixed-partitions":
932 for child in node.children.values():
933 if "label" in child.props:
934 label = child.props["label"].val
935 macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}"
936 val = f"DT_{child.z_path_id}"
937
938 out_dt_define(macro, val)
939 out_dt_define(macro + "_EXISTS", 1)
940
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700941 out_comment('Macros for compatibles with status "okay" nodes\n')
942 for compat, okay_nodes in edt.compat2okay.items():
943 if okay_nodes:
944 out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1)
945
946 out_comment('Macros for status "okay" instances of each compatible\n')
947 for macro, value in n_okay_macros.items():
Martí Bolívar63d55292020-04-06 15:13:53 -0700948 out_define(macro, value)
949 for macro, value in for_each_macros.items():
950 out_define(macro, value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800951
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700952 out_comment('Bus information for status "okay" nodes of each compatible\n')
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700953 for compat, buses in compat2buses.items():
954 for bus in buses:
955 out_define(
956 f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800957
Florian Grandelde846c72024-09-06 10:15:55 +0200958
959def str2ident(s: str) -> str:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800960 # Converts 's' to a form suitable for (part of) an identifier
961
962 return re.sub('[-,.@/+]', '_', s.lower())
963
964
Florian Grandelde846c72024-09-06 10:15:55 +0200965def list2init(l: Iterable[str]) -> str:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800966 # Converts 'l', a Python list (or iterable), to a C array initializer
967
968 return "{" + ", ".join(l) + "}"
969
970
Florian Grandelde846c72024-09-06 10:15:55 +0200971def out_dt_define(
972 macro: str,
973 val: str,
974 width: Optional[int] = None,
975 deprecation_msg: Optional[str] = None,
976) -> str:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800977 # Writes "#define DT_<macro> <val>" to the header file
978 #
979 # The macro will be left-justified to 'width' characters if that
980 # is specified, and the value will follow immediately after in
981 # that case. Otherwise, this function decides how to add
982 # whitespace between 'macro' and 'val'.
983 #
984 # If a 'deprecation_msg' string is passed, the generated identifiers will
985 # generate a warning if used, via __WARN(<deprecation_msg>)).
986 #
987 # Returns the full generated macro for 'macro', with leading "DT_".
988 ret = "DT_" + macro
989 out_define(ret, val, width=width, deprecation_msg=deprecation_msg)
990 return ret
991
992
Florian Grandelde846c72024-09-06 10:15:55 +0200993def out_define(
994 macro: str,
995 val: str,
996 width: Optional[int] = None,
997 deprecation_msg: Optional[str] = None,
998) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800999 # Helper for out_dt_define(). Outputs "#define <macro> <val>",
1000 # adds a deprecation message if given, and allocates whitespace
1001 # unless told not to.
1002
1003 warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else ""
1004
1005 if width:
1006 s = f"#define {macro.ljust(width)}{warn} {val}"
1007 else:
1008 s = f"#define {macro}{warn} {val}"
1009
1010 print(s, file=header_file)
1011
1012
Florian Grandelde846c72024-09-06 10:15:55 +02001013def out_comment(s: str, blank_before=True) -> None:
Martí Bolívardc85edd2020-02-28 15:26:52 -08001014 # Writes 's' as a comment to the header and configuration file. 's' is
1015 # allowed to have multiple lines. blank_before=True adds a blank line
1016 # before the comment.
1017
1018 if blank_before:
1019 print(file=header_file)
1020
1021 if "\n" in s:
1022 # Format multi-line comments like
1023 #
1024 # /*
1025 # * first line
1026 # * second line
1027 # *
1028 # * empty line before this line
1029 # */
1030 res = ["/*"]
1031 for line in s.splitlines():
1032 # Avoid an extra space after '*' for empty lines. They turn red in
1033 # Vim if space error checking is on, which is annoying.
1034 res.append(" *" if not line.strip() else " * " + line)
1035 res.append(" */")
1036 print("\n".join(res), file=header_file)
1037 else:
1038 # Format single-line comments like
1039 #
1040 # /* foo bar */
1041 print("/* " + s + " */", file=header_file)
1042
1043
Joel Spadin6edefd82024-09-14 20:17:32 -05001044ESCAPE_TABLE = str.maketrans(
1045 {
1046 "\n": "\\n",
1047 "\r": "\\r",
1048 "\\": "\\\\",
1049 '"': '\\"',
1050 }
1051)
Martí Bolívardc85edd2020-02-28 15:26:52 -08001052
Joel Spadin6edefd82024-09-14 20:17:32 -05001053
1054def escape(s: str) -> str:
1055 # Backslash-escapes any double quotes, backslashes, and new lines in 's'
1056
1057 return s.translate(ESCAPE_TABLE)
Martí Bolívardc85edd2020-02-28 15:26:52 -08001058
1059
Florian Grandelde846c72024-09-06 10:15:55 +02001060def quote_str(s: str) -> str:
Martí Bolívardc85edd2020-02-28 15:26:52 -08001061 # Puts quotes around 's' and escapes any double quotes and
1062 # backslashes within it
1063
1064 return f'"{escape(s)}"'
1065
1066
Joel Spadin6edefd82024-09-14 20:17:32 -05001067def escape_unquoted(s: str) -> str:
1068 # C macros cannot contain line breaks, so replace them with spaces.
1069 # Whitespace is used to separate preprocessor tokens, but it does not matter
1070 # which whitespace characters are used, so a line break and a space are
1071 # equivalent with regards to unquoted strings being used as C code.
1072
1073 return s.replace("\r", " ").replace("\n", " ")
1074
1075
Florian Grandelde846c72024-09-06 10:15:55 +02001076def err(s: str) -> NoReturn:
Martí Bolívardc85edd2020-02-28 15:26:52 -08001077 raise Exception(s)
1078
1079
1080if __name__ == "__main__":
1081 main()