From nobody Sat Nov 23 23:19:48 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=reject dis=none) header.from=google.com ARC-Seal: i=1; a=rsa-sha256; t=1724741255; cv=none; d=zohomail.com; s=zohoarc; b=ZjqERQ2X+Lyt/yHp2mCcwlUwcmGaP74FYtWRRq6P/Rx+P2jmf7UAgsQh05LAmqfwvSyWpAGOnmBgAYCoqbWzpKnXtSP4PCULobOsBkkQJGWOVQQc4bIKeRQ5Hv9kw3blsjzHrXtDP02YN9ke9qCWY8ZU1+vn21EAex2cjaFl8VM= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1724741255; h=Content-Type:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=lAh/CBS4B9KfA0v7xRIzjxZuLwU+4zechPyuqw1fJdc=; b=Sw+NevkBbKrXb+rqj/oT/beIlsMrrhIoFXWn1MJp0SHVv5zNiRLdbcaRd+bK7/XeHiAq87kkpVjpdb0X//jglEm9kXkZhYA534T3ymJ0lGGIyJgK/molOpe9Z6UsyB/aYaNTZHTJx9r3ztSOhgDpMfYSOQut8XGhK0Cg9ZIGGJE= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=reject dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1724741255429281.7370781071211; Mon, 26 Aug 2024 23:47:35 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sipxZ-0002gf-4p; Tue, 27 Aug 2024 02:45:45 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from <3EHbNZgUKCm8gNiVcTbbTYR.PbZdRZh-QRiRYabaTah.beT@flex--tavip.bounces.google.com>) id 1sipxX-0002bR-R9 for qemu-devel@nongnu.org; Tue, 27 Aug 2024 02:45:43 -0400 Received: from mail-pl1-x64a.google.com ([2607:f8b0:4864:20::64a]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from <3EHbNZgUKCm8gNiVcTbbTYR.PbZdRZh-QRiRYabaTah.beT@flex--tavip.bounces.google.com>) id 1sipxU-000641-37 for qemu-devel@nongnu.org; Tue, 27 Aug 2024 02:45:43 -0400 Received: by mail-pl1-x64a.google.com with SMTP id d9443c01a7336-1fc58790766so59592895ad.3 for ; Mon, 26 Aug 2024 23:45:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1724741136; x=1725345936; darn=nongnu.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=lAh/CBS4B9KfA0v7xRIzjxZuLwU+4zechPyuqw1fJdc=; b=fhnAa3sOl+3ZQVeyO9KMuMDqm4YHlIH5xKzzBDgkhtx6LvAit0DKKeylDaJMF9+h0H 1OUBd8HbXeFePOvaNcugYq4K+gLgMXR6lUrWy6WWI+0XbD4h/KqDCqA/uzfj2E8kkzys QCGWoi7xdkK/xggxS/uhy2+WwT12E4oWd05ssorLhUj+1t8tmY1I2ncIzXbirtbX/qv2 DMhsrvTj2FDF6o5pBZmqQ9ps9PHyDCA7ZnEvRPgIdO5RVUev2tAbLhVsginN5vdwpudW 5skAVPXowFefifkZnmR2JNWtlXT/JPrr7ADPtMdAnmpIwbBZsDWgP+xASoixlh2IS6Dv fvpw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724741136; x=1725345936; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=lAh/CBS4B9KfA0v7xRIzjxZuLwU+4zechPyuqw1fJdc=; b=mq9Oo1gNUDTkr4fyJHQqPj3sd9rBL7UHJymUspFrsySlyglkt95tNmtUIWkwGug4p5 RNOK0FwWcISRMwsC9sn3ovCW0BnwHWraVDZmJNfdJjOFfCro7iy/HE7i7jWnF5BJFqWX JgI05POOjO/wtaOcVQetE8eX2yXmhqLBV3KNpFEHjL9JP+IBfFQ3XxyftqJnY0XIBDGk h8SR0K64gtPYgKguWDh8ivKJ5zNb/b4M/d6RSyz+YkkDeLLCbWiIjDUxZ1GuFTZGGsrk Y+7v4aB49zWdtfP3vVUDZoh+Znh74GIkr7PsNh47JSNevibnJpUQkuNs8T99iWGGxnje fJKw== X-Gm-Message-State: AOJu0YzzPbvC0sU5pP/12OIO9jlUXIqxMnzFBVOU6LmvI3m5mFs+dj5Q nbWksg0g9nUU006/JfCXDTmkKGuwv8Kv+D6ukc7HGzRGMkeBdPBO5hVobfWyl+hEdqBwUJMVCTO XNk0/WXoXNBtuqf6vDJIdtk3syrrJALCiu1arld3kYg3nR8+ENulxKXc8fZYUpighAq++J9n49G ++jcvYp5h4++br2sOayEgNlbRWCg== X-Google-Smtp-Source: AGHT+IG3HkFXp6vtXiuyhiA4nxX6kmE+kth1d1rBKeeaemX+5N5lTzh3xmpNbWP9kfR7QAsicSjoPa+UXA== X-Received: from warp10.c.googlers.com ([fda3:e722:ac3:cc00:24:72f4:c0a8:750]) (user=tavip job=sendgmr) by 2002:a17:902:c401:b0:1fc:2e36:5112 with SMTP id d9443c01a7336-2039e4a6ce7mr11982345ad.2.1724741136009; Mon, 26 Aug 2024 23:45:36 -0700 (PDT) Date: Mon, 26 Aug 2024 23:45:07 -0700 In-Reply-To: <20240827064529.1246786-1-tavip@google.com> Mime-Version: 1.0 References: <20240827064529.1246786-1-tavip@google.com> X-Mailer: git-send-email 2.46.0.295.g3b9ea8a38a-goog Message-ID: <20240827064529.1246786-4-tavip@google.com> Subject: [RFC PATCH v3 03/24] scripts: add script to generate C header files from SVD XML files From: Octavian Purdila To: qemu-devel@nongnu.org Cc: qemu-arm@nongnu.org, stefanst@google.com, pbonzini@redhat.com, peter.maydell@linaro.org, marcandre.lureau@redhat.com, berrange@redhat.com, eduardo@habkost.net, luc@lmichel.fr, damien.hedde@dahe.fr, alistair@alistair23.me, thuth@redhat.com, philmd@linaro.org, jsnow@redhat.com, crosa@redhat.com, lvivier@redhat.com Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::64a; envelope-from=3EHbNZgUKCm8gNiVcTbbTYR.PbZdRZh-QRiRYabaTah.beT@flex--tavip.bounces.google.com; helo=mail-pl1-x64a.google.com X-Spam_score_int: -95 X-Spam_score: -9.6 X-Spam_bar: --------- X-Spam_report: (-9.6 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_MED=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01, USER_IN_DEF_DKIM_WL=-7.5 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @google.com) X-ZM-MESSAGEID: 1724741256011116600 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Stefan Stanacar The CMSIS System View Description format(CMSIS-SVD) is an XML based description of Arm Cortex-M microcontrollers provided and maintained by sillicon vendors. It includes details such as peripherals registers (down to bitfields), peripheral register block addresses, reset values, etc. This script uses this information to create header files that makes it easier to emulate peripherals. The script can be used to create either peripheral specific headers or board / system specific information. Peripheral specific headers contains information such as register layout (using the qemu register fields infrastructure), register names, register write masks and register reset values, the latter using RegisterAccessInfo. Here is an excerpt from a generated header: #pragma once #include "hw/registerfields.h" /* Flexcomm */ #define FLEXCOMM_REGS_NO (1024) /* Peripheral Select and Flexcomm module ID */ REG32(FLEXCOMM_PSELID, 4088); /* Peripheral Select */ FIELD(FLEXCOMM_PSELID, PERSEL, 0, 3); /* Lock the peripheral select */ FIELD(FLEXCOMM_PSELID, LOCK, 3, 1); /* USART present indicator */ FIELD(FLEXCOMM_PSELID, USARTPRESENT, 4, 1); ... typedef enum { /* FLEXCOMM_PSELID_LOCK */ /* Peripheral select can be changed by software. */ FLEXCOMM_PSELID_LOCK_UNLOCKED =3D 0, /* Peripheral select is locked and cannot be changed until this * Flexcomm module or the entire device is reset. */ FLEXCOMM_PSELID_LOCK_LOCKED =3D 1, } FLEXCOMM_PSELID_LOCK_Enum; ... #define FLEXCOMM_REGISTER_ACCESS_INFO_ARRAY(_name) \ struct RegisterAccessInfo _name[FLEXCOMM_REGS_NO] =3D { \ [0 ... FLEXCOMM_REGS_NO -1] =3D { \ .name =3D "", \ .addr =3D -1, \ }, \ [R_FLEXCOMM_PSELID] =3D { \ .name =3D "PSELID", \ .addr =3D 0xFF8, \ .ro =3D 0xFFFFFFF0, \ .reset =3D 0x101000, \ }, \ [R_FLEXCOMM_PID] =3D { \ .name =3D "PID", \ .addr =3D 0xFFC, \ .ro =3D 0xFFFFFFFF, \ .reset =3D 0x0, \ }, \ } Board specific headers contains information about peripheral base register addresses. Signed-off-by: Stefan Stanacar [tavip: pylint fixes, generate layout with qemu register fields instead of bitfields, generate register names, romask and reset values] Signed-off-by: Octavian Purdila --- meson.build | 4 + scripts/svd-gen-header.py | 330 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 334 insertions(+) create mode 100755 scripts/svd-gen-header.py diff --git a/meson.build b/meson.build index ec59effca2..dee587483b 100644 --- a/meson.build +++ b/meson.build @@ -3235,6 +3235,10 @@ tracetool_depends =3D files( 'scripts/tracetool/vcpu.py' ) =20 +svd_gen_header =3D [ + python, files('scripts/svd-gen-header.py') +] + qemu_version_cmd =3D [find_program('scripts/qemu-version.sh'), meson.current_source_dir(), get_option('pkgversion'), meson.project_version()] diff --git a/scripts/svd-gen-header.py b/scripts/svd-gen-header.py new file mode 100755 index 0000000000..f24fc4335e --- /dev/null +++ b/scripts/svd-gen-header.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 + +# Copyright 2024 Google LLC +# +# This work is licensed under the terms of the GNU GPL, version 2 or later. +# See the COPYING file in the top-level directory. +# +# Use this script to generate a C header file from an SVD xml +# +# Two mode of operations are supported: peripheral and system. +# +# When running in peripheral mode a header for a specific peripheral +# is going to be generated. It will define a type and structure with +# all of the available registers at the bitfield level. An array that +# contains the reigster names indexed by address is also going to be +# generated as well as a function to initialize registers to their +# reset values. +# +# Invocation example: +# +# svd_gen_header -i MIMXRT595S_cm33.xml -o flexcomm.h -p FLEXCOMM0 -t FLEX= COMM +# +# When running in system mode a header for a specific system / +# platform will be generated. It will define register base addresses +# and interrupt numbers for selected peripherals. +# +# Invocation example: +# +# svd_gen_header -i MIMXRT595S_cm33.xml -o rt500.h -s RT500 -p FLEXCOMM0 \ +# -p CLKCTL0 -p CLKCTL1 +# + +import argparse +import re +import os +import sys +import xml.etree.ElementTree +import pysvd + +data_type_by_bits =3D { + 8: "uint8_t", + 16: "uint16_t", + 32: "uint32_t", +} + + +def get_register_array_name_and_size(reg): + """Return register name and register array size. + + The SVD can define register arrays and pysvd encodes the whole set + as as regular register with their name prepended by []. + + Returns a tuple with the register name and the size of the array or + zero if this is not a register set. + + """ + + split =3D re.split(r"[\[\]]", reg.name) + return (split[0], int(split[1]) if len(split) > 1 else 0) + + +def generate_comment(indent, text): + """Generate a comment block with for the given text with the given + indentation level. + + If possible, use a single line /* */ comment block, otherwise use + a multiline comment block. + + Newlines are preseved but tabs are not. + + """ + + # preserve new lines + text =3D text.replace("\n", " \n ") + text =3D text.replace(" ", " ") + + if len(text) + len("/* */") + len(" " * indent) <=3D 80 and "\n" not = in text: + return f"{' '* indent}/* {text} */\n" + + out =3D " " * indent + "/*\n" + line =3D " " * indent + " *" + for word in re.split(r"[ ]", text): + if len(line) + len(word) >=3D 79 or word =3D=3D "\n": + out +=3D line + "\n" + line =3D " " * indent + " *" + if word !=3D "\n": + line +=3D " " + word + else: + line +=3D " " + word + + out +=3D line + "\n" + + out +=3D " " * indent + " */\n" + return out + + +def generate_registers(name, periph): + """Generate register offsets and fields + + Use registerfield macros to define register offsets and fields for + a given peripheral. + + """ + + regs =3D sorted(periph.registers, key=3Dlambda reg: reg.addressOffset) + out =3D generate_comment(0, periph.description) + out +=3D f"#define {name}_REGS_NO ({regs[-1].addressOffset // 4 + 1})\= n\n" + for reg in regs: + out +=3D generate_comment(0, reg.description) + reg_name, reg_array_size =3D get_register_array_name_and_size(reg) + if reg_array_size > 1: + for idx in range(0, reg_array_size): + addr =3D reg.addressOffset + idx * reg.size // 8 + out +=3D f"REG32({name}_{reg_name}{idx}, {addr});\n" + else: + addr =3D reg.addressOffset + out +=3D f"REG32({name}_{reg_name}, {addr});\n" + for field in reg.fields: + out +=3D generate_comment(0, field.description) + if reg_array_size > 1: + out +=3D f"SHARED_FIELD({name}_{reg_name}_{field.name}, " + out +=3D f"{field.bitOffset}, {field.bitWidth});\n" + else: + out +=3D f"FIELD({name}_{reg_name}, {field.name}, " + out +=3D f"{field.bitOffset}, {field.bitWidth});\n" + out +=3D "\n" + + return out + + +def generate_enum_values(name, periph): + """Generate enum values""" + + out =3D "\n" + for reg in periph.registers: + reg_name, _ =3D get_register_array_name_and_size(reg) + for field in reg.fields: + if hasattr(field, "enumeratedValues"): + out +=3D "typedef enum {\n" + for enum in field.enumeratedValues.enumeratedValues: + enum_name =3D f"{name}_{reg_name}_{field.name}_{enum.n= ame}" + out +=3D generate_comment(4, enum.description) + out +=3D f" {enum_name} =3D {enum.value},\n" + out +=3D f"}} {name}_{reg_name}_{field.name}_Enum;\n" + out +=3D "\n" + + return out + + +def create_wmask(reg): + """Generate write mask for a register. + + Generate a mask with all bits that are writable set to 1 + """ + + wmask =3D 0 + fields =3D sorted(reg.fields, key=3Dlambda field: field.bitOffset) + if len(fields) > 0: + for field in fields: + if field.access !=3D pysvd.type.access.read_only: + wmask |=3D ((1 << field.bitWidth) - 1) << field.bitOffset + else: + if reg.access !=3D pysvd.type.access.read_only: + wmask =3D 0xFFFFFFFF + return wmask + + +def create_romask(reg): + """Generate write mask for a register. + + Generate a mask with all bits that are readonly set to 1 + """ + + return ~create_wmask(reg) & 0xFFFFFFFF + + +def generate_register_access_info(name, periph): + """Generate RegisterAccessInfo array macro""" + + out =3D f"\n#define {name}_REGISTER_ACCESS_INFO_ARRAY(_name) \\\n" + out +=3D f" struct RegisterAccessInfo _name[{name}_REGS_NO] =3D {{ = \\\n" + out +=3D f" [0 ... {name}_REGS_NO - 1] =3D {{ \\\n" + out +=3D ' .name =3D "", \\\n' + out +=3D " .addr =3D -1, \\\n" + out +=3D " }, \\\n" + for reg in periph.registers: + reg_name, reg_array_size =3D get_register_array_name_and_size(reg) + if reg_array_size > 1: + for idx in range(0, reg_array_size): + out +=3D f" [R_{name}_{reg_name}{idx}] =3D {{ \\\n" + addr =3D reg.addressOffset + idx * reg.size // 8 + out +=3D f' .name =3D "{reg_name}{idx}", \\\n' + out +=3D f" .addr =3D 0x{addr:X}, \\\n" + out +=3D f" .ro =3D 0x{create_romask(reg):X}, \= \\n" + out +=3D f" .reset =3D 0x{reg.resetValue:X}, \\= \n" + out +=3D " }, \\\n" + else: + out +=3D f" [R_{name}_{reg_name}] =3D {{ \\\n" + out +=3D f' .name =3D "{reg_name}", \\\n' + out +=3D f" .addr =3D 0x{reg.addressOffset:X}, \\\n" + out +=3D f" .ro =3D 0x{create_romask(reg):X}, \\\n" + out +=3D f" .reset =3D 0x{reg.resetValue:X}, \\\n" + out +=3D " }, \\\n" + out +=3D " }\n" + + return out + + +def generate_peripheral_header(periph, name): + """Generate peripheral header + + The following information is generated: + + * typedef with all of the available registers and register fields, + position and mask defines for register fields. + + * enum values that encode register fields options. + + * a macro that defines the register names indexed by the relative + address of the register. + + * a function that sets the registers to their reset values + + """ + + out =3D generate_registers(name, periph) + + out +=3D generate_enum_values(name, periph) + + out +=3D generate_register_access_info(name, periph) + + return out + + +def get_same_class_peripherals(svd, periph): + """Get a list of peripherals that are instances of the same class.""" + + return [periph] + [ + p + for p in svd.peripherals + if p.derivedFrom and p.derivedFrom.name =3D=3D periph.name + ] + + +def generate_system_header(system, svd, periph): + """Generate base and irq defines for given list of peripherals""" + + out =3D "" + + for p in get_same_class_peripherals(svd, periph): + out +=3D f"#define {system}_{p.name}_BASE 0x{p.baseAddress:X}UL\n" + out +=3D "\n" + + for p in get_same_class_peripherals(svd, periph): + for irq in p.interrupts: + out +=3D f"#define {system}_{irq.name}_IRQn 0x{irq.value}UL\n" + out +=3D "\n" + + return out + + +def main(): + """Script to generate C header file from an SVD file""" + + parser =3D argparse.ArgumentParser() + parser.add_argument( + "-i", "--input", type=3Dstr, help=3D"Input SVD file", required=3DT= rue + ) + parser.add_argument( + "-o", "--output", type=3Dstr, help=3D"Output .h file", required=3D= True + ) + parser.add_argument( + "-p", + "--peripheral", + action=3D"append", + help=3D"peripheral name from the SVD file", + required=3DTrue, + ) + parser.add_argument( + "-t", + "--type-name", + type=3Dstr, + help=3D"name to be used for peripheral definitions", + required=3DFalse, + ) + parser.add_argument( + "-s", + "--system", + type=3Dstr, + help=3D"name to be used for the system definitions", + required=3DFalse, + ) + + args =3D parser.parse_args() + + node =3D xml.etree.ElementTree.parse(args.input).getroot() + svd =3D pysvd.element.Device(node) + + # Write license header + header =3D svd.licenseText.strip() + header +=3D f"\n\nAutomatically generated by {os.path.basename(__file_= _)} " + header +=3D f"from {os.path.basename(args.input)}" + out =3D generate_comment(0, header) + + # Write some generic defines + out +=3D "#pragma once\n\n" + + for name in args.peripheral: + periph =3D svd.find(name) + if periph: + if args.system: + out +=3D generate_system_header(args.system, svd, periph) + else: + out +=3D '#include "hw/register.h"\n\n' + out +=3D '#include "hw/registerfields.h"\n\n' + out +=3D generate_peripheral_header( + periph, args.type_name if args.type_name else periph.n= ame + ) + else: + print(f"No such peripheral: {name}") + return 1 + + with open(args.output, "w", encoding=3D"ascii") as output: + output.write(out) + + return 0 + + +if __name__ =3D=3D "__main__": + sys.exit(main()) --=20 2.46.0.295.g3b9ea8a38a-goog