Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 1 | #!/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 | |
| 21 | import argparse |
Martí Bolívar | a3fae2f | 2020-03-25 14:18:27 -0700 | [diff] [blame] | 22 | from collections import defaultdict |
Martí Bolívar | 0985849 | 2020-12-08 09:41:49 -0800 | [diff] [blame] | 23 | import logging |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 24 | import os |
| 25 | import pathlib |
Martí Bolívar | 533f451 | 2020-07-01 10:43:43 -0700 | [diff] [blame] | 26 | import pickle |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 27 | import re |
| 28 | import sys |
| 29 | |
Martí Bolívar | 5332847 | 2021-03-26 16:18:58 -0700 | [diff] [blame] | 30 | sys.path.append(os.path.join(os.path.dirname(__file__), 'python-devicetree', |
| 31 | 'src')) |
| 32 | |
| 33 | from devicetree import edtlib |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 34 | |
Martí Bolívar | 9c229a4 | 2021-04-14 15:26:42 -0700 | [diff] [blame] | 35 | # 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. |
| 38 | FOREACH_PROP_ELEM_TYPES = set(['string', 'array', 'uint8-array', 'string-array', |
| 39 | 'phandles', 'phandle-array']) |
| 40 | |
Martí Bolívar | 0985849 | 2020-12-08 09:41:49 -0800 | [diff] [blame] | 41 | class 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ívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 52 | def main(): |
| 53 | global header_file |
Kumar Gala | bd97378 | 2020-05-06 20:54:29 -0500 | [diff] [blame] | 54 | global flash_area_num |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 55 | |
| 56 | args = parse_args() |
| 57 | |
Martí Bolívar | 0985849 | 2020-12-08 09:41:49 -0800 | [diff] [blame] | 58 | setup_edtlib_logging() |
| 59 | |
Martí Bolívar | f261d77 | 2021-05-18 15:09:49 -0700 | [diff] [blame] | 60 | if args.vendor_prefixes: |
| 61 | vendor_prefixes = edtlib.load_vendor_prefixes_txt(args.vendor_prefixes) |
| 62 | else: |
| 63 | vendor_prefixes = None |
| 64 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 65 | try: |
| 66 | edt = edtlib.EDT(args.dts, args.bindings_dirs, |
| 67 | # Suppress this warning if it's suppressed in dtc |
| 68 | warn_reg_unit_address_mismatch= |
Kumar Gala | bc48f1c | 2020-05-01 12:33:00 -0500 | [diff] [blame] | 69 | "-Wno-simple_bus_reg" not in args.dtc_flags, |
Peter Bigot | 932532e | 2020-09-02 05:05:19 -0500 | [diff] [blame] | 70 | default_prop_types=True, |
Martí Bolívar | df5a55c | 2021-02-14 17:52:57 -0800 | [diff] [blame] | 71 | infer_binding_for_paths=["/zephyr,user"], |
Martí Bolívar | c4079e4 | 2021-07-30 15:43:27 -0700 | [diff] [blame] | 72 | werror=args.edtlib_Werror, |
Martí Bolívar | f261d77 | 2021-05-18 15:09:49 -0700 | [diff] [blame] | 73 | vendor_prefixes=vendor_prefixes) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 74 | except edtlib.EDTError as e: |
| 75 | sys.exit(f"devicetree error: {e}") |
| 76 | |
Kumar Gala | bd97378 | 2020-05-06 20:54:29 -0500 | [diff] [blame] | 77 | flash_area_num = 0 |
| 78 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 79 | # Save merged DTS source, as a debugging aid |
| 80 | with open(args.dts_out, "w", encoding="utf-8") as f: |
| 81 | print(edt.dts_source, file=f) |
| 82 | |
Martí Bolívar | e96ca54 | 2020-05-07 12:07:02 -0700 | [diff] [blame] | 83 | # The raw index into edt.compat2nodes[compat] is used for node |
| 84 | # instance numbering within a compatible. |
| 85 | # |
| 86 | # As a way to satisfy people's intuitions about instance numbers, |
| 87 | # though, we sort this list so enabled instances come first. |
| 88 | # |
| 89 | # This might look like a hack, but it keeps drivers and |
| 90 | # applications which don't use instance numbers carefully working |
| 91 | # as expected, since e.g. instance number 0 is always the |
| 92 | # singleton instance if there's just one enabled node of a |
| 93 | # particular compatible. |
| 94 | # |
| 95 | # This doesn't violate any devicetree.h API guarantees about |
| 96 | # instance ordering, since we make no promises that instance |
| 97 | # numbers are stable across builds. |
| 98 | for compat, nodes in edt.compat2nodes.items(): |
| 99 | edt.compat2nodes[compat] = sorted( |
| 100 | nodes, key=lambda node: 0 if node.status == "okay" else 1) |
| 101 | |
Martí Bolívar | 533f451 | 2020-07-01 10:43:43 -0700 | [diff] [blame] | 102 | # Create the generated header. |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 103 | with open(args.header_out, "w", encoding="utf-8") as header_file: |
| 104 | write_top_comment(edt) |
| 105 | |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 106 | # populate all z_path_id first so any children references will |
| 107 | # work correctly. |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 108 | for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal): |
Martí Bolívar | 186bace | 2020-04-08 15:02:18 -0700 | [diff] [blame] | 109 | node.z_path_id = node_z_path_id(node) |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 110 | |
| 111 | for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal): |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 112 | write_node_comment(node) |
| 113 | |
Kumar Gala | 270a05f | 2021-02-24 11:28:21 -0600 | [diff] [blame] | 114 | out_comment("Node's full path:") |
Martí Bolívar | 00ffc7e | 2020-12-13 12:27:04 -0800 | [diff] [blame] | 115 | out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"') |
| 116 | |
Kumar Gala | 4aac908 | 2021-02-24 10:44:07 -0600 | [diff] [blame] | 117 | out_comment("Node's name with unit-address:") |
| 118 | out_dt_define(f"{node.z_path_id}_FULL_NAME", |
| 119 | f'"{escape(node.name)}"') |
| 120 | |
Martí Bolívar | 6e27343 | 2020-04-08 15:04:15 -0700 | [diff] [blame] | 121 | if node.parent is not None: |
| 122 | out_comment(f"Node parent ({node.parent.path}) identifier:") |
| 123 | out_dt_define(f"{node.z_path_id}_PARENT", |
| 124 | f"DT_{node.parent.z_path_id}") |
| 125 | |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 126 | write_child_functions(node) |
Hou Zhiqiang | 0700a24 | 2021-04-26 16:22:38 +0800 | [diff] [blame] | 127 | write_child_functions_status_okay(node) |
Martí Bolívar | 305379e | 2020-06-08 14:59:19 -0700 | [diff] [blame] | 128 | write_dep_info(node) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 129 | write_idents_and_existence(node) |
| 130 | write_bus(node) |
| 131 | write_special_props(node) |
| 132 | write_vanilla_props(node) |
| 133 | |
| 134 | write_chosen(edt) |
Martí Bolívar | a3fae2f | 2020-03-25 14:18:27 -0700 | [diff] [blame] | 135 | write_global_compat_info(edt) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 136 | |
Kumar Gala | 98b6e4f | 2021-01-13 11:06:46 -0600 | [diff] [blame] | 137 | write_device_extern_header(args.device_header_out, edt) |
| 138 | |
Martí Bolívar | 533f451 | 2020-07-01 10:43:43 -0700 | [diff] [blame] | 139 | if args.edt_pickle_out: |
| 140 | write_pickled_edt(edt, args.edt_pickle_out) |
| 141 | |
Kumar Gala | 98b6e4f | 2021-01-13 11:06:46 -0600 | [diff] [blame] | 142 | |
| 143 | def write_device_extern_header(device_header_out, edt): |
| 144 | # Generate header that will extern devicetree struct device's |
| 145 | |
| 146 | with open(device_header_out, "w", encoding="utf-8") as dev_header_file: |
| 147 | print("#ifndef DEVICE_EXTERN_GEN_H", file=dev_header_file) |
| 148 | print("#define DEVICE_EXTERN_GEN_H", file=dev_header_file) |
| 149 | print("", file=dev_header_file) |
| 150 | print("#ifdef __cplusplus", file=dev_header_file) |
| 151 | print('extern "C" {', file=dev_header_file) |
| 152 | print("#endif", file=dev_header_file) |
| 153 | print("", file=dev_header_file) |
| 154 | |
| 155 | for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal): |
Peter Bigot | f91e9fb | 2021-01-23 07:56:09 -0600 | [diff] [blame] | 156 | print(f"extern const struct device DEVICE_DT_NAME_GET(DT_{node.z_path_id}); /* dts_ord_{node.dep_ordinal} */", |
| 157 | file=dev_header_file) |
Kumar Gala | 98b6e4f | 2021-01-13 11:06:46 -0600 | [diff] [blame] | 158 | |
| 159 | print("", file=dev_header_file) |
| 160 | print("#ifdef __cplusplus", file=dev_header_file) |
| 161 | print("}", file=dev_header_file) |
| 162 | print("#endif", file=dev_header_file) |
| 163 | print("", file=dev_header_file) |
| 164 | print("#endif /* DEVICE_EXTERN_GEN_H */", file=dev_header_file) |
| 165 | |
| 166 | |
Martí Bolívar | 0985849 | 2020-12-08 09:41:49 -0800 | [diff] [blame] | 167 | def setup_edtlib_logging(): |
| 168 | # The edtlib module emits logs using the standard 'logging' module. |
| 169 | # Configure it so that warnings and above are printed to stderr, |
| 170 | # using the LogFormatter class defined above to format each message. |
| 171 | |
| 172 | handler = logging.StreamHandler(sys.stderr) |
| 173 | handler.setFormatter(LogFormatter()) |
| 174 | |
| 175 | logger = logging.getLogger('edtlib') |
| 176 | logger.setLevel(logging.WARNING) |
| 177 | logger.addHandler(handler) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 178 | |
Martí Bolívar | 186bace | 2020-04-08 15:02:18 -0700 | [diff] [blame] | 179 | def node_z_path_id(node): |
| 180 | # Return the node specific bit of the node's path identifier: |
| 181 | # |
| 182 | # - the root node's path "/" has path identifier "N" |
| 183 | # - "/foo" has "N_S_foo" |
| 184 | # - "/foo/bar" has "N_S_foo_S_bar" |
| 185 | # - "/foo/bar@123" has "N_S_foo_S_bar_123" |
| 186 | # |
| 187 | # This is used throughout this file to generate macros related to |
| 188 | # the node. |
| 189 | |
| 190 | components = ["N"] |
| 191 | if node.parent is not None: |
| 192 | components.extend(f"S_{str2ident(component)}" for component in |
| 193 | node.path.split("/")[1:]) |
| 194 | |
| 195 | return "_".join(components) |
| 196 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 197 | def parse_args(): |
| 198 | # Returns parsed command-line arguments |
| 199 | |
| 200 | parser = argparse.ArgumentParser() |
| 201 | parser.add_argument("--dts", required=True, help="DTS file") |
| 202 | parser.add_argument("--dtc-flags", |
| 203 | help="'dtc' devicetree compiler flags, some of which " |
| 204 | "might be respected here") |
| 205 | parser.add_argument("--bindings-dirs", nargs='+', required=True, |
| 206 | help="directory with bindings in YAML format, " |
| 207 | "we allow multiple") |
| 208 | parser.add_argument("--header-out", required=True, |
| 209 | help="path to write header to") |
| 210 | parser.add_argument("--dts-out", required=True, |
| 211 | help="path to write merged DTS source code to (e.g. " |
| 212 | "as a debugging aid)") |
Kumar Gala | 98b6e4f | 2021-01-13 11:06:46 -0600 | [diff] [blame] | 213 | parser.add_argument("--device-header-out", required=True, |
| 214 | help="path to write device struct extern header to") |
Martí Bolívar | 533f451 | 2020-07-01 10:43:43 -0700 | [diff] [blame] | 215 | parser.add_argument("--edt-pickle-out", |
| 216 | help="path to write pickled edtlib.EDT object to") |
Martí Bolívar | f261d77 | 2021-05-18 15:09:49 -0700 | [diff] [blame] | 217 | parser.add_argument("--vendor-prefixes", |
| 218 | help="vendor-prefixes.txt path; used for validation") |
Martí Bolívar | c4079e4 | 2021-07-30 15:43:27 -0700 | [diff] [blame] | 219 | parser.add_argument("--edtlib-Werror", action="store_true", |
| 220 | help="if set, edtlib-specific warnings become errors. " |
| 221 | "(this does not apply to warnings shared " |
| 222 | "with dtc.)") |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 223 | |
| 224 | return parser.parse_args() |
| 225 | |
| 226 | |
| 227 | def write_top_comment(edt): |
| 228 | # Writes an overview comment with misc. info at the top of the header and |
| 229 | # configuration file |
| 230 | |
| 231 | s = f"""\ |
| 232 | Generated by gen_defines.py |
| 233 | |
| 234 | DTS input file: |
| 235 | {edt.dts_path} |
| 236 | |
| 237 | Directories with bindings: |
| 238 | {", ".join(map(relativize, edt.bindings_dirs))} |
| 239 | |
Martí Bolívar | 305379e | 2020-06-08 14:59:19 -0700 | [diff] [blame] | 240 | Node dependency ordering (ordinal and path): |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 241 | """ |
| 242 | |
Martí Bolívar | b6db201 | 2020-08-24 13:33:53 -0700 | [diff] [blame] | 243 | for scc in edt.scc_order: |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 244 | if len(scc) > 1: |
| 245 | err("cycle in devicetree involving " |
| 246 | + ", ".join(node.path for node in scc)) |
| 247 | s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n" |
| 248 | |
| 249 | s += """ |
| 250 | Definitions derived from these nodes in dependency order are next, |
| 251 | followed by /chosen nodes. |
| 252 | """ |
| 253 | |
| 254 | out_comment(s, blank_before=False) |
| 255 | |
| 256 | |
| 257 | def write_node_comment(node): |
| 258 | # Writes a comment describing 'node' to the header and configuration file |
| 259 | |
| 260 | s = f"""\ |
Martí Bolívar | b6e6ba0 | 2020-04-08 15:09:46 -0700 | [diff] [blame] | 261 | Devicetree node: {node.path} |
| 262 | |
Martí Bolívar | 305379e | 2020-06-08 14:59:19 -0700 | [diff] [blame] | 263 | Node identifier: DT_{node.z_path_id} |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 264 | """ |
| 265 | |
| 266 | if node.matching_compat: |
Peter Bigot | 932532e | 2020-09-02 05:05:19 -0500 | [diff] [blame] | 267 | if node.binding_path: |
| 268 | s += f""" |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 269 | Binding (compatible = {node.matching_compat}): |
| 270 | {relativize(node.binding_path)} |
| 271 | """ |
Peter Bigot | 932532e | 2020-09-02 05:05:19 -0500 | [diff] [blame] | 272 | else: |
| 273 | s += f""" |
| 274 | Binding (compatible = {node.matching_compat}): |
| 275 | No yaml (bindings inferred from properties) |
| 276 | """ |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 277 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 278 | if node.description: |
Martí Bolívar | f7d33f2 | 2020-10-30 17:45:27 -0700 | [diff] [blame] | 279 | # We used to put descriptions in the generated file, but |
| 280 | # devicetree bindings now have pages in the HTML |
| 281 | # documentation. Let users who are accustomed to digging |
| 282 | # around in the generated file where to find the descriptions |
| 283 | # now. |
| 284 | # |
| 285 | # Keeping them here would mean that the descriptions |
| 286 | # themselves couldn't contain C multi-line comments, which is |
| 287 | # inconvenient when we want to do things like quote snippets |
| 288 | # of .dtsi files within the descriptions, or otherwise |
| 289 | # include the string "*/". |
| 290 | s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n" |
| 291 | "in the documentation.)\n") |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 292 | |
| 293 | out_comment(s) |
| 294 | |
| 295 | |
| 296 | def relativize(path): |
| 297 | # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE, |
| 298 | # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise, |
| 299 | # returns 'path' unchanged. |
| 300 | |
| 301 | zbase = os.getenv("ZEPHYR_BASE") |
| 302 | if zbase is None: |
| 303 | return path |
| 304 | |
| 305 | try: |
| 306 | return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase)) |
| 307 | except ValueError: |
| 308 | # Not within ZEPHYR_BASE |
| 309 | return path |
| 310 | |
| 311 | |
| 312 | def write_idents_and_existence(node): |
| 313 | # Writes macros related to the node's aliases, labels, etc., |
| 314 | # as well as existence flags. |
| 315 | |
| 316 | # Aliases |
| 317 | idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases] |
| 318 | # Instances |
| 319 | for compat in node.compats: |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 320 | instance_no = node.edt.compat2nodes[compat].index(node) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 321 | idents.append(f"N_INST_{instance_no}_{str2ident(compat)}") |
| 322 | # Node labels |
| 323 | idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels) |
| 324 | |
| 325 | out_comment("Existence and alternate IDs:") |
| 326 | out_dt_define(node.z_path_id + "_EXISTS", 1) |
| 327 | |
| 328 | # Only determine maxlen if we have any idents |
| 329 | if idents: |
| 330 | maxlen = max(len("DT_" + ident) for ident in idents) |
| 331 | for ident in idents: |
| 332 | out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen) |
| 333 | |
| 334 | |
| 335 | def write_bus(node): |
| 336 | # Macros about the node's bus controller, if there is one |
| 337 | |
| 338 | bus = node.bus_node |
| 339 | if not bus: |
| 340 | return |
| 341 | |
| 342 | if not bus.label: |
| 343 | err(f"missing 'label' property on bus node {bus!r}") |
| 344 | |
| 345 | out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_bus}')") |
| 346 | out_dt_define(f"{node.z_path_id}_BUS_{str2ident(node.on_bus)}", 1) |
| 347 | out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}") |
| 348 | |
| 349 | |
| 350 | def write_special_props(node): |
| 351 | # Writes required macros for special case properties, when the |
| 352 | # data cannot otherwise be obtained from write_vanilla_props() |
| 353 | # results |
| 354 | |
Kumar Gala | bd97378 | 2020-05-06 20:54:29 -0500 | [diff] [blame] | 355 | global flash_area_num |
| 356 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 357 | out_comment("Special property macros:") |
| 358 | |
| 359 | # Macros that are special to the devicetree specification |
| 360 | write_regs(node) |
| 361 | write_interrupts(node) |
| 362 | write_compatibles(node) |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 363 | write_status(node) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 364 | |
Kumar Gala | bd97378 | 2020-05-06 20:54:29 -0500 | [diff] [blame] | 365 | if node.parent and "fixed-partitions" in node.parent.compats: |
| 366 | macro = f"{node.z_path_id}_PARTITION_ID" |
| 367 | out_dt_define(macro, flash_area_num) |
| 368 | flash_area_num += 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 369 | |
| 370 | def write_regs(node): |
| 371 | # reg property: edtlib knows the right #address-cells and |
| 372 | # #size-cells, and can therefore pack the register base addresses |
| 373 | # and sizes correctly |
| 374 | |
| 375 | idx_vals = [] |
| 376 | name_vals = [] |
| 377 | path_id = node.z_path_id |
| 378 | |
| 379 | if node.regs is not None: |
| 380 | idx_vals.append((f"{path_id}_REG_NUM", len(node.regs))) |
| 381 | |
| 382 | for i, reg in enumerate(node.regs): |
Kumar Gala | 4e2ad00 | 2020-04-14 14:27:20 -0500 | [diff] [blame] | 383 | idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1)) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 384 | if reg.addr is not None: |
| 385 | idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS" |
| 386 | idx_vals.append((idx_macro, |
| 387 | f"{reg.addr} /* {hex(reg.addr)} */")) |
| 388 | if reg.name: |
| 389 | name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS" |
| 390 | name_vals.append((name_macro, f"DT_{idx_macro}")) |
| 391 | |
| 392 | if reg.size is not None: |
| 393 | idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE" |
| 394 | idx_vals.append((idx_macro, |
| 395 | f"{reg.size} /* {hex(reg.size)} */")) |
| 396 | if reg.name: |
| 397 | name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE" |
| 398 | name_vals.append((name_macro, f"DT_{idx_macro}")) |
| 399 | |
| 400 | for macro, val in idx_vals: |
| 401 | out_dt_define(macro, val) |
| 402 | for macro, val in name_vals: |
| 403 | out_dt_define(macro, val) |
| 404 | |
| 405 | def write_interrupts(node): |
| 406 | # interrupts property: we have some hard-coded logic for interrupt |
| 407 | # mapping here. |
| 408 | # |
| 409 | # TODO: can we push map_arm_gic_irq_type() and |
| 410 | # encode_zephyr_multi_level_irq() out of Python and into C with |
| 411 | # macro magic in devicetree.h? |
| 412 | |
| 413 | def map_arm_gic_irq_type(irq, irq_num): |
| 414 | # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number |
| 415 | if "type" not in irq.data: |
| 416 | err(f"Expected binding for {irq.controller!r} to have 'type' in " |
| 417 | "interrupt-cells") |
| 418 | irq_type = irq.data["type"] |
| 419 | |
| 420 | if irq_type == 0: # GIC_SPI |
| 421 | return irq_num + 32 |
| 422 | if irq_type == 1: # GIC_PPI |
| 423 | return irq_num + 16 |
| 424 | err(f"Invalid interrupt type specified for {irq!r}") |
| 425 | |
| 426 | def encode_zephyr_multi_level_irq(irq, irq_num): |
| 427 | # See doc/reference/kernel/other/interrupts.rst for details |
| 428 | # on how this encoding works |
| 429 | |
| 430 | irq_ctrl = irq.controller |
| 431 | # Look for interrupt controller parent until we have none |
| 432 | while irq_ctrl.interrupts: |
| 433 | irq_num = (irq_num + 1) << 8 |
| 434 | if "irq" not in irq_ctrl.interrupts[0].data: |
| 435 | err(f"Expected binding for {irq_ctrl!r} to have 'irq' in " |
| 436 | "interrupt-cells") |
| 437 | irq_num |= irq_ctrl.interrupts[0].data["irq"] |
| 438 | irq_ctrl = irq_ctrl.interrupts[0].controller |
| 439 | return irq_num |
| 440 | |
| 441 | idx_vals = [] |
| 442 | name_vals = [] |
| 443 | path_id = node.z_path_id |
| 444 | |
| 445 | if node.interrupts is not None: |
| 446 | idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts))) |
| 447 | |
| 448 | for i, irq in enumerate(node.interrupts): |
| 449 | for cell_name, cell_value in irq.data.items(): |
| 450 | name = str2ident(cell_name) |
| 451 | |
| 452 | if cell_name == "irq": |
| 453 | if "arm,gic" in irq.controller.compats: |
| 454 | cell_value = map_arm_gic_irq_type(irq, cell_value) |
| 455 | cell_value = encode_zephyr_multi_level_irq(irq, cell_value) |
| 456 | |
Kumar Gala | 4e2ad00 | 2020-04-14 14:27:20 -0500 | [diff] [blame] | 457 | idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1)) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 458 | idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}" |
| 459 | idx_vals.append((idx_macro, cell_value)) |
| 460 | idx_vals.append((idx_macro + "_EXISTS", 1)) |
| 461 | if irq.name: |
| 462 | name_macro = \ |
| 463 | f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}" |
| 464 | name_vals.append((name_macro, f"DT_{idx_macro}")) |
| 465 | name_vals.append((name_macro + "_EXISTS", 1)) |
| 466 | |
| 467 | for macro, val in idx_vals: |
| 468 | out_dt_define(macro, val) |
| 469 | for macro, val in name_vals: |
| 470 | out_dt_define(macro, val) |
| 471 | |
| 472 | |
| 473 | def write_compatibles(node): |
| 474 | # Writes a macro for each of the node's compatibles. We don't care |
| 475 | # about whether edtlib / Zephyr's binding language recognizes |
| 476 | # them. The compatibles the node provides are what is important. |
| 477 | |
| 478 | for compat in node.compats: |
| 479 | out_dt_define( |
| 480 | f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1) |
| 481 | |
| 482 | |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 483 | def write_child_functions(node): |
| 484 | # Writes macro that are helpers that will call a macro/function |
| 485 | # for each child node. |
| 486 | |
Kumar Gala | 4a5a90a | 2020-05-08 12:25:25 -0500 | [diff] [blame] | 487 | out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)", |
| 488 | " ".join(f"fn(DT_{child.z_path_id})" for child in |
| 489 | node.children.values())) |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 490 | |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 491 | out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)", |
| 492 | " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)" for child in |
| 493 | node.children.values())) |
Dominik Ermel | ba8b74d | 2020-04-17 06:32:28 +0000 | [diff] [blame] | 494 | |
Hou Zhiqiang | 0700a24 | 2021-04-26 16:22:38 +0800 | [diff] [blame] | 495 | def write_child_functions_status_okay(node): |
| 496 | # Writes macro that are helpers that will call a macro/function |
| 497 | # for each child node with status "okay". |
| 498 | |
| 499 | functions = '' |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 500 | functions_args = '' |
Hou Zhiqiang | 0700a24 | 2021-04-26 16:22:38 +0800 | [diff] [blame] | 501 | for child in node.children.values(): |
| 502 | if child.status == "okay": |
| 503 | functions = functions + f"fn(DT_{child.z_path_id}) " |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 504 | functions_args = functions_args + f"fn(DT_{child.z_path_id}, " \ |
| 505 | "__VA_ARGS__) " |
Hou Zhiqiang | 0700a24 | 2021-04-26 16:22:38 +0800 | [diff] [blame] | 506 | |
| 507 | out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)", functions) |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 508 | out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)", |
| 509 | functions_args) |
Hou Zhiqiang | 0700a24 | 2021-04-26 16:22:38 +0800 | [diff] [blame] | 510 | |
| 511 | |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 512 | def write_status(node): |
| 513 | out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1) |
| 514 | |
| 515 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 516 | def write_vanilla_props(node): |
| 517 | # Writes macros for any and all properties defined in the |
| 518 | # "properties" section of the binding for the node. |
| 519 | # |
| 520 | # This does generate macros for special properties as well, like |
| 521 | # regs, etc. Just let that be rather than bothering to add |
| 522 | # never-ending amounts of special case code here to skip special |
| 523 | # properties. This function's macros can't conflict with |
| 524 | # write_special_props() macros, because they're in different |
| 525 | # namespaces. Special cases aren't special enough to break the rules. |
| 526 | |
| 527 | macro2val = {} |
| 528 | for prop_name, prop in node.props.items(): |
Martí Bolívar | 9c229a4 | 2021-04-14 15:26:42 -0700 | [diff] [blame] | 529 | prop_id = str2ident(prop_name) |
| 530 | macro = f"{node.z_path_id}_P_{prop_id}" |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 531 | val = prop2value(prop) |
| 532 | if val is not None: |
| 533 | # DT_N_<node-id>_P_<prop-id> |
| 534 | macro2val[macro] = val |
| 535 | |
Carlo Caione | f4db14f | 2021-05-17 17:24:27 +0200 | [diff] [blame] | 536 | if prop.spec.type == 'string': |
| 537 | macro2val[macro + "_STRING_TOKEN"] = prop.val_as_token |
| 538 | macro2val[macro + "_STRING_UPPER_TOKEN"] = prop.val_as_token.upper() |
| 539 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 540 | if prop.enum_index is not None: |
| 541 | # DT_N_<node-id>_P_<prop-id>_ENUM_IDX |
| 542 | macro2val[macro + "_ENUM_IDX"] = prop.enum_index |
Peter Bigot | 345da78 | 2020-12-02 09:04:27 -0600 | [diff] [blame] | 543 | spec = prop.spec |
| 544 | |
| 545 | if spec.enum_tokenizable: |
| 546 | as_token = prop.val_as_token |
| 547 | |
| 548 | # DT_N_<node-id>_P_<prop-id>_ENUM_TOKEN |
| 549 | macro2val[macro + "_ENUM_TOKEN"] = as_token |
| 550 | |
| 551 | if spec.enum_upper_tokenizable: |
| 552 | # DT_N_<node-id>_P_<prop-id>_ENUM_UPPER_TOKEN |
| 553 | macro2val[macro + "_ENUM_UPPER_TOKEN"] = as_token.upper() |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 554 | |
| 555 | if "phandle" in prop.type: |
| 556 | macro2val.update(phandle_macros(prop, macro)) |
| 557 | elif "array" in prop.type: |
| 558 | # DT_N_<node-id>_P_<prop-id>_IDX_<i> |
Martí Bolívar | ffc0312 | 2020-11-12 20:27:20 -0800 | [diff] [blame] | 559 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 560 | for i, subval in enumerate(prop.val): |
| 561 | if isinstance(subval, str): |
| 562 | macro2val[macro + f"_IDX_{i}"] = quote_str(subval) |
| 563 | else: |
| 564 | macro2val[macro + f"_IDX_{i}"] = subval |
Martí Bolívar | ffc0312 | 2020-11-12 20:27:20 -0800 | [diff] [blame] | 565 | macro2val[macro + f"_IDX_{i}_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 566 | |
Martí Bolívar | 9c229a4 | 2021-04-14 15:26:42 -0700 | [diff] [blame] | 567 | if prop.type in FOREACH_PROP_ELEM_TYPES: |
| 568 | # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM |
| 569 | macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \ |
| 570 | ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i})' |
| 571 | for i in range(len(prop.val))) |
| 572 | |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 573 | macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \ |
| 574 | ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i},' |
| 575 | ' __VA_ARGS__)' |
| 576 | for i in range(len(prop.val))) |
| 577 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 578 | plen = prop_len(prop) |
| 579 | if plen is not None: |
| 580 | # DT_N_<node-id>_P_<prop-id>_LEN |
| 581 | macro2val[macro + "_LEN"] = plen |
| 582 | |
| 583 | macro2val[f"{macro}_EXISTS"] = 1 |
| 584 | |
| 585 | if macro2val: |
| 586 | out_comment("Generic property macros:") |
| 587 | for macro, val in macro2val.items(): |
| 588 | out_dt_define(macro, val) |
| 589 | else: |
| 590 | out_comment("(No generic property macros)") |
| 591 | |
| 592 | |
Martí Bolívar | 305379e | 2020-06-08 14:59:19 -0700 | [diff] [blame] | 593 | def write_dep_info(node): |
| 594 | # Write dependency-related information about the node. |
| 595 | |
| 596 | def fmt_dep_list(dep_list): |
| 597 | if dep_list: |
| 598 | # Sort the list by dependency ordinal for predictability. |
| 599 | sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal) |
| 600 | return "\\\n\t" + \ |
| 601 | " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */" |
| 602 | for n in sorted_list) |
| 603 | else: |
| 604 | return "/* nothing */" |
| 605 | |
| 606 | out_comment("Node's dependency ordinal:") |
| 607 | out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal) |
| 608 | |
| 609 | out_comment("Ordinals for what this node depends on directly:") |
| 610 | out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS", |
| 611 | fmt_dep_list(node.depends_on)) |
| 612 | |
| 613 | out_comment("Ordinals for what depends directly on this node:") |
| 614 | out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS", |
| 615 | fmt_dep_list(node.required_by)) |
| 616 | |
| 617 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 618 | def prop2value(prop): |
| 619 | # Gets the macro value for property 'prop', if there is |
| 620 | # a single well-defined C rvalue that it can be represented as. |
| 621 | # Returns None if there isn't one. |
| 622 | |
| 623 | if prop.type == "string": |
| 624 | return quote_str(prop.val) |
| 625 | |
| 626 | if prop.type == "int": |
| 627 | return prop.val |
| 628 | |
| 629 | if prop.type == "boolean": |
| 630 | return 1 if prop.val else 0 |
| 631 | |
| 632 | if prop.type in ["array", "uint8-array"]: |
| 633 | return list2init(f"{val} /* {hex(val)} */" for val in prop.val) |
| 634 | |
| 635 | if prop.type == "string-array": |
| 636 | return list2init(quote_str(val) for val in prop.val) |
| 637 | |
| 638 | # phandle, phandles, phandle-array, path, compound: nothing |
| 639 | return None |
| 640 | |
| 641 | |
| 642 | def prop_len(prop): |
| 643 | # Returns the property's length if and only if we should generate |
| 644 | # a _LEN macro for the property. Otherwise, returns None. |
| 645 | # |
| 646 | # This deliberately excludes reg and interrupts. |
| 647 | # While they have array type, their lengths as arrays are |
| 648 | # basically nonsense semantically due to #address-cells and |
| 649 | # #size-cells for "reg" and #interrupt-cells for "interrupts". |
| 650 | # |
| 651 | # We have special purpose macros for the number of register blocks |
| 652 | # / interrupt specifiers. Excluding them from this list means |
| 653 | # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer |
| 654 | # with a build error. This forces users to switch to the right |
| 655 | # macros. |
| 656 | |
| 657 | if prop.type == "phandle": |
| 658 | return 1 |
| 659 | |
| 660 | if (prop.type in ["array", "uint8-array", "string-array", |
| 661 | "phandles", "phandle-array"] and |
| 662 | prop.name not in ["reg", "interrupts"]): |
| 663 | return len(prop.val) |
| 664 | |
| 665 | return None |
| 666 | |
| 667 | |
| 668 | def phandle_macros(prop, macro): |
| 669 | # Returns a dict of macros for phandle or phandles property 'prop'. |
| 670 | # |
| 671 | # The 'macro' argument is the N_<node-id>_P_<prop-id> bit. |
| 672 | # |
| 673 | # These are currently special because we can't serialize their |
| 674 | # values without using label properties, which we're trying to get |
| 675 | # away from needing in Zephyr. (Label properties are great for |
| 676 | # humans, but have drawbacks for code size and boot time.) |
| 677 | # |
| 678 | # The names look a bit weird to make it easier for devicetree.h |
| 679 | # to use the same macros for phandle, phandles, and phandle-array. |
| 680 | |
| 681 | ret = {} |
| 682 | |
| 683 | if prop.type == "phandle": |
| 684 | # A phandle is treated as a phandles with fixed length 1. |
Kumar Gala | 7b9fbcd | 2021-08-12 14:57:49 -0500 | [diff] [blame^] | 685 | ret[f"{macro}"] = f"DT_{prop.val.z_path_id}" |
| 686 | ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}" |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 687 | ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}" |
Martí Bolívar | ffc0312 | 2020-11-12 20:27:20 -0800 | [diff] [blame] | 688 | ret[f"{macro}_IDX_0_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 689 | elif prop.type == "phandles": |
| 690 | for i, node in enumerate(prop.val): |
Kumar Gala | 7b9fbcd | 2021-08-12 14:57:49 -0500 | [diff] [blame^] | 691 | ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}" |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 692 | ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}" |
Martí Bolívar | ffc0312 | 2020-11-12 20:27:20 -0800 | [diff] [blame] | 693 | ret[f"{macro}_IDX_{i}_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 694 | elif prop.type == "phandle-array": |
| 695 | for i, entry in enumerate(prop.val): |
Martí Bolívar | 38ede5a | 2020-12-17 14:12:01 -0800 | [diff] [blame] | 696 | if entry is None: |
| 697 | # Unspecified element. The phandle-array at this index |
| 698 | # does not point at a ControllerAndData value, but |
| 699 | # subsequent indices in the array may. |
| 700 | ret[f"{macro}_IDX_{i}_EXISTS"] = 0 |
| 701 | continue |
| 702 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 703 | ret.update(controller_and_data_macros(entry, i, macro)) |
| 704 | |
| 705 | return ret |
| 706 | |
| 707 | |
| 708 | def controller_and_data_macros(entry, i, macro): |
| 709 | # Helper procedure used by phandle_macros(). |
| 710 | # |
| 711 | # Its purpose is to write the "controller" (i.e. label property of |
| 712 | # the phandle's node) and associated data macros for a |
| 713 | # ControllerAndData. |
| 714 | |
| 715 | ret = {} |
| 716 | data = entry.data |
| 717 | |
Martí Bolívar | ffc0312 | 2020-11-12 20:27:20 -0800 | [diff] [blame] | 718 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS |
| 719 | ret[f"{macro}_IDX_{i}_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 720 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH |
| 721 | ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}" |
| 722 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL> |
| 723 | for cell, val in data.items(): |
| 724 | ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val |
| 725 | ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1 |
| 726 | |
| 727 | if not entry.name: |
| 728 | return ret |
| 729 | |
| 730 | name = str2ident(entry.name) |
Erwan Gouriou | 6c8617a | 2020-04-06 14:56:11 +0200 | [diff] [blame] | 731 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS |
| 732 | ret[f"{macro}_IDX_{i}_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 733 | # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME |
| 734 | ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name) |
| 735 | # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH |
| 736 | ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}" |
Erwan Gouriou | 6c8617a | 2020-04-06 14:56:11 +0200 | [diff] [blame] | 737 | # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS |
| 738 | ret[f"{macro}_NAME_{name}_EXISTS"] = 1 |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 739 | # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL> |
| 740 | for cell, val in data.items(): |
| 741 | cell_ident = str2ident(cell) |
| 742 | ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \ |
| 743 | f"DT_{macro}_IDX_{i}_VAL_{cell_ident}" |
| 744 | ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1 |
| 745 | |
| 746 | return ret |
| 747 | |
| 748 | |
| 749 | def write_chosen(edt): |
| 750 | # Tree-wide information such as chosen nodes is printed here. |
| 751 | |
| 752 | out_comment("Chosen nodes\n") |
| 753 | chosen = {} |
| 754 | for name, node in edt.chosen_nodes.items(): |
| 755 | chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}" |
| 756 | chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1 |
Kumar Gala | 299bfd0 | 2020-03-25 15:32:58 -0500 | [diff] [blame] | 757 | max_len = max(map(len, chosen), default=0) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 758 | for macro, value in chosen.items(): |
| 759 | out_define(macro, value, width=max_len) |
| 760 | |
| 761 | |
Martí Bolívar | a3fae2f | 2020-03-25 14:18:27 -0700 | [diff] [blame] | 762 | def write_global_compat_info(edt): |
| 763 | # Tree-wide information related to each compatible, such as number |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 764 | # of instances with status "okay", is printed here. |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 765 | |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 766 | n_okay_macros = {} |
| 767 | for_each_macros = {} |
| 768 | compat2buses = defaultdict(list) # just for "okay" nodes |
| 769 | for compat, okay_nodes in edt.compat2okay.items(): |
| 770 | for node in okay_nodes: |
Martí Bolívar | a3fae2f | 2020-03-25 14:18:27 -0700 | [diff] [blame] | 771 | bus = node.on_bus |
| 772 | if bus is not None and bus not in compat2buses[compat]: |
| 773 | compat2buses[compat].append(bus) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 774 | |
Martí Bolívar | 63d5529 | 2020-04-06 15:13:53 -0700 | [diff] [blame] | 775 | ident = str2ident(compat) |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 776 | n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes) |
Martí Bolívar | e7d42ff | 2021-08-05 15:24:50 -0700 | [diff] [blame] | 777 | |
| 778 | # Helpers for non-INST for-each macros that take node |
| 779 | # identifiers as arguments. |
| 780 | for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \ |
| 781 | " ".join(f"fn(DT_{node.z_path_id})" |
| 782 | for node in okay_nodes) |
| 783 | for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \ |
| 784 | " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)" |
| 785 | for node in okay_nodes) |
| 786 | |
| 787 | # Helpers for INST versions of for-each macros, which take |
| 788 | # instance numbers. We emit separate helpers for these because |
| 789 | # avoiding an intermediate node_id --> instance number |
| 790 | # conversion in the preprocessor helps to keep the macro |
| 791 | # expansions simpler. That hopefully eases debugging. |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 792 | for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \ |
| 793 | " ".join(f"fn({edt.compat2nodes[compat].index(node)})" |
| 794 | for node in okay_nodes) |
Arvin Farahmand | d0b9c03 | 2021-05-06 11:19:29 -0400 | [diff] [blame] | 795 | for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \ |
| 796 | " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)" |
| 797 | for node in okay_nodes) |
| 798 | |
Kumar Gala | bd97378 | 2020-05-06 20:54:29 -0500 | [diff] [blame] | 799 | for compat, nodes in edt.compat2nodes.items(): |
| 800 | for node in nodes: |
| 801 | if compat == "fixed-partitions": |
| 802 | for child in node.children.values(): |
| 803 | if "label" in child.props: |
| 804 | label = child.props["label"].val |
| 805 | macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}" |
| 806 | val = f"DT_{child.z_path_id}" |
| 807 | |
| 808 | out_dt_define(macro, val) |
| 809 | out_dt_define(macro + "_EXISTS", 1) |
| 810 | |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 811 | out_comment('Macros for compatibles with status "okay" nodes\n') |
| 812 | for compat, okay_nodes in edt.compat2okay.items(): |
| 813 | if okay_nodes: |
| 814 | out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1) |
| 815 | |
| 816 | out_comment('Macros for status "okay" instances of each compatible\n') |
| 817 | for macro, value in n_okay_macros.items(): |
Martí Bolívar | 63d5529 | 2020-04-06 15:13:53 -0700 | [diff] [blame] | 818 | out_define(macro, value) |
| 819 | for macro, value in for_each_macros.items(): |
| 820 | out_define(macro, value) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 821 | |
Martí Bolívar | 7e0eed9 | 2020-05-06 11:23:07 -0700 | [diff] [blame] | 822 | out_comment('Bus information for status "okay" nodes of each compatible\n') |
Martí Bolívar | a3fae2f | 2020-03-25 14:18:27 -0700 | [diff] [blame] | 823 | for compat, buses in compat2buses.items(): |
| 824 | for bus in buses: |
| 825 | out_define( |
| 826 | f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1) |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 827 | |
| 828 | def str2ident(s): |
| 829 | # Converts 's' to a form suitable for (part of) an identifier |
| 830 | |
| 831 | return re.sub('[-,.@/+]', '_', s.lower()) |
| 832 | |
| 833 | |
| 834 | def list2init(l): |
| 835 | # Converts 'l', a Python list (or iterable), to a C array initializer |
| 836 | |
| 837 | return "{" + ", ".join(l) + "}" |
| 838 | |
| 839 | |
| 840 | def out_dt_define(macro, val, width=None, deprecation_msg=None): |
| 841 | # Writes "#define DT_<macro> <val>" to the header file |
| 842 | # |
| 843 | # The macro will be left-justified to 'width' characters if that |
| 844 | # is specified, and the value will follow immediately after in |
| 845 | # that case. Otherwise, this function decides how to add |
| 846 | # whitespace between 'macro' and 'val'. |
| 847 | # |
| 848 | # If a 'deprecation_msg' string is passed, the generated identifiers will |
| 849 | # generate a warning if used, via __WARN(<deprecation_msg>)). |
| 850 | # |
| 851 | # Returns the full generated macro for 'macro', with leading "DT_". |
| 852 | ret = "DT_" + macro |
| 853 | out_define(ret, val, width=width, deprecation_msg=deprecation_msg) |
| 854 | return ret |
| 855 | |
| 856 | |
| 857 | def out_define(macro, val, width=None, deprecation_msg=None): |
| 858 | # Helper for out_dt_define(). Outputs "#define <macro> <val>", |
| 859 | # adds a deprecation message if given, and allocates whitespace |
| 860 | # unless told not to. |
| 861 | |
| 862 | warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else "" |
| 863 | |
| 864 | if width: |
| 865 | s = f"#define {macro.ljust(width)}{warn} {val}" |
| 866 | else: |
| 867 | s = f"#define {macro}{warn} {val}" |
| 868 | |
| 869 | print(s, file=header_file) |
| 870 | |
| 871 | |
| 872 | def out_comment(s, blank_before=True): |
| 873 | # Writes 's' as a comment to the header and configuration file. 's' is |
| 874 | # allowed to have multiple lines. blank_before=True adds a blank line |
| 875 | # before the comment. |
| 876 | |
| 877 | if blank_before: |
| 878 | print(file=header_file) |
| 879 | |
| 880 | if "\n" in s: |
| 881 | # Format multi-line comments like |
| 882 | # |
| 883 | # /* |
| 884 | # * first line |
| 885 | # * second line |
| 886 | # * |
| 887 | # * empty line before this line |
| 888 | # */ |
| 889 | res = ["/*"] |
| 890 | for line in s.splitlines(): |
| 891 | # Avoid an extra space after '*' for empty lines. They turn red in |
| 892 | # Vim if space error checking is on, which is annoying. |
| 893 | res.append(" *" if not line.strip() else " * " + line) |
| 894 | res.append(" */") |
| 895 | print("\n".join(res), file=header_file) |
| 896 | else: |
| 897 | # Format single-line comments like |
| 898 | # |
| 899 | # /* foo bar */ |
| 900 | print("/* " + s + " */", file=header_file) |
| 901 | |
| 902 | |
| 903 | def escape(s): |
| 904 | # Backslash-escapes any double quotes and backslashes in 's' |
| 905 | |
| 906 | # \ must be escaped before " to avoid double escaping |
| 907 | return s.replace("\\", "\\\\").replace('"', '\\"') |
| 908 | |
| 909 | |
| 910 | def quote_str(s): |
| 911 | # Puts quotes around 's' and escapes any double quotes and |
| 912 | # backslashes within it |
| 913 | |
| 914 | return f'"{escape(s)}"' |
| 915 | |
| 916 | |
Martí Bolívar | 533f451 | 2020-07-01 10:43:43 -0700 | [diff] [blame] | 917 | def write_pickled_edt(edt, out_file): |
| 918 | # Writes the edt object in pickle format to out_file. |
| 919 | |
| 920 | with open(out_file, 'wb') as f: |
| 921 | # Pickle protocol version 4 is the default as of Python 3.8 |
| 922 | # and was introduced in 3.4, so it is both available and |
| 923 | # recommended on all versions of Python that Zephyr supports |
| 924 | # (at time of writing, Python 3.6 was Zephyr's minimum |
| 925 | # version, and 3.8 the most recent CPython release). |
| 926 | # |
| 927 | # Using a common protocol version here will hopefully avoid |
| 928 | # reproducibility issues in different Python installations. |
| 929 | pickle.dump(edt, f, protocol=4) |
| 930 | |
| 931 | |
Martí Bolívar | dc85edd | 2020-02-28 15:26:52 -0800 | [diff] [blame] | 932 | def err(s): |
| 933 | raise Exception(s) |
| 934 | |
| 935 | |
| 936 | if __name__ == "__main__": |
| 937 | main() |