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