Search is not available for this dataset
content
stringlengths
0
376M
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // FPV CSR read and write assertions auto-generated by `reggen` containing data structure // Do Not Edit directly // TODO: This automation currently only support register without HW write access <% from reggen import (gen_fpv) from reggen.register import Register from topgen import lib lblock = block.name.lower() use_reg_iface = any([interface['protocol'] == BusProtocol.REG_IFACE and not interace['is_host'] for interface in block.bus_interfaces.interface_list]) # This template shouldn't be instantiated if the device interface # doesn't actually have any registers. assert rb.flat_regs %>\ <%def name="construct_classes(block)">\ % if use_reg_iface: `include "common_cells/assertions.svh" % else: `include "prim_assert.sv" % endif `ifdef UVM import uvm_pkg::*; `endif // Block: ${lblock} module ${mod_base}_csr_assert_fpv import tlul_pkg::*; import top_pkg::*;( input clk_i, input rst_ni, // tile link ports input tl_h2d_t h2d, input tl_d2h_t d2h ); <% addr_width = rb.get_addr_width() addr_msb = addr_width - 1 hro_regs_list = [r for r in rb.flat_regs if not r.hwaccess.allows_write()] num_hro_regs = len(hro_regs_list) hro_map = {r.offset: (idx, r) for idx, r in enumerate(hro_regs_list)} %>\ // Currently FPV csr assertion only support HRO registers. % if num_hro_regs > 0: `ifndef VERILATOR `ifndef SYNTHESIS parameter bit[3:0] MAX_A_SOURCE = 10; // used for FPV only to reduce runtime typedef struct packed { logic [TL_DW-1:0] wr_data; logic [TL_AW-1:0] addr; logic wr_pending; logic rd_pending; } pend_item_t; bit disable_sva; // mask register to convert byte to bit logic [TL_DW-1:0] a_mask_bit; assign a_mask_bit[7:0] = h2d.a_mask[0] ? '1 : '0; assign a_mask_bit[15:8] = h2d.a_mask[1] ? '1 : '0; assign a_mask_bit[23:16] = h2d.a_mask[2] ? '1 : '0; assign a_mask_bit[31:24] = h2d.a_mask[3] ? '1 : '0; bit [${addr_msb}-2:0] hro_idx; // index for exp_vals bit [${addr_msb}:0] normalized_addr; // Map register address with hro_idx in exp_vals array. always_comb begin: decode_hro_addr_to_idx unique case (pend_trans[d2h.d_source].addr) % for idx, r in hro_map.values(): ${r.offset}: hro_idx <= ${idx}; % endfor // If the register is not a HRO register, the write data will all update to this default idx. default: hro_idx <= ${num_hro_regs + 1}; endcase end // store internal expected values for HW ReadOnly registers logic [TL_DW-1:0] exp_vals[${num_hro_regs + 1}]; `ifdef FPV_ON pend_item_t [MAX_A_SOURCE:0] pend_trans; `else pend_item_t [2**TL_AIW-1:0] pend_trans; `endif // normalized address only take the [${addr_msb}:2] address from the TLUL a_address assign normalized_addr = {h2d.a_address[${addr_msb}:2], 2'b0}; % if num_hro_regs > 0: // for write HRO registers, store the write data into exp_vals always_ff @(negedge clk_i or negedge rst_ni) begin if (!rst_ni) begin pend_trans <= '0; % for hro_reg in hro_regs_list: exp_vals[${hro_map.get(hro_reg.offset)[0]}] <= ${hro_reg.resval}; % endfor end else begin if (h2d.a_valid && d2h.a_ready) begin pend_trans[h2d.a_source].addr <= normalized_addr; if (h2d.a_opcode inside {PutFullData, PutPartialData}) begin pend_trans[h2d.a_source].wr_data <= h2d.a_data & a_mask_bit; pend_trans[h2d.a_source].wr_pending <= 1'b1; end else if (h2d.a_opcode == Get) begin pend_trans[h2d.a_source].rd_pending <= 1'b1; end end if (d2h.d_valid) begin if (pend_trans[d2h.d_source].wr_pending == 1) begin if (!d2h.d_error) begin exp_vals[hro_idx] <= pend_trans[d2h.d_source].wr_data; end pend_trans[d2h.d_source].wr_pending <= 1'b0; end if (h2d.d_ready && pend_trans[d2h.d_source].rd_pending == 1) begin pend_trans[d2h.d_source].rd_pending <= 1'b0; end end end end // for read HRO registers, assert read out values by access policy and exp_vals % for hro_reg in hro_regs_list: <% r_name = hro_reg.name.lower() reg_addr = hro_reg.offset reg_addr_hex = format(reg_addr, 'x') regwen = hro_reg.regwen reg_mask = 0 for f in hro_reg.get_field_list(): f_access = f.swaccess.key.lower() if f_access == "rw" and regwen == None: reg_mask = reg_mask | f.bits.bitmask() %>\ % if reg_mask != 0: <% reg_mask_hex = format(reg_mask, 'x') %>\ `ASSERT(${r_name}_rd_A, d2h.d_valid && pend_trans[d2h.d_source].rd_pending && pend_trans[d2h.d_source].addr == ${addr_width}'h${reg_addr_hex} |-> d2h.d_error || (d2h.d_data & 'h${reg_mask_hex}) == (exp_vals[${hro_map.get(reg_addr)[0]}] & 'h${reg_mask_hex})) % endif % endfor % endif // This FPV only assumption is to reduce the FPV runtime. `ASSUME_FPV(TlulSource_M, h2d.a_source >= 0 && h2d.a_source <= MAX_A_SOURCE, clk_i, !rst_ni) `ifdef UVM initial forever begin bit csr_assert_en; uvm_config_db#(bit)::wait_modified(null, "%m", "csr_assert_en"); if (!uvm_config_db#(bit)::get(null, "%m", "csr_assert_en", csr_assert_en)) begin `uvm_fatal("csr_assert", "Can't find csr_assert_en") end disable_sva = !csr_assert_en; end `endif `endif `endif % endif endmodule </%def>\ ${construct_classes(block)}
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """ Generate HTML documentation from Block """ from typing import TextIO from .ip_block import IpBlock from .html_helpers import render_td from .signal import Signal def genout(outfile: TextIO, msg: str) -> None: outfile.write(msg) def name_width(x: Signal) -> str: if x.bits.width() == 1: return x.name return '{}[{}:0]'.format(x.name, x.bits.msb) def gen_kv(outfile: TextIO, key: str, value: str) -> None: genout(outfile, '<p><i>{}:</i> {}</p>\n'.format(key, value)) def gen_cfg_html(cfgs: IpBlock, outfile: TextIO) -> None: rnames = cfgs.get_rnames() ot_server = 'https://docs.opentitan.org' comport_url = ot_server + '/doc/rm/comportability_specification' genout(outfile, '<p>Referring to the <a href="{url}">Comportable guideline for ' 'peripheral device functionality</a>, the module ' '<b><code>{mod_name}</code></b> has the following hardware ' 'interfaces defined.</p>\n' .format(url=comport_url, mod_name=cfgs.name)) # clocks gen_kv(outfile, 'Primary Clock', '<b><code>{}</code></b>'.format(cfgs.clock_signals[0])) if len(cfgs.clock_signals) > 1: other_clocks = ['<b><code>{}</code></b>'.format(clk) for clk in cfgs.clock_signals[1:]] gen_kv(outfile, 'Other Clocks', ', '.join(other_clocks)) else: gen_kv(outfile, 'Other Clocks', '<i>none</i>') # bus interfaces dev_ports = ['<b><code>{}</code></b>'.format(port) for port in cfgs.bus_interfaces.get_port_names(False, True)] assert dev_ports gen_kv(outfile, 'Bus Device Interfaces (TL-UL)', ', '.join(dev_ports)) host_ports = ['<b><code>{}</code></b>'.format(port) for port in cfgs.bus_interfaces.get_port_names(True, False)] if host_ports: gen_kv(outfile, 'Bus Host Interfaces (TL-UL)', ', '.join(host_ports)) else: gen_kv(outfile, 'Bus Host Interfaces (TL-UL)', '<i>none</i>') # IO ios = ([('input', x) for x in cfgs.xputs[1]] + [('output', x) for x in cfgs.xputs[2]] + [('inout', x) for x in cfgs.xputs[0]]) if ios: genout(outfile, "<p><i>Peripheral Pins for Chip IO:</i></p>\n") genout( outfile, "<table class=\"cfgtable\"><tr>" + "<th>Pin name</th><th>direction</th>" + "<th>Description</th></tr>\n") for direction, x in ios: genout(outfile, '<tr><td>{}</td><td>{}</td>{}</tr>' .format(name_width(x), direction, render_td(x.desc, rnames, None))) genout(outfile, "</table>\n") else: genout(outfile, "<p><i>Peripheral Pins for Chip IO: none</i></p>\n") if not cfgs.interrupts: genout(outfile, "<p><i>Interrupts: none</i></p>\n") else: genout(outfile, "<p><i>Interrupts:</i></p>\n") genout( outfile, "<table class=\"cfgtable\"><tr><th>Interrupt Name</th>" + "<th>Description</th></tr>\n") for x in cfgs.interrupts: genout(outfile, '<tr><td>{}</td>{}</tr>' .format(name_width(x), render_td(x.desc, rnames, None))) genout(outfile, "</table>\n") if not cfgs.alerts: genout(outfile, "<p><i>Security Alerts: none</i></p>\n") else: genout(outfile, "<p><i>Security Alerts:</i></p>\n") genout( outfile, "<table class=\"cfgtable\"><tr><th>Alert Name</th>" + "<th>Description</th></tr>\n") for x in cfgs.alerts: genout(outfile, '<tr><td>{}</td>{}</tr>' .format(x.name, render_td(x.desc, rnames, None))) genout(outfile, "</table>\n")
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """ Generate C header from validated register JSON tree """ import io import logging as log import sys import textwrap import warnings from typing import List, Optional, Set, TextIO from .field import Field from .ip_block import IpBlock from .params import LocalParam from .register import Register from .multi_register import MultiRegister from .signal import Signal from .window import Window def genout(outfile: TextIO, msg: str) -> None: outfile.write(msg) def to_snake_case(s: str) -> str: val = [] for i, ch in enumerate(s): if i > 0 and ch.isupper(): val.append('_') val.append(ch) return ''.join(val) def as_define(s: str) -> str: s = s.upper() r = '' for i in range(0, len(s)): r += s[i] if s[i].isalnum() else '_' return r def first_line(s: str) -> str: """Returns the first line of a multi-line string""" return s.splitlines()[0] def format_comment(s: str) -> str: """Formats a string to comment wrapped to an 80 character line width Returns wrapped string including newline and // comment characters. """ return '\n'.join( textwrap.wrap( s, width=77, initial_indent='// ', subsequent_indent='// ')) + '\n' def gen_define(name: str, args: List[str], body: str, existing_defines: Set[str], indent: str = ' ') -> str: r"""Produces a #define string, will split into two lines if a single line has a width greater than 80 characters. Result includes newline. Arguments: name - Name of the #define args - List of arguments for the define, provide an empty list if there are none body - Body of the #define existing_defines - set of already generated define names. Error if `name` is in `existing_defines`. indent - Gives string to prepend on any new lines produced by wrapping (default ' ') Example result: name = 'A_MACRO' args = ['arg1', 'arg2'], body = 'arg1 + arg2 + 10' #define A_MACRO(arg1, arg2) arg1 + arg2 + 10 When the macro is wrapped the break happens after the argument list (or macro name if there is no argument list #define A_MACRO(arg1, arg2) \ arg1 + arg2 + 10 """ if name in existing_defines: log.error("Duplicate #define for " + name) sys.exit(1) if len(args) != 0: define_declare = '#define ' + name + '(' + ', '.join(args) + ')' else: define_declare = '#define ' + name oneline_define = define_declare + ' ' + body existing_defines.add(name) if len(oneline_define) <= 80: return oneline_define + '\n' return define_declare + ' \\\n' + indent + body + '\n' def gen_cdefine_register(outstr: TextIO, reg: Register, comp: str, width: int, rnames: Set[str], existing_defines: Set[str]) -> None: rname = reg.name offset = reg.offset genout(outstr, format_comment(first_line(reg.desc))) defname = as_define(comp + '_' + rname) genout( outstr, gen_define(defname + '_REG_OFFSET', [], hex(offset), existing_defines)) for field in reg.fields: dname = defname + '_' + as_define(field.name) field_width = field.bits.width() if field_width == 1: # single bit genout( outstr, gen_define(dname + '_BIT', [], str(field.bits.lsb), existing_defines)) else: # multiple bits (unless it is the whole register) if field_width != width: mask = field.bits.bitmask() >> field.bits.lsb genout( outstr, gen_define(dname + '_MASK', [], hex(mask), existing_defines)) genout( outstr, gen_define(dname + '_OFFSET', [], str(field.bits.lsb), existing_defines)) genout( outstr, gen_define( dname + '_FIELD', [], '((bitfield_field32_t) {{ .mask = {dname}_MASK, .index = {dname}_OFFSET }})' .format(dname=dname), existing_defines)) if field.enum is not None: for enum in field.enum: ename = as_define(enum.name) value = hex(enum.value) genout( outstr, gen_define( defname + '_' + as_define(field.name) + '_VALUE_' + ename, [], value, existing_defines)) genout(outstr, '\n') return def gen_cdefine_window(outstr: TextIO, win: Window, comp: str, regwidth: int, rnames: Set[str], existing_defines: Set[str]) -> None: offset = win.offset genout(outstr, format_comment('Memory area: ' + first_line(win.desc))) defname = as_define(comp + '_' + win.name) genout( outstr, gen_define(defname + '_REG_OFFSET', [], hex(offset), existing_defines)) items = win.items genout( outstr, gen_define(defname + '_SIZE_WORDS', [], str(items), existing_defines)) items = items * (regwidth // 8) genout( outstr, gen_define(defname + '_SIZE_BYTES', [], str(items), existing_defines)) wid = win.validbits if (wid != regwidth): mask = (1 << wid) - 1 genout(outstr, gen_define(defname + '_MASK ', [], hex(mask), existing_defines)) def gen_cdefines_module_param(outstr: TextIO, param: LocalParam, module_name: str, existing_defines: Set[str]) -> None: # Presently there is only one type (int), however if the new types are # added, they potentially need to be handled differently. known_types = ["int"] if param.param_type not in known_types: warnings.warn("Cannot generate a module define of type {}" .format(param.param_type)) return if param.desc is not None: genout(outstr, format_comment(first_line(param.desc))) # Heuristic: if the name already has underscores, it's already snake_case, # otherwise, assume StudlyCaps and covert it to snake_case. param_name = param.name if '_' in param.name else to_snake_case(param.name) define_name = as_define(module_name + '_PARAM_' + param_name) if param.param_type == "int": define = gen_define(define_name, [], param.value, existing_defines) genout(outstr, define) genout(outstr, '\n') def gen_cdefines_module_params(outstr: TextIO, module_data: IpBlock, module_name: str, register_width: int, existing_defines: Set[str]) -> None: module_params = module_data.params for param in module_params.get_localparams(): gen_cdefines_module_param(outstr, param, module_name, existing_defines) genout(outstr, format_comment(first_line("Register width"))) define_name = as_define(module_name + '_PARAM_REG_WIDTH') define = gen_define(define_name, [], str(register_width), existing_defines) genout(outstr, define) genout(outstr, '\n') def gen_multireg_field_defines(outstr: TextIO, regname: str, field: Field, subreg_num: int, regwidth: int, existing_defines: Set[str]) -> None: field_width = field.bits.width() fields_per_reg = regwidth // field_width define_name = regname + '_' + as_define(field.name + "_FIELD_WIDTH") define = gen_define(define_name, [], str(field_width), existing_defines) genout(outstr, define) define_name = regname + '_' + as_define(field.name + "_FIELDS_PER_REG") define = gen_define(define_name, [], str(fields_per_reg), existing_defines) genout(outstr, define) define_name = regname + "_MULTIREG_COUNT" define = gen_define(define_name, [], str(subreg_num), existing_defines) genout(outstr, define) genout(outstr, '\n') def gen_cdefine_multireg(outstr: TextIO, multireg: MultiRegister, component: str, regwidth: int, rnames: Set[str], existing_defines: Set[str]) -> None: comment = multireg.reg.desc + " (common parameters)" genout(outstr, format_comment(first_line(comment))) if len(multireg.reg.fields) == 1: regname = as_define(component + '_' + multireg.reg.name) gen_multireg_field_defines(outstr, regname, multireg.reg.fields[0], len(multireg.regs), regwidth, existing_defines) else: log.warn("Non-homogeneous multireg " + multireg.reg.name + " skip multireg specific data generation.") for subreg in multireg.regs: gen_cdefine_register(outstr, subreg, component, regwidth, rnames, existing_defines) def gen_cdefines_interrupt_field(outstr: TextIO, interrupt: Signal, component: str, regwidth: int, existing_defines: Set[str]) -> None: fieldlsb = interrupt.bits.lsb iname = interrupt.name defname = as_define(component + '_INTR_COMMON_' + iname) if interrupt.bits.width() == 1: # single bit genout( outstr, gen_define(defname + '_BIT', [], str(fieldlsb), existing_defines)) else: # multiple bits (unless it is the whole register) if interrupt.bits.width() != regwidth: mask = interrupt.bits.msb >> fieldlsb genout( outstr, gen_define(defname + '_MASK', [], hex(mask), existing_defines)) genout( outstr, gen_define(defname + '_OFFSET', [], str(fieldlsb), existing_defines)) genout( outstr, gen_define( defname + '_FIELD', [], '((bitfield_field32_t) {{ .mask = {dname}_MASK, .index = {dname}_OFFSET }})' .format(dname=defname), existing_defines)) def gen_cdefines_interrupts(outstr: TextIO, block: IpBlock, component: str, regwidth: int, existing_defines: Set[str]) -> None: # If no_auto_intr_regs is true, then we do not generate common defines, # because the bit offsets for a particular interrupt may differ between # the interrupt enable/state/test registers. if block.no_auto_intr: return genout(outstr, format_comment(first_line("Common Interrupt Offsets"))) for intr in block.interrupts: gen_cdefines_interrupt_field(outstr, intr, component, regwidth, existing_defines) genout(outstr, '\n') def gen_cdefines(block: IpBlock, outfile: TextIO, src_lic: Optional[str], src_copy: str) -> int: rnames = block.get_rnames() outstr = io.StringIO() # This tracks the defines that have been generated so far, so we # can error if we attempt to duplicate a definition existing_defines = set() # type: Set[str] gen_cdefines_module_params(outstr, block, block.name, block.regwidth, existing_defines) gen_cdefines_interrupts(outstr, block, block.name, block.regwidth, existing_defines) for rb in block.reg_blocks.values(): for x in rb.entries: if isinstance(x, Register): gen_cdefine_register(outstr, x, block.name, block.regwidth, rnames, existing_defines) continue if isinstance(x, MultiRegister): gen_cdefine_multireg(outstr, x, block.name, block.regwidth, rnames, existing_defines) continue if isinstance(x, Window): gen_cdefine_window(outstr, x, block.name, block.regwidth, rnames, existing_defines) continue generated = outstr.getvalue() outstr.close() genout(outfile, '// Generated register defines for ' + block.name + '\n\n') if src_copy != '': genout(outfile, '// Copyright information found in source file:\n') genout(outfile, '// ' + src_copy + '\n\n') if src_lic is not None: genout(outfile, '// Licensing information found in source file:\n') for line in src_lic.splitlines(): genout(outfile, '// ' + line + '\n') genout(outfile, '\n') # Header Include Guard genout(outfile, '#ifndef _' + as_define(block.name) + '_REG_DEFS_\n') genout(outfile, '#define _' + as_define(block.name) + '_REG_DEFS_\n\n') # Header Extern Guard (so header can be used from C and C++) genout(outfile, '#ifdef __cplusplus\n') genout(outfile, 'extern "C" {\n') genout(outfile, '#endif\n') genout(outfile, generated) # Header Extern Guard genout(outfile, '#ifdef __cplusplus\n') genout(outfile, '} // extern "C"\n') genout(outfile, '#endif\n') # Header Include Guard genout(outfile, '#endif // _' + as_define(block.name) + '_REG_DEFS_\n') genout(outfile, '// End generated register defines for ' + block.name) return 0 def test_gen_define() -> None: basic_oneline = '#define MACRO_NAME body\n' assert gen_define('MACRO_NAME', [], 'body', set()) == basic_oneline basic_oneline_with_args = '#define MACRO_NAME(arg1, arg2) arg1 + arg2\n' assert (gen_define('MACRO_NAME', ['arg1', 'arg2'], 'arg1 + arg2', set()) == basic_oneline_with_args) long_macro_name = 'A_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_LONG_MACRO_NAME' multiline = ('#define ' + long_macro_name + ' \\\n' + ' a_fairly_long_body + something_else + 10\n') assert (gen_define(long_macro_name, [], 'a_fairly_long_body + something_else + 10', set()) == multiline) multiline_with_args = ('#define ' + long_macro_name + '(arg1, arg2, arg3) \\\n' + ' a_fairly_long_body + arg1 + arg2 + arg3\n') assert (gen_define(long_macro_name, ['arg1', 'arg2', 'arg3'], 'a_fairly_long_body + arg1 + arg2 + arg3', set()) == multiline_with_args) multiline_with_args_big_indent = ( '#define ' + long_macro_name + '(arg1, arg2, arg3) \\\n' + ' a_fairly_long_body + arg1 + arg2 + arg3\n') assert (gen_define(long_macro_name, ['arg1', 'arg2', 'arg3'], 'a_fairly_long_body + arg1 + arg2 + arg3', set(), indent=' ') == multiline_with_args_big_indent)
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Generate DV code for an IP block''' import logging as log import os from typing import List import yaml from mako import exceptions # type: ignore from mako.lookup import TemplateLookup # type: ignore from pkg_resources import resource_filename from .ip_block import IpBlock from .register import Register from .window import Window def bcname(esc_if_name: str) -> str: '''Get the name of the dv_base_reg_block subclass for this device interface''' return esc_if_name + "_reg_block" def rcname(esc_if_name: str, r: Register) -> str: '''Get the name of the dv_base_reg subclass for this register''' return '{}_reg_{}'.format(esc_if_name, r.name.lower()) def mcname(esc_if_name: str, m: Window) -> str: '''Get the name of the dv_base_mem subclass for this memory''' return '{}_mem_{}'.format(esc_if_name, m.name.lower()) def miname(m: Window) -> str: '''Get the lower-case name of a memory block''' return m.name.lower() def gen_core_file(outdir: str, lblock: str, dv_base_prefix: str, paths: List[str]) -> None: depends = ["lowrisc:dv:dv_base_reg"] if dv_base_prefix and dv_base_prefix != "dv_base": depends.append("lowrisc:dv:{}_reg".format(dv_base_prefix)) # Generate a fusesoc core file that points at the files we've just # generated. core_data = { 'name': "lowrisc:dv:{}_ral_pkg".format(lblock), 'filesets': { 'files_dv': { 'depend': depends, 'files': paths, 'file_type': 'systemVerilogSource' }, }, 'targets': { 'default': { 'filesets': [ 'files_dv', ], }, }, } core_file_path = os.path.join(outdir, lblock + '_ral_pkg.core') with open(core_file_path, 'w') as core_file: core_file.write('CAPI=2:\n') yaml.dump(core_data, core_file, encoding='utf-8') def gen_dv(block: IpBlock, dv_base_prefix: str, outdir: str) -> int: '''Generate DV files for an IpBlock''' lookup = TemplateLookup(directories=[resource_filename('reggen', '.')]) uvm_reg_tpl = lookup.get_template('uvm_reg.sv.tpl') # Generate the RAL package(s). For a device interface with no name we # generate the package "<block>_ral_pkg" (writing to <block>_ral_pkg.sv). # In any other case, we also need the interface name, giving # <block>_<ifname>_ral_pkg. generated = [] lblock = block.name.lower() for if_name, rb in block.reg_blocks.items(): hier_path = '' if block.hier_path is None else block.hier_path + '.' if_suffix = '' if if_name is None else '_' + if_name.lower() mod_base = lblock + if_suffix reg_block_path = hier_path + 'u_reg' + if_suffix file_name = mod_base + '_ral_pkg.sv' generated.append(file_name) reg_top_path = os.path.join(outdir, file_name) with open(reg_top_path, 'w', encoding='UTF-8') as fout: try: fout.write(uvm_reg_tpl.render(rb=rb, block=block, esc_if_name=mod_base, reg_block_path=reg_block_path, dv_base_prefix=dv_base_prefix)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 gen_core_file(outdir, lblock, dv_base_prefix, generated) return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # # Lint as: python3 # """Generate FPV CSR read and write assertions from IpBlock """ import logging as log import os.path import yaml from mako import exceptions from mako.template import Template from pkg_resources import resource_filename from .ip_block import IpBlock def gen_fpv(block: IpBlock, outdir): # Read Register templates fpv_csr_tpl = Template( filename=resource_filename('reggen', 'fpv_csr.sv.tpl')) # Generate a module with CSR assertions for each device interface. For a # device interface with no name, we generate <block>_csr_assert_fpv. For a # named interface, we generate <block>_<ifname>_csr_assert_fpv. lblock = block.name.lower() generated = [] for if_name, rb in block.reg_blocks.items(): if not rb.flat_regs: # No registers to check! continue if if_name is None: mod_base = lblock else: mod_base = lblock + '_' + if_name.lower() mod_name = mod_base + '_csr_assert_fpv' filename = mod_name + '.sv' generated.append(filename) reg_top_path = os.path.join(outdir, filename) with open(reg_top_path, 'w', encoding='UTF-8') as fout: try: fout.write(fpv_csr_tpl.render(block=block, mod_base=mod_base, if_name=if_name, rb=rb)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 # Generate a fusesoc core file that points at the files we've just # generated. core_data = { 'name': "lowrisc:fpv:{}_csr_assert".format(lblock), 'filesets': { 'files_dv': { 'depend': [ "lowrisc:tlul:headers", "lowrisc:prim:assert", ], 'files': generated, 'file_type': 'systemVerilogSource' }, }, 'targets': { 'default': { 'filesets': [ 'files_dv', ], }, }, } core_file_path = os.path.join(outdir, lblock + '_csr_assert_fpv.core') with open(core_file_path, 'w') as core_file: core_file.write('CAPI=2:\n') yaml.dump(core_data, core_file, encoding='utf-8') return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """ Generate HTML documentation from IpBlock """ from typing import Set, TextIO from .ip_block import IpBlock from .html_helpers import expand_paras, render_td from .multi_register import MultiRegister from .reg_block import RegBlock from .register import Register from .window import Window def genout(outfile: TextIO, msg: str) -> None: outfile.write(msg) # Generation of HTML table with register bit-field summary picture # Max 16-bit wide on one line def gen_tbl_row(outfile: TextIO, msb: int, width: int, close: bool) -> None: if (close): genout(outfile, "</tr>\n") genout(outfile, "<tr>") for x in range(msb, msb - width, -1): genout(outfile, "<td class=\"bitnum\">" + str(x) + "</td>") genout(outfile, "</tr><tr>") def gen_html_reg_pic(outfile: TextIO, reg: Register, width: int) -> None: if (width > 32): bsize = 3 nextbit = 63 hdrbits = 16 nextline = 48 elif (width > 16): bsize = 3 nextbit = 31 hdrbits = 16 nextline = 16 elif (width > 8): bsize = 3 nextbit = 15 nextline = 0 hdrbits = 16 else: bsize = 12 nextbit = 7 nextline = 0 hdrbits = 8 genout(outfile, "<table class=\"regpic\">") gen_tbl_row(outfile, nextbit, hdrbits, False) for field in reversed(reg.fields): fieldlsb = field.bits.lsb fieldwidth = field.bits.width() fieldmsb = field.bits.msb fname = field.name while nextbit > fieldmsb: if (nextbit >= nextline) and (fieldmsb < nextline): spans = nextbit - (nextline - 1) else: spans = nextbit - fieldmsb genout( outfile, "<td class=\"unused\" colspan=" + str(spans) + ">&nbsp;</td>\n") if (nextbit >= nextline) and (fieldmsb < nextline): nextbit = nextline - 1 gen_tbl_row(outfile, nextbit, hdrbits, True) nextline = nextline - 16 else: nextbit = fieldmsb while (fieldmsb >= nextline) and (fieldlsb < nextline): spans = fieldmsb - (nextline - 1) genout( outfile, "<td class=\"fname\" colspan=" + str(spans) + ">" + fname + "...</td>\n") fname = "..." + field.name fieldwidth = fieldwidth - spans fieldmsb = nextline - 1 nextline = nextline - 16 gen_tbl_row(outfile, fieldmsb, hdrbits, True) namelen = len(fname) if namelen == 0 or fname == ' ': fname = "&nbsp;" if (namelen > bsize * fieldwidth): usestyle = (" style=\"font-size:" + str( (bsize * 100 * fieldwidth) / namelen) + "%\"") else: usestyle = "" genout( outfile, "<td class=\"fname\" colspan=" + str(fieldwidth) + usestyle + ">" + fname + "</td>\n") if (fieldlsb == nextline) and nextline > 0: gen_tbl_row(outfile, nextline - 1, hdrbits, True) nextline = nextline - 16 nextbit = fieldlsb - 1 while (nextbit > 0): spans = nextbit - (nextline - 1) genout(outfile, "<td class=\"unused\" colspan=" + str(spans) + ">&nbsp;</td>\n") nextbit = nextline - 1 if (nextline > 0): gen_tbl_row(outfile, nextline - 1, hdrbits, True) nextline = nextline - 16 genout(outfile, "</tr></table>") # Generation of HTML table with header, register picture and details def gen_html_register(outfile: TextIO, reg: Register, comp: str, width: int, rnames: Set[str]) -> None: rname = reg.name offset = reg.offset regwen_div = '' if reg.regwen is not None: regwen_div = (' <div>Register enable = {}</div>\n' .format(reg.regwen)) desc_paras = expand_paras(reg.desc, rnames) desc_head = desc_paras[0] desc_body = desc_paras[1:] genout(outfile, '<table class="regdef" id="Reg_{lrname}">\n' ' <tr>\n' ' <th class="regdef" colspan=5>\n' ' <div>{comp}.{rname} @ {off:#x}</div>\n' ' <div>{desc}</div>\n' ' <div>Reset default = {resval:#x}, mask {mask:#x}</div>\n' '{wen}' ' </th>\n' ' </tr>\n' .format(lrname=rname.lower(), comp=comp, rname=rname, off=offset, desc=desc_head, resval=reg.resval, mask=reg.resmask, wen=regwen_div)) if desc_body: genout(outfile, '<tr><td colspan=5>{}</td></tr>' .format(''.join(desc_body))) genout(outfile, "<tr><td colspan=5>") gen_html_reg_pic(outfile, reg, width) genout(outfile, "</td></tr>\n") genout(outfile, "<tr><th width=5%>Bits</th>") genout(outfile, "<th width=5%>Type</th>") genout(outfile, "<th width=5%>Reset</th>") genout(outfile, "<th>Name</th>") genout(outfile, "<th>Description</th></tr>") nextbit = 0 fcount = 0 for field in reg.fields: fcount += 1 fname = field.name fieldlsb = field.bits.lsb if fieldlsb > nextbit: genout(outfile, "<tr><td class=\"regbits\">") if (nextbit == (fieldlsb - 1)): genout(outfile, str(nextbit)) else: genout(outfile, str(fieldlsb - 1) + ":" + str(nextbit)) genout(outfile, "</td><td></td><td></td><td></td><td>Reserved</td></tr>") genout(outfile, "<tr><td class=\"regbits\">" + field.bits.as_str() + "</td>") genout(outfile, "<td class=\"regperm\">" + field.swaccess.key + "</td>") genout( outfile, "<td class=\"regrv\">" + ('x' if field.resval is None else hex(field.resval)) + "</td>") genout(outfile, "<td class=\"regfn\">" + fname + "</td>") # Collect up any description and enum table desc_parts = [] if field.desc is not None: desc_parts += expand_paras(field.desc, rnames) if field.enum is not None: desc_parts.append('<table>') for enum in field.enum: enum_desc_paras = expand_paras(enum.desc, rnames) desc_parts.append('<tr>' '<td>{val}</td>' '<td>{name}</td>' '<td>{desc}</td>' '</tr>\n' .format(val=enum.value, name=enum.name, desc=''.join(enum_desc_paras))) desc_parts.append('</table>') if field.has_incomplete_enum(): desc_parts.append("<p>Other values are reserved.</p>") genout(outfile, '<td class="regde">{}</td>'.format(''.join(desc_parts))) nextbit = fieldlsb + field.bits.width() genout(outfile, "</table>\n<br>\n") def gen_html_window(outfile: TextIO, win: Window, comp: str, regwidth: int, rnames: Set[str]) -> None: wname = win.name or '(unnamed window)' offset = win.offset genout(outfile, '<table class="regdef" id="Reg_{lwname}">\n' ' <tr>\n' ' <th class="regdef">\n' ' <div>{comp}.{wname} @ + {off:#x}</div>\n' ' <div>{items} item {swaccess} window</div>\n' ' <div>Byte writes are {byte_writes}supported</div>\n' ' </th>\n' ' </tr>\n' .format(comp=comp, wname=wname, lwname=wname.lower(), off=offset, items=win.items, swaccess=win.swaccess.key, byte_writes=('' if win.byte_write else '<i>not</i> '))) genout(outfile, '<tr><td><table class="regpic">') genout(outfile, '<tr><td width="10%"></td>') wid = win.validbits for x in range(regwidth - 1, -1, -1): if x == regwidth - 1 or x == wid - 1 or x == 0: genout(outfile, '<td class="bitnum">' + str(x) + '</td>') else: genout(outfile, '<td class="bitnum"></td>') genout(outfile, '</tr>') tblmax = win.items - 1 for x in [0, 1, 2, tblmax - 1, tblmax]: if x == 2: genout( outfile, '<tr><td>&nbsp;</td><td align=center colspan=' + str(regwidth) + '>...</td></tr>') else: genout( outfile, '<tr><td class="regbits">+' + hex(offset + x * (regwidth // 8)) + '</td>') if wid < regwidth: genout( outfile, '<td class="unused" colspan=' + str(regwidth - wid) + '>&nbsp;</td>\n') genout( outfile, '<td class="fname" colspan=' + str(wid) + '>&nbsp;</td>\n') else: genout( outfile, '<td class="fname" colspan=' + str(regwidth) + '>&nbsp;</td>\n') genout(outfile, '</tr>') genout(outfile, '</td></tr></table>') genout(outfile, '<tr>{}</tr>'.format(render_td(win.desc, rnames, 'regde'))) genout(outfile, "</table>\n<br>\n") def gen_html_reg_block(outfile: TextIO, rb: RegBlock, comp: str, width: int, rnames: Set[str]) -> None: for x in rb.entries: if isinstance(x, Register): gen_html_register(outfile, x, comp, width, rnames) elif isinstance(x, MultiRegister): for reg in x.regs: gen_html_register(outfile, reg, comp, width, rnames) else: assert isinstance(x, Window) gen_html_window(outfile, x, comp, width, rnames) def gen_html(block: IpBlock, outfile: TextIO) -> int: rnames = block.get_rnames() assert block.reg_blocks # Handle the case where there's just one interface if len(block.reg_blocks) == 1: rb = list(block.reg_blocks.values())[0] gen_html_reg_block(outfile, rb, block.name, block.regwidth, rnames) return 0 # Handle the case where there is more than one device interface and, # correspondingly, more than one reg block. for iface_name, rb in block.reg_blocks.items(): iface_desc = ('device interface <code>{}</code>'.format(iface_name) if iface_name is not None else 'the unnamed device interface') genout(outfile, '<h3>Registers visible under {}</h3>'.format(iface_desc)) gen_html_reg_block(outfile, rb, block.name, block.regwidth, rnames) return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Generate JSON/compact JSON/Hjson from register JSON tree """ import hjson def gen_json(obj, outfile, format): if format == 'json': hjson.dumpJSON(obj, outfile, ensure_ascii=False, use_decimal=True, indent=' ', for_json=True) elif format == 'compact': hjson.dumpJSON(obj, outfile, ensure_ascii=False, for_json=True, use_decimal=True, separators=(',', ':')) elif format == 'hjson': hjson.dump(obj, outfile, ensure_ascii=False, for_json=True, use_decimal=True) else: raise ValueError('Invalid JSON format ' + format) return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Generate SystemVerilog designs from IpBlock object""" import logging as log import os from typing import Dict, Optional, Tuple from mako import exceptions # type: ignore from mako.template import Template # type: ignore from pkg_resources import resource_filename from .ip_block import IpBlock from .multi_register import MultiRegister from .reg_base import RegBase from .register import Register def escape_name(name: str) -> str: return name.lower().replace(' ', '_') def make_box_quote(msg: str, indent: str = ' ') -> str: hr = indent + ('/' * (len(msg) + 6)) middle = indent + '// ' + msg + ' //' return '\n'.join([hr, middle, hr]) def _get_awparam_name(iface_name: Optional[str]) -> str: return (iface_name or 'Iface').capitalize() + 'Aw' def get_addr_widths(block: IpBlock) -> Dict[Optional[str], Tuple[str, int]]: '''Return the address widths for the device interfaces Returns a dictionary keyed by interface name whose values are pairs: (paramname, width) where paramname is IfaceAw for an unnamed interface and FooAw for an interface called foo. This is constructed in the same order as block.reg_blocks. If there is a single device interface and that interface is unnamed, use the more general parameter name "BlockAw". ''' assert block.reg_blocks if len(block.reg_blocks) == 1 and None in block.reg_blocks: return {None: ('BlockAw', block.reg_blocks[None].get_addr_width())} return {name: (_get_awparam_name(name), rb.get_addr_width()) for name, rb in block.reg_blocks.items()} def get_type_name_pfx(block: IpBlock, iface_name: Optional[str]) -> str: return block.name.lower() + ('' if iface_name is None else '_{}'.format(iface_name.lower())) def get_r0(reg: RegBase) -> Register: '''Get a Register representing an entry in the RegBase''' if isinstance(reg, Register): return reg else: assert isinstance(reg, MultiRegister) return reg.reg def get_iface_tx_type(block: IpBlock, iface_name: Optional[str], hw2reg: bool) -> str: x2x = 'hw2reg' if hw2reg else 'reg2hw' pfx = get_type_name_pfx(block, iface_name) return '_'.join([pfx, x2x, 't']) def get_reg_tx_type(block: IpBlock, reg: RegBase, hw2reg: bool) -> str: '''Get the name of the hw2reg or reg2hw type for reg''' if isinstance(reg, Register): r0 = reg type_suff = 'reg_t' else: assert isinstance(reg, MultiRegister) r0 = reg.reg type_suff = 'mreg_t' x2x = 'hw2reg' if hw2reg else 'reg2hw' return '_'.join([block.name.lower(), x2x, r0.name.lower(), type_suff]) def gen_rtl(block: IpBlock, outdir: str) -> int: # Read Register templates reg_top_tpl = Template( filename=resource_filename('reggen', 'reg_top.sv.tpl')) reg_pkg_tpl = Template( filename=resource_filename('reggen', 'reg_pkg.sv.tpl')) # Generate <block>_reg_pkg.sv # # This defines the various types used to interface between the *_reg_top # module(s) and the block itself. reg_pkg_path = os.path.join(outdir, block.name.lower() + "_reg_pkg.sv") with open(reg_pkg_path, 'w', encoding='UTF-8') as fout: try: fout.write(reg_pkg_tpl.render(block=block)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 # Generate the register block implementation(s). For a device interface # with no name we generate the register module "<block>_reg_top" (writing # to <block>_reg_top.sv). In any other case, we also need the interface # name, giving <block>_<ifname>_reg_top. lblock = block.name.lower() for if_name, rb in block.reg_blocks.items(): if if_name is None: mod_base = lblock else: mod_base = lblock + '_' + if_name.lower() mod_name = mod_base + '_reg_top' reg_top_path = os.path.join(outdir, mod_name + '.sv') with open(reg_top_path, 'w', encoding='UTF-8') as fout: try: fout.write(reg_top_tpl.render(block=block, mod_base=mod_base, mod_name=mod_name, if_name=if_name, rb=rb)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """ Generates the documentation for the register tool """ from .access import SWACCESS_PERMITTED, HWACCESS_PERMITTED from reggen import (validate, ip_block, enum_entry, field, register, multi_register, window) def genout(outfile, msg): outfile.write(msg) doc_intro = """ <!-- Start of output generated by `regtool.py --doc` --> The tables describe each key and the type of the value. The following types are used: Type | Description ---- | ----------- """ swaccess_intro = """ Register fields are tagged using the swaccess key to describe the permitted access and side-effects. This key must have one of these values: """ hwaccess_intro = """ Register fields are tagged using the hwaccess key to describe the permitted access from hardware logic and side-effects. This key must have one of these values: """ top_example = """ The basic structure of a register definition file is thus: ```hjson { name: "GP", regwidth: "32", registers: [ // register definitions... ] } ``` """ register_example = """ The basic register definition group will follow this pattern: ```hjson { name: "REGA", desc: "Description of register", swaccess: "rw", resval: "42", fields: [ // bit field definitions... ] } ``` The name and brief description are required. If the swaccess key is provided it describes the access pattern that will be used by all bitfields in the register that do not override with their own swaccess key. This is a useful shortcut because in most cases a register will have the same access restrictions for all fields. The reset value of the register may also be provided here or in the individual fields. If it is provided in both places then they must match, if it is provided in neither place then the reset value defaults to zero for all except write-only fields when it defaults to x. """ field_example = """ Field names should be relatively short because they will be used frequently (and need to fit in the register layout picture!) The field description is expected to be longer and will most likely make use of the Hjson ability to include multi-line strings. An example with three fields: ```hjson fields: [ { bits: "15:0", name: "RXS", desc: ''' Last 16 oversampled values of RX. These are captured at 16x the baud rate clock. This is a shift register with the most recent bit in bit 0 and the oldest in bit 15. Only valid when ENRXS is set. ''' } { bits: "16", name: "ENRXS", desc: ''' If this bit is set the receive oversampled data is collected in the RXS field. ''' } {bits: "20:19", name: "TXILVL", desc: "Trigger level for TX interrupts", resval: "2", enum: [ { value: "0", name: "txlvl1", desc: "1 character" }, { value: "1", name: "txlvl4", desc: "4 characters" }, { value: "2", name: "txlvl8", desc: "8 characters" }, { value: "3", name: "txlvl16", desc: "16 characters" } ] } ] ``` In all of these the swaccess parameter is inherited from the register level, and will be added so this key is always available to the backend. The RXS and ENRXS will default to zero reset value (unless something different is provided for the register) and will have the key added, but TXILVL expicitly sets its reset value as 2. The missing bits 17 and 18 will be treated as reserved by the tool, as will any bits between 21 and the maximum in the register. The TXILVL is an example using an enumeration to specify all valid values for the field. In this case all possible values are described, if the list is incomplete then the field is marked with the rsvdenum key so the backend can take appropriate action. (If the enum field is more than 7 bits then the checking is not done.) """ offset_intro = """ """ multi_intro = """ The multireg expands on the register required fields and will generate a list of the generated registers (that contain all required and generated keys for an actual register). """ window_intro = """ A window defines an open region of the register space that can be used for things that are not registers (for example access to a buffer ram). """ regwen_intro = """ Registers can protect themselves from software writes by using the register attribute regwen. When not an emptry string (the default value), regwen indicates that another register must be true in order to allow writes to this register. This is useful for the prevention of software modification. The register-enable register (call it REGWEN) must be one bit in width, and should default to 1 and be rw1c for preferred security control. This allows all writes to proceed until at some point software disables future modifications by clearing REGWEN. An error is reported if REGWEN does not exist, contains more than one bit, is not `rw1c` or does not default to 1. One REGWEN can protect multiple registers. The REGWEN register must precede those registers that refer to it in the .hjson register list. An example: ```hjson { name: "REGWEN", desc: "Register write enable for a bank of registers", swaccess: "rw1c", fields: [ { bits: "0", resval: "1" } ] } { name: "REGA", swaccess: "rw", regwen: "REGWEN", ... } { name: "REGB", swaccess: "rw", regwen: "REGWEN", ... } ``` """ doc_tail = """ (end of output generated by `regtool.py --doc`) """ def doc_tbl_head(outfile, use): if use is not None: genout(outfile, "\nKey | Kind | Type | Description of Value\n") genout(outfile, "--- | ---- | ---- | --------------------\n") else: genout(outfile, "\nKey | Description\n") genout(outfile, "--- | -----------\n") def doc_tbl_line(outfile, key, use, desc): if use is not None: desc_key, desc_txt = desc val_type = (validate.val_types[desc_key][0] if desc_key is not None else None) else: assert isinstance(desc, str) val_type = None desc_txt = desc if val_type is not None: genout( outfile, '{} | {} | {} | {}\n'.format(key, validate.key_use[use], val_type, desc_txt)) else: genout(outfile, key + " | " + desc_txt + "\n") def document(outfile): genout(outfile, doc_intro) for x in validate.val_types: genout( outfile, validate.val_types[x][0] + " | " + validate.val_types[x][1] + "\n") genout(outfile, swaccess_intro) doc_tbl_head(outfile, None) for key, value in SWACCESS_PERMITTED.items(): doc_tbl_line(outfile, key, None, value[0]) genout(outfile, hwaccess_intro) doc_tbl_head(outfile, None) for key, value in HWACCESS_PERMITTED.items(): doc_tbl_line(outfile, key, None, value[0]) genout( outfile, "\n\nThe top level of the JSON is a group containing " "the following keys:\n") doc_tbl_head(outfile, 1) for k, v in ip_block.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) for k, v in ip_block.OPTIONAL_FIELDS.items(): doc_tbl_line(outfile, k, 'o', v) genout(outfile, top_example) genout( outfile, "\n\nThe list of registers includes register definition " "groups containing the following keys:\n") doc_tbl_head(outfile, 1) for k, v in register.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) for k, v in register.OPTIONAL_FIELDS.items(): doc_tbl_line(outfile, k, 'o', v) genout(outfile, register_example) genout( outfile, "\n\nIn the fields list each field definition is a group " "itself containing the following keys:\n") doc_tbl_head(outfile, 1) for k, v in field.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) for k, v in field.OPTIONAL_FIELDS.items(): doc_tbl_line(outfile, k, 'o', v) genout(outfile, field_example) genout(outfile, "\n\nDefinitions in an enumeration group contain:\n") doc_tbl_head(outfile, 1) for k, v in enum_entry.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) genout( outfile, "\n\nThe list of registers may include single entry groups " "to control the offset, open a window or generate registers:\n") doc_tbl_head(outfile, 1) for x in validate.list_optone: doc_tbl_line(outfile, x, 'o', validate.list_optone[x]) genout(outfile, offset_intro) genout(outfile, regwen_intro) genout(outfile, window_intro) doc_tbl_head(outfile, 1) for k, v in window.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) for k, v in window.OPTIONAL_FIELDS.items(): doc_tbl_line(outfile, k, 'o', v) genout(outfile, multi_intro) doc_tbl_head(outfile, 1) for k, v in multi_register.REQUIRED_FIELDS.items(): doc_tbl_line(outfile, k, 'r', v) for k, v in multi_register.OPTIONAL_FIELDS.items(): doc_tbl_line(outfile, k, 'o', v) genout(outfile, doc_tail)
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import logging as log import re from typing import List, Match, Optional, Set def expand_paras(s: str, rnames: Set[str]) -> List[str]: '''Expand a description field to HTML. This supports a sort of simple pseudo-markdown. Supported Markdown features: - Separate paragraphs on a blank line - **bold** and *italicised* text - Back-ticks for pre-formatted text We also generate links to registers when a name is prefixed with a double exclamation mark. For example, if there is a register FOO then !!FOO or !!FOO.field will generate a link to that register. Returns a list of rendered paragraphs ''' # Start by splitting into paragraphs. The regex matches a newline followed # by one or more lines that just contain whitespace. Then render each # paragraph with the _expand_paragraph worker function. paras = [_expand_paragraph(paragraph.strip(), rnames) for paragraph in re.split(r'\n(?:\s*\n)+', s)] # There will always be at least one paragraph (splitting an empty string # gives ['']) assert paras return paras def _expand_paragraph(s: str, rnames: Set[str]) -> str: '''Expand a single paragraph, as described in _get_desc_paras''' def fieldsub(match: Match[str]) -> str: base = match.group(1).partition('.')[0].lower() if base in rnames: if match.group(1)[-1] == ".": return ('<a href="#Reg_' + base + '"><code class=\"reg\">' + match.group(1)[:-1] + '</code></a>.') else: return ('<a href="#Reg_' + base + '"><code class=\"reg\">' + match.group(1) + '</code></a>') log.warn('!!' + match.group(1).partition('.')[0] + ' not found in register list.') return match.group(0) # Split out pre-formatted text. Because the call to re.split has a capture # group in the regex, we get an odd number of results. Elements with even # indices are "normal text". Those with odd indices are the captured text # between the back-ticks. code_split = re.split(r'`([^`]+)`', s) expanded_parts = [] for idx, part in enumerate(code_split): if idx & 1: # Text contained in back ticks expanded_parts.append('<code>{}</code>'.format(part)) continue part = re.sub(r"!!([A-Za-z0-9_.]+)", fieldsub, part) part = re.sub(r"(?s)\*\*(.+?)\*\*", r'<B>\1</B>', part) part = re.sub(r"\*([^*]+?)\*", r'<I>\1</I>', part) expanded_parts.append(part) return '<p>{}</p>'.format(''.join(expanded_parts)) def render_td(s: str, rnames: Set[str], td_class: Optional[str]) -> str: '''Expand a description field and put it in a <td>. Returns a string. See _get_desc_paras for the format that gets expanded. ''' desc_paras = expand_paras(s, rnames) class_attr = '' if td_class is None else ' class="{}"'.format(td_class) return '<td{}>{}</td>'.format(class_attr, ''.join(desc_paras))
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict, Optional from .lib import (check_keys, check_name, check_str, check_optional_str, check_int) class InterSignal: def __init__(self, name: str, desc: Optional[str], struct: str, package: Optional[str], signal_type: str, act: str, width: int, default: Optional[str]): assert 0 < width self.name = name self.desc = desc self.struct = struct self.package = package self.signal_type = signal_type self.act = act self.width = width self.default = default @staticmethod def from_raw(what: str, raw: object) -> 'InterSignal': rd = check_keys(raw, what, ['name', 'struct', 'type', 'act'], ['desc', 'package', 'width', 'default']) name = check_name(rd['name'], 'name field of ' + what) r_desc = rd.get('desc') if r_desc is None: desc = None else: desc = check_str(r_desc, 'desc field of ' + what) struct = check_str(rd['struct'], 'struct field of ' + what) r_package = rd.get('package') if r_package is None or r_package == '': package = None else: package = check_name(r_package, 'package field of ' + what) signal_type = check_name(rd['type'], 'type field of ' + what) act = check_name(rd['act'], 'act field of ' + what) width = check_int(rd.get('width', 1), 'width field of ' + what) if width <= 0: raise ValueError('width field of {} is not positive.'.format(what)) default = check_optional_str(rd.get('default'), 'default field of ' + what) return InterSignal(name, desc, struct, package, signal_type, act, width, default) def _asdict(self) -> Dict[str, object]: ret = {'name': self.name} # type: Dict[str, object] if self.desc is not None: ret['desc'] = self.desc ret['struct'] = self.struct if self.package is not None: ret['package'] = self.package ret['type'] = self.signal_type ret['act'] = self.act ret['width'] = self.width if self.default is not None: ret['default'] = self.default return ret def as_dict(self) -> Dict[str, object]: return self._asdict()
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Code representing an IP block for reggen''' from typing import Dict, List, Optional, Sequence, Set, Tuple import hjson # type: ignore from .alert import Alert from .bus_interfaces import BusInterfaces from .inter_signal import InterSignal from .lib import (check_keys, check_name, check_int, check_bool, check_list, check_optional_str, check_name_list) from .params import ReggenParams, LocalParam from .reg_block import RegBlock from .signal import Signal REQUIRED_FIELDS = { 'name': ['s', "name of the component"], 'clock_primary': ['s', "name of the primary clock"], 'bus_interfaces': ['l', "bus interfaces for the device"], 'registers': [ 'l', "list of register definition groups and " "offset control groups" ] } OPTIONAL_FIELDS = { 'alert_list': ['lnw', "list of peripheral alerts"], 'available_inout_list': ['lnw', "list of available peripheral inouts"], 'available_input_list': ['lnw', "list of available peripheral inputs"], 'available_output_list': ['lnw', "list of available peripheral outputs"], 'hier_path': [ None, 'additional hierarchy path before the reg block instance' ], 'interrupt_list': ['lnw', "list of peripheral interrupts"], 'inter_signal_list': ['l', "list of inter-module signals"], 'no_auto_alert_regs': [ 's', "Set to true to suppress automatic " "generation of alert test registers. " "Defaults to true if no alert_list is present. " "Otherwise this defaults to false. " ], 'no_auto_intr_regs': [ 's', "Set to true to suppress automatic " "generation of interrupt registers. " "Defaults to true if no interrupt_list is present. " "Otherwise this defaults to false. " ], 'other_clock_list': ['l', "list of other chip clocks needed"], 'other_reset_list': ['l', "list of other resets"], 'param_list': ['lp', "list of parameters of the IP"], 'regwidth': ['d', "width of registers in bits (default 32)"], 'reset_primary': ['s', "primary reset used by the module"], 'reset_request_list': ['l', 'list of signals requesting reset'], 'scan': ['pb', 'Indicates the module have `scanmode_i`'], 'scan_reset': ['pb', 'Indicates the module have `scan_rst_ni`'], 'scan_en': ['pb', 'Indicates the module has `scan_en_i`'], 'SPDX-License-Identifier': [ 's', "License ientifier (if using pure json) " "Only use this if unable to put this " "information in a comment at the top of the " "file." ], 'wakeup_list': ['lnw', "list of peripheral wakeups"] } class IpBlock: def __init__(self, name: str, regwidth: int, params: ReggenParams, reg_blocks: Dict[Optional[str], RegBlock], interrupts: Sequence[Signal], no_auto_intr: bool, alerts: List[Alert], no_auto_alert: bool, scan: bool, inter_signals: List[InterSignal], bus_interfaces: BusInterfaces, hier_path: Optional[str], clock_signals: List[str], reset_signals: List[str], xputs: Tuple[Sequence[Signal], Sequence[Signal], Sequence[Signal]], wakeups: Sequence[Signal], reset_requests: Sequence[Signal], scan_reset: bool, scan_en: bool): assert reg_blocks assert clock_signals assert reset_signals # Check that register blocks are in bijection with device interfaces reg_block_names = reg_blocks.keys() dev_if_names = [] # type: List[Optional[str]] dev_if_names += bus_interfaces.named_devices if bus_interfaces.has_unnamed_device: dev_if_names.append(None) assert set(reg_block_names) == set(dev_if_names) self.name = name self.regwidth = regwidth self.reg_blocks = reg_blocks self.params = params self.interrupts = interrupts self.no_auto_intr = no_auto_intr self.alerts = alerts self.no_auto_alert = no_auto_alert self.scan = scan self.inter_signals = inter_signals self.bus_interfaces = bus_interfaces self.hier_path = hier_path self.clock_signals = clock_signals self.reset_signals = reset_signals self.xputs = xputs self.wakeups = wakeups self.reset_requests = reset_requests self.scan_reset = scan_reset self.scan_en = scan_en @staticmethod def from_raw(param_defaults: List[Tuple[str, str]], raw: object, where: str) -> 'IpBlock': rd = check_keys(raw, 'block at ' + where, list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) name = check_name(rd['name'], 'name of block at ' + where) what = '{} block at {}'.format(name, where) r_regwidth = rd.get('regwidth') if r_regwidth is None: regwidth = 32 else: regwidth = check_int(r_regwidth, 'regwidth field of ' + what) if regwidth <= 0: raise ValueError('Invalid regwidth field for {}: ' '{} is not positive.' .format(what, regwidth)) params = ReggenParams.from_raw('parameter list for ' + what, rd.get('param_list', [])) try: params.apply_defaults(param_defaults) except (ValueError, KeyError) as err: raise ValueError('Failed to apply defaults to params: {}' .format(err)) from None init_block = RegBlock(regwidth, params) interrupts = Signal.from_raw_list('interrupt_list for block {}' .format(name), rd.get('interrupt_list', [])) alerts = Alert.from_raw_list('alert_list for block {}' .format(name), rd.get('alert_list', [])) no_auto_intr = check_bool(rd.get('no_auto_intr_regs', not interrupts), 'no_auto_intr_regs field of ' + what) no_auto_alert = check_bool(rd.get('no_auto_alert_regs', not alerts), 'no_auto_alert_regs field of ' + what) if interrupts and not no_auto_intr: if interrupts[-1].bits.msb >= regwidth: raise ValueError("Interrupt list for {} is too wide: " "msb is {}, which doesn't fit with a " "regwidth of {}." .format(what, interrupts[-1].bits.msb, regwidth)) init_block.make_intr_regs(interrupts) if alerts: if not no_auto_alert: if len(alerts) > regwidth: raise ValueError("Interrupt list for {} is too wide: " "{} alerts don't fit with a regwidth of {}." .format(what, len(alerts), regwidth)) init_block.make_alert_regs(alerts) # Generate a NumAlerts parameter existing_param = params.get('NumAlerts') if existing_param is not None: if ((not isinstance(existing_param, LocalParam) or existing_param.param_type != 'int' or existing_param.value != str(len(alerts)))): raise ValueError('Conflicting definition of NumAlerts ' 'parameter.') else: params.add(LocalParam(name='NumAlerts', desc='Number of alerts', param_type='int', value=str(len(alerts)))) scan = check_bool(rd.get('scan', False), 'scan field of ' + what) reg_blocks = RegBlock.build_blocks(init_block, rd['registers']) r_inter_signals = check_list(rd.get('inter_signal_list', []), 'inter_signal_list field') inter_signals = [ InterSignal.from_raw('entry {} of the inter_signal_list field' .format(idx + 1), entry) for idx, entry in enumerate(r_inter_signals) ] bus_interfaces = (BusInterfaces. from_raw(rd['bus_interfaces'], 'bus_interfaces field of ' + where)) inter_signals += bus_interfaces.inter_signals() hier_path = check_optional_str(rd.get('hier_path', None), 'hier_path field of ' + what) clock_primary = check_name(rd['clock_primary'], 'clock_primary field of ' + what) other_clock_list = check_name_list(rd.get('other_clock_list', []), 'other_clock_list field of ' + what) clock_signals = [clock_primary] + other_clock_list reset_primary = check_name(rd.get('reset_primary', 'rst_ni'), 'reset_primary field of ' + what) other_reset_list = check_name_list(rd.get('other_reset_list', []), 'other_reset_list field of ' + what) reset_signals = [reset_primary] + other_reset_list xputs = ( Signal.from_raw_list('available_inout_list for block ' + name, rd.get('available_inout_list', [])), Signal.from_raw_list('available_input_list for block ' + name, rd.get('available_input_list', [])), Signal.from_raw_list('available_output_list for block ' + name, rd.get('available_output_list', [])) ) wakeups = Signal.from_raw_list('wakeup_list for block ' + name, rd.get('wakeup_list', [])) rst_reqs = Signal.from_raw_list('reset_request_list for block ' + name, rd.get('reset_request_list', [])) scan_reset = check_bool(rd.get('scan_reset', False), 'scan_reset field of ' + what) scan_en = check_bool(rd.get('scan_en', False), 'scan_en field of ' + what) # Check that register blocks are in bijection with device interfaces reg_block_names = reg_blocks.keys() dev_if_names = [] # type: List[Optional[str]] dev_if_names += bus_interfaces.named_devices if bus_interfaces.has_unnamed_device: dev_if_names.append(None) if set(reg_block_names) != set(dev_if_names): raise ValueError("IP block {} defines device interfaces, named {} " "but its registers don't match (they are keyed " "by {})." .format(name, dev_if_names, list(reg_block_names))) return IpBlock(name, regwidth, params, reg_blocks, interrupts, no_auto_intr, alerts, no_auto_alert, scan, inter_signals, bus_interfaces, hier_path, clock_signals, reset_signals, xputs, wakeups, rst_reqs, scan_reset, scan_en) @staticmethod def from_text(txt: str, param_defaults: List[Tuple[str, str]], where: str) -> 'IpBlock': '''Load an IpBlock from an hjson description in txt''' return IpBlock.from_raw(param_defaults, hjson.loads(txt, use_decimal=True), where) @staticmethod def from_path(path: str, param_defaults: List[Tuple[str, str]]) -> 'IpBlock': '''Load an IpBlock from an hjson description in a file at path''' with open(path, 'r', encoding='utf-8') as handle: return IpBlock.from_text(handle.read(), param_defaults, 'file at {!r}'.format(path)) def _asdict(self) -> Dict[str, object]: ret = { 'name': self.name, 'regwidth': self.regwidth } if len(self.reg_blocks) == 1 and None in self.reg_blocks: ret['registers'] = self.reg_blocks[None].as_dicts() else: ret['registers'] = {k: v.as_dicts() for k, v in self.reg_blocks.items()} ret['param_list'] = self.params.as_dicts() ret['interrupt_list'] = self.interrupts ret['no_auto_intr_regs'] = self.no_auto_intr ret['alert_list'] = self.alerts ret['no_auto_alert_regs'] = self.no_auto_alert ret['scan'] = self.scan ret['inter_signal_list'] = self.inter_signals ret['bus_interfaces'] = self.bus_interfaces.as_dicts() if self.hier_path is not None: ret['hier_path'] = self.hier_path ret['clock_primary'] = self.clock_signals[0] if len(self.clock_signals) > 1: ret['other_clock_list'] = self.clock_signals[1:] ret['reset_primary'] = self.reset_signals[0] if len(self.reset_signals) > 1: ret['other_reset_list'] = self.reset_signals[1:] inouts, inputs, outputs = self.xputs if inouts: ret['available_inout_list'] = inouts if inputs: ret['available_input_list'] = inputs if outputs: ret['available_output_list'] = outputs if self.wakeups: ret['wakeup_list'] = self.wakeups if self.reset_requests: ret['reset_request_list'] = self.reset_requests ret['scan_reset'] = self.scan_reset ret['scan_en'] = self.scan_en return ret def get_rnames(self) -> Set[str]: ret = set() # type: Set[str] for rb in self.reg_blocks.values(): ret = ret.union(set(rb.name_to_offset.keys())) return ret def get_signals_as_list_of_dicts(self) -> List[Dict]: '''Look up and return signal by name''' result = [] for iodir, xput in zip(('inout', 'input', 'output'), self.xputs): for sig in xput: result.append(sig.as_nwt_dict(iodir)) return result def get_signal_by_name_as_dict(self, name: str) -> Dict: '''Look up and return signal by name''' sig_list = self.get_signals_as_list_of_dicts() for sig in sig_list: if sig['name'] == name: return sig else: raise ValueError("Signal {} does not exist in IP block {}" .format(name, self.name))
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Parsing support code for reggen''' import re from typing import Dict, List, Optional, cast # Names that are prohibited (used as reserved keywords in systemverilog) _VERILOG_KEYWORDS = { 'alias', 'always', 'always_comb', 'always_ff', 'always_latch', 'and', 'assert', 'assign', 'assume', 'automatic', 'before', 'begin', 'bind', 'bins', 'binsof', 'bit', 'break', 'buf', 'bufif0', 'bufif1', 'byte', 'case', 'casex', 'casez', 'cell', 'chandle', 'class', 'clocking', 'cmos', 'config', 'const', 'constraint', 'context', 'continue', 'cover', 'covergroup', 'coverpoint', 'cross', 'deassign', 'default', 'defparam', 'design', 'disable', 'dist', 'do', 'edge', 'else', 'end', 'endcase', 'endclass', 'endclocking', 'endconfig', 'endfunction', 'endgenerate', 'endgroup', 'endinterface', 'endmodule', 'endpackage', 'endprimitive', 'endprogram', 'endproperty', 'endspecify', 'endsequence', 'endtable', 'endtask', 'enum', 'event', 'expect', 'export', 'extends', 'extern', 'final', 'first_match', 'for', 'force', 'foreach', 'forever', 'fork', 'forkjoin', 'function', 'generate', 'genvar', 'highz0', 'highz1', 'if', 'iff', 'ifnone', 'ignore_bins', 'illegal_bins', 'import', 'incdir', 'include', 'initial', 'inout', 'input', 'inside', 'instance', 'int', 'integer', 'interface', 'intersect', 'join', 'join_any', 'join_none', 'large', 'liblist', 'library', 'local', 'localparam', 'logic', 'longint', 'macromodule', 'matches', 'medium', 'modport', 'module', 'nand', 'negedge', 'new', 'nmos', 'nor', 'noshowcancelled', 'not', 'notif0', 'notif1', 'null', 'or', 'output', 'package', 'packed', 'parameter', 'pmos', 'posedge', 'primitive', 'priority', 'program', 'property', 'protected', 'pull0', 'pull1', 'pulldown', 'pullup', 'pulsestyle_onevent', 'pulsestyle_ondetect', 'pure', 'rand', 'randc', 'randcase', 'randsequence', 'rcmos', 'real', 'realtime', 'ref', 'reg', 'release', 'repeat', 'return', 'rnmos', 'rpmos', 'rtran', 'rtranif0', 'rtranif1', 'scalared', 'sequence', 'shortint', 'shortreal', 'showcancelled', 'signed', 'small', 'solve', 'specify', 'specparam', 'static', 'string', 'strong0', 'strong1', 'struct', 'super', 'supply0', 'supply1', 'table', 'tagged', 'task', 'this', 'throughout', 'time', 'timeprecision', 'timeunit', 'tran', 'tranif0', 'tranif1', 'tri', 'tri0', 'tri1', 'triand', 'trior', 'trireg', 'type', 'typedef', 'union', 'unique', 'unsigned', 'use', 'uwire', 'var', 'vectored', 'virtual', 'void', 'wait', 'wait_order', 'wand', 'weak0', 'weak1', 'while', 'wildcard', 'wire', 'with', 'within', 'wor', 'xnor', 'xor' } def check_str_dict(obj: object, what: str) -> Dict[str, object]: if not isinstance(obj, dict): raise ValueError("{} is expected to be a dict, but was actually a {}." .format(what, type(obj).__name__)) for key in obj: if not isinstance(key, str): raise ValueError('{} has a key {!r}, which is not a string.' .format(what, key)) return cast(Dict[str, object], obj) def check_keys(obj: object, what: str, required_keys: List[str], optional_keys: List[str]) -> Dict[str, object]: '''Check that obj is a dict object with the expected keys If not, raise a ValueError; the what argument names the object. ''' od = check_str_dict(obj, what) allowed = set() missing = [] for key in required_keys: assert key not in allowed allowed.add(key) if key not in od: missing.append(key) for key in optional_keys: assert key not in allowed allowed.add(key) unexpected = [] for key in od: if key not in allowed: unexpected.append(key) if missing or unexpected: mstr = ('The following required fields were missing: {}.' .format(', '.join(missing)) if missing else '') ustr = ('The following unexpected fields were found: {}.' .format(', '.join(unexpected)) if unexpected else '') raise ValueError("{} doesn't have the right keys. {}{}{}" .format(what, mstr, ' ' if mstr and ustr else '', ustr)) return od def check_str(obj: object, what: str) -> str: '''Check that the given object is a string If not, raise a ValueError; the what argument names the object. ''' if not isinstance(obj, str): raise ValueError('{} is of type {}, not a string.' .format(what, type(obj).__name__)) return obj def check_name(obj: object, what: str) -> str: '''Check that obj is a string that's a valid name. If not, raise a ValueError; the what argument names the object. ''' as_str = check_str(obj, what) # Allow the usual symbol constituents (alphanumeric plus underscore; no # leading numbers) if not re.match(r'[a-zA-Z_][a-zA-Z_0-9]*$', as_str): raise ValueError("{} is {!r}, which isn't a valid symbol in " "C / Verilog, so isn't allowed as a name." .format(what, as_str)) # Also check that this isn't a reserved word. if as_str in _VERILOG_KEYWORDS: raise ValueError("{} is {!r}, which is a reserved word in " "SystemVerilog, so isn't allowed as a name." .format(what, as_str)) return as_str def check_bool(obj: object, what: str) -> bool: '''Check that obj is a bool or a string that parses to a bool. If not, raise a ValueError; the what argument names the object. ''' if isinstance(obj, str): as_bool = { 'true': True, 'false': False, '1': True, '0': False }.get(obj.lower()) if as_bool is None: raise ValueError('{} is {!r}, which cannot be parsed as a bool.' .format(what, obj)) return as_bool if obj is True or obj is False: return obj raise ValueError('{} is of type {}, not a bool.' .format(what, type(obj).__name__)) def check_list(obj: object, what: str) -> List[object]: '''Check that the given object is a list If not, raise a ValueError; the what argument names the object. ''' if not isinstance(obj, list): raise ValueError('{} is of type {}, not a list.' .format(what, type(obj).__name__)) return obj def check_str_list(obj: object, what: str) -> List[str]: '''Check that the given object is a list of strings If not, raise a ValueError; the what argument names the object. ''' lst = check_list(obj, what) for idx, elt in enumerate(lst): if not isinstance(elt, str): raise ValueError('Element {} of {} is of type {}, ' 'not a string.' .format(idx, what, type(elt).__name__)) return cast(List[str], lst) def check_name_list(obj: object, what: str) -> List[str]: '''Check that the given object is a list of valid names If not, raise a ValueError; the what argument names the object. ''' lst = check_list(obj, what) for idx, elt in enumerate(lst): check_name(elt, 'Element {} of {}'.format(idx + 1, what)) return cast(List[str], lst) def check_int(obj: object, what: str) -> int: '''Check that obj is an integer or a string that parses to an integer. If not, raise a ValueError; the what argument names the object. ''' if isinstance(obj, int): return obj if isinstance(obj, str): try: return int(obj, 0) except ValueError: raise ValueError('{} is {!r}, which cannot be parsed as an int.' .format(what, obj)) from None raise ValueError('{} is of type {}, not an integer.' .format(what, type(obj).__name__)) def check_xint(obj: object, what: str) -> Optional[int]: '''Check that obj is an integer, a string that parses to an integer or "x". On success, return an integer value if there is one or None if the value was 'x'. On failure, raise a ValueError; the what argument names the object. ''' if isinstance(obj, int): return obj if isinstance(obj, str): if obj == 'x': return None try: return int(obj, 0) except ValueError: raise ValueError('{} is {!r}, which is not "x", ' 'nor can it be parsed as an int.' .format(what, obj)) from None raise ValueError('{} is of type {}, not an integer.' .format(what, type(obj).__name__)) def check_optional_str(obj: object, what: str) -> Optional[str]: '''Check that obj is a string or None''' return None if obj is None else check_str(obj, what) def get_basename(name: str) -> str: '''Strip trailing _number (used as multireg suffix) from name''' # TODO: This is a workaround, should solve this as part of parsing a # multi-reg. match = re.search(r'_[0-9]+$', name) assert match assert match.start() > 0 return name[0:match.start()]
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict, List from reggen import register from .field import Field from .lib import check_keys, check_str, check_name, check_bool from .params import ReggenParams from .reg_base import RegBase from .register import Register REQUIRED_FIELDS = { 'name': ['s', "base name of the registers"], 'desc': ['t', "description of the registers"], 'count': [ 's', "number of instances to generate." " This field can be integer or string matching" " from param_list." ], 'cname': [ 's', "base name for each instance, mostly" " useful for referring to instance in messages." ], 'fields': [ 'l', "list of register field description" " groups. Describes bit positions used for" " base instance." ] } OPTIONAL_FIELDS = register.OPTIONAL_FIELDS.copy() OPTIONAL_FIELDS.update({ 'regwen_multi': [ 'pb', "If true, regwen term increments" " along with current multireg count." ], 'compact': [ 'pb', "If true, allow multireg compacting." "If false, do not compact." ] }) class MultiRegister(RegBase): def __init__(self, offset: int, addrsep: int, reg_width: int, params: ReggenParams, raw: object): super().__init__(offset) rd = check_keys(raw, 'multireg', list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) # Now that we've checked the schema of rd, we make a "reg" version of # it that removes any fields that are allowed by MultiRegister but # aren't allowed by Register. We'll pass that to the register factory # method. reg_allowed_keys = (set(register.REQUIRED_FIELDS.keys()) | set(register.OPTIONAL_FIELDS.keys())) reg_rd = {key: value for key, value in rd.items() if key in reg_allowed_keys} self.reg = Register.from_raw(reg_width, offset, params, reg_rd) self.cname = check_name(rd['cname'], 'cname field of multireg {}' .format(self.reg.name)) self.regwen_multi = check_bool(rd.get('regwen_multi', False), 'regwen_multi field of multireg {}' .format(self.reg.name)) default_compact = True if len(self.reg.fields) == 1 else False self.compact = check_bool(rd.get('compact', default_compact), 'compact field of multireg {}' .format(self.reg.name)) if self.compact and len(self.reg.fields) > 1: raise ValueError('Multireg {} sets the compact flag ' 'but has multiple fields.' .format(self.reg.name)) count_str = check_str(rd['count'], 'count field of multireg {}' .format(self.reg.name)) self.count = params.expand(count_str, 'count field of multireg ' + self.reg.name) if self.count <= 0: raise ValueError("Multireg {} has a count of {}, " "which isn't positive." .format(self.reg.name, self.count)) # Generate the registers that this multireg expands into. Here, a # "creg" is a "compacted register", which might contain multiple actual # registers. if self.compact: assert len(self.reg.fields) == 1 width_per_reg = self.reg.fields[0].bits.msb + 1 assert width_per_reg <= reg_width regs_per_creg = reg_width // width_per_reg else: regs_per_creg = 1 self.regs = [] creg_count = (self.count + regs_per_creg - 1) // regs_per_creg for creg_idx in range(creg_count): min_reg_idx = regs_per_creg * creg_idx max_reg_idx = min(min_reg_idx + regs_per_creg, self.count) - 1 creg_offset = offset + creg_idx * addrsep reg = self.reg.make_multi(reg_width, creg_offset, creg_idx, creg_count, self.regwen_multi, self.compact, min_reg_idx, max_reg_idx, self.cname) self.regs.append(reg) def next_offset(self, addrsep: int) -> int: return self.offset + len(self.regs) * addrsep def get_n_bits(self, bittype: List[str] = ["q"]) -> int: return sum(reg.get_n_bits(bittype) for reg in self.regs) def get_field_list(self) -> List[Field]: ret = [] for reg in self.regs: ret += reg.get_field_list() return ret def is_homogeneous(self) -> bool: return self.reg.is_homogeneous() def _asdict(self) -> Dict[str, object]: rd = self.reg._asdict() rd['count'] = str(self.count) rd['cname'] = self.cname rd['regwen_multi'] = str(self.regwen_multi) rd['compact'] = str(self.compact) return {'multireg': rd}
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import re from collections.abc import MutableMapping from typing import Dict, List, Optional, Tuple from .lib import check_keys, check_str, check_int, check_bool, check_list REQUIRED_FIELDS = { 'name': ['s', "name of the item"], } OPTIONAL_FIELDS = { 'desc': ['s', "description of the item"], 'type': ['s', "item type. int by default"], 'default': ['s', "item default value"], 'local': ['pb', "to be localparam"], 'expose': ['pb', "to be exposed to top"], 'randcount': [ 's', "number of bits to randomize in the parameter. 0 by default." ], 'randtype': ['s', "type of randomization to perform. none by default"], } class BaseParam: def __init__(self, name: str, desc: Optional[str], param_type: str): self.name = name self.desc = desc self.param_type = param_type def apply_default(self, value: str) -> None: if self.param_type[:3] == 'int': check_int(value, 'default value for parameter {} ' '(which has type {})' .format(self.name, self.param_type)) self.default = value def as_dict(self) -> Dict[str, object]: rd = {} # type: Dict[str, object] rd['name'] = self.name if self.desc is not None: rd['desc'] = self.desc rd['type'] = self.param_type return rd class LocalParam(BaseParam): def __init__(self, name: str, desc: Optional[str], param_type: str, value: str): super().__init__(name, desc, param_type) self.value = value def expand_value(self, when: str) -> int: try: return int(self.value, 0) except ValueError: raise ValueError("When {}, the {} value expanded as " "{}, which doesn't parse as an integer." .format(when, self.name, self.value)) from None def as_dict(self) -> Dict[str, object]: rd = super().as_dict() rd['local'] = True rd['default'] = self.value return rd class Parameter(BaseParam): def __init__(self, name: str, desc: Optional[str], param_type: str, default: str, expose: bool): super().__init__(name, desc, param_type) self.default = default self.expose = expose def as_dict(self) -> Dict[str, object]: rd = super().as_dict() rd['default'] = self.default rd['expose'] = 'true' if self.expose else 'false' return rd class RandParameter(BaseParam): def __init__(self, name: str, desc: Optional[str], param_type: str, randcount: int, randtype: str): assert randcount > 0 assert randtype in ['perm', 'data'] super().__init__(name, desc, param_type) self.randcount = randcount self.randtype = randtype def apply_default(self, value: str) -> None: raise ValueError('Cannot apply a default value of {!r} to ' 'parameter {}: it is a random netlist constant.' .format(self.name, value)) def as_dict(self) -> Dict[str, object]: rd = super().as_dict() rd['randcount'] = self.randcount rd['randtype'] = self.randtype return rd def _parse_parameter(where: str, raw: object) -> BaseParam: rd = check_keys(raw, where, list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) # TODO: Check if PascalCase or ALL_CAPS name = check_str(rd['name'], 'name field of ' + where) r_desc = rd.get('desc') if r_desc is None: desc = None else: desc = check_str(r_desc, 'desc field of ' + where) # TODO: We should probably check that any register called RndCnstFoo has # randtype and randcount. if name.lower().startswith('rndcnst') and 'randtype' in rd: # This is a random netlist constant and should be parsed as a # RandParameter. randtype = check_str(rd.get('randtype', 'none'), 'randtype field of ' + where) if randtype not in ['perm', 'data']: raise ValueError('At {}, parameter {} has a name that implies it ' 'is a random netlist constant, which means it ' 'must specify a randtype of "perm" or "data", ' 'rather than {!r}.' .format(where, name, randtype)) r_randcount = rd.get('randcount') if r_randcount is None: raise ValueError('At {}, the random netlist constant {} has no ' 'randcount field.' .format(where, name)) randcount = check_int(r_randcount, 'randcount field of ' + where) if randcount <= 0: raise ValueError('At {}, the random netlist constant {} has a ' 'randcount of {}, which is not positive.' .format(where, name, randcount)) r_type = rd.get('type') if r_type is None: raise ValueError('At {}, parameter {} has no type field (which is ' 'required for random netlist constants).' .format(where, name)) param_type = check_str(r_type, 'type field of ' + where) local = check_bool(rd.get('local', 'false'), 'local field of ' + where) if local: raise ValueError('At {}, the parameter {} specifies local = true, ' 'meaning that it is a localparam. This is ' 'incompatible with being a random netlist ' 'constant (how would it be set?)' .format(where, name)) r_default = rd.get('default') if r_default is not None: raise ValueError('At {}, the parameter {} specifies a value for ' 'the "default" field. This is incompatible with ' 'being a random netlist constant: the value will ' 'be set by the random generator.' .format(where, name)) expose = check_bool(rd.get('expose', 'false'), 'expose field of ' + where) if expose: raise ValueError('At {}, the parameter {} specifies expose = ' 'true, meaning that the parameter is exposed to ' 'the top-level. This is incompatible with being ' 'a random netlist constant.' .format(where, name)) return RandParameter(name, desc, param_type, randcount, randtype) # This doesn't have a name like a random netlist constant. Check that it # doesn't define randcount or randtype. for fld in ['randcount', 'randtype']: if fld in rd: raise ValueError("At {where}, the parameter {name} specifies " "{fld} but the name doesn't look like a random " "netlist constant. To use {fld}, prefix the name " "with RndCnst." .format(where=where, name=name, fld=fld)) r_type = rd.get('type') if r_type is None: param_type = 'int' else: param_type = check_str(r_type, 'type field of ' + where) local = check_bool(rd.get('local', 'true'), 'local field of ' + where) expose = check_bool(rd.get('expose', 'false'), 'expose field of ' + where) r_default = rd.get('default') if r_default is None: raise ValueError('At {}, the {} param has no default field.' .format(where, name)) else: default = check_str(r_default, 'default field of ' + where) if param_type[:3] == 'int': check_int(default, 'default field of {}, (an integer parameter)' .format(name)) if local: if expose: raise ValueError('At {}, the localparam {} cannot be exposed to ' 'the top-level.' .format(where, name)) return LocalParam(name, desc, param_type, value=default) else: return Parameter(name, desc, param_type, default, expose) class Params(MutableMapping): def __init__(self) -> None: self.by_name = {} # type: Dict[str, BaseParam] def __getitem__(self, key): return self.by_name[key] def __delitem__(self, key): del self.by_name[key] def __setitem__(self, key, value): self.by_name[key] = value def __iter__(self): return iter(self.by_name) def __len__(self): return len(self.by_name) def __repr__(self): return f"{type(self).__name__}({self.by_name})" def add(self, param: BaseParam) -> None: assert param.name not in self.by_name self.by_name[param.name] = param def apply_defaults(self, defaults: List[Tuple[str, str]]) -> None: for idx, (key, value) in enumerate(defaults): param = self.by_name[key] if param is None: raise KeyError('Cannot find parameter ' '{} to set default value.' .format(key)) param.apply_default(value) def _expand_one(self, value: str, when: str) -> int: # Check whether value is already an integer: if so, return that. try: return int(value, 0) except ValueError: pass param = self.by_name.get(value) if param is None: raise ValueError('Cannot find a parameter called {} when {}. ' 'Known parameters: {}.' .format(value, when, ', '.join(self.by_name.keys()))) # Only allow localparams in the expansion (because otherwise we're at # the mercy of whatever instantiates the block). if not isinstance(param, LocalParam): raise ValueError("When {}, {} is a not a local parameter." .format(when, value)) return param.expand_value(when) def expand(self, value: str, where: str) -> int: # Here, we want to support arithmetic expressions with + and -. We # don't support other operators, or parentheses (so can parse with just # a regex). # # Use re.split, capturing the operators. This turns e.g. "a + b-c" into # ['a ', '+', ' b', '-', 'c']. If there's a leading operator ("+a"), # the first element of the results is an empty string. This means # elements with odd positions are always operators and elements with # even positions are values. acc = 0 is_neg = False for idx, tok in enumerate(re.split(r'([+-])', value)): if idx == 0 and not tok: continue if idx % 2: is_neg = (tok == '-') continue term = self._expand_one(tok.strip(), 'expanding term {} of {}' .format(idx // 2, where)) acc += -term if is_neg else term return acc def as_dicts(self) -> List[Dict[str, object]]: return [p.as_dict() for p in self.by_name.values()] class ReggenParams(Params): @staticmethod def from_raw(where: str, raw: object) -> 'ReggenParams': ret = ReggenParams() rl = check_list(raw, where) for idx, r_param in enumerate(rl): entry_where = 'entry {} in {}'.format(idx + 1, where) param = _parse_parameter(entry_where, r_param) if param.name in ret: raise ValueError('At {}, found a duplicate parameter with ' 'name {}.' .format(entry_where, param.name)) ret.add(param) return ret def get_localparams(self) -> List[LocalParam]: ret = [] for param in self.by_name.values(): if isinstance(param, LocalParam): ret.append(param) return ret
# Register generator `reggen` and `regtool` The utility script `regtool.py` and collateral under `reggen` are Python tools to read register descriptions in Hjson and generate various output formats. The tool can output HTML documentation, standard JSON, compact standard JSON (whitespace removed) and Hjson. The example commands assume `$REPO_TOP` is set to the toplevel directory of the repository. ### Setup If packages have not previously been installed you will need to set a few things up. First use `pip3` to install some required packages: ```console $ pip3 install --user hjson $ pip3 install --user mistletoe $ pip3 install --user mako ``` ### Register JSON Format For details on the register JSON format, see the [register tool documentation]({{< relref "doc/rm/register_tool/index.md" >}}). To ensure things stay up to date, the register JSON format information is documented by the tool itself. The documentation can be generated by running the following commands: ```console $ cd $REPO_TOP/util $ ./build_docs.py ``` Under the hood, the `build_docs.py` tool will automatically use the `reggen` tool to produce Markdown and processing that into HTML. ### Examples using standalone regtool Normally for documentation the `build_docs.py` tool will automatically use `reggen`. The script `regtool.py` provides a standalone way to run `reggen`. See the [register tool documentation]({{< relref "doc/rm/register_tool/index.md" >}}) for details about how to invoke the tool. The following shows an example of how to generate RTL from a register description: ```console $ cd $REPO_TOP/util $ mkdir /tmp/rtl $ ./regtool.py -r -t /tmp/rtl ../hw/ip/uart/data/uart.hjson $ ls /tmp/rtl uart_reg_pkg.sv uart_reg_top.sv ``` The following shows an example of how to generate a DV UVM class from a register description: ```console $ cd $REPO_TOP/util $ mkdir /tmp/dv $ ./regtool.py -s -t /tmp/dv ../hw/ip/uart/data/uart.hjson $ ls /tmp/dv uart_ral_pkg.sv ``` By default, the generated block, register and field models are derived from `dv_base_reg` classes provided at `hw/dv/sv/dv_base_reg`. If required, the user can supply the `--dv-base-prefix my_base` switch to have the models derive from a custom, user-defined RAL classes instead: ```console $ cd $REPO_TOP/util $ mkdir /tmp/dv $ ./regtool.py -s -t /tmp/dv ../hw/ip/uart/data/uart.hjson \ --dv-base-prefix my_base $ ls /tmp/dv uart_ral_pkg.sv ``` This makes the following assumptions: - A FuseSoC core file aggregating the `my_base` RAL classes with the VLNV name `lowrisc:dv:my_base_reg` is provided in the cores search path. - These custom classes are derived from the corresponding `dv_base_reg` classes and have the following names: - `my_base_reg_pkg.sv`: The RAL package that includes the below sources - `my_base_reg_block.sv`: The register block abstraction - `my_base_reg.sv`: The register abstraction - `my_base_reg_field.sv`: The register field abstraction - `my_base_mem.sv`: The memory abstraction - If any of the above class specializations is not needed, it can be `typedef`'ed in `my_base_reg_pkg`: ```systemverilog package my_base_reg_pkg; import dv_base_reg_pkg::*; typedef dv_base_reg_field my_base_reg_field; typedef dv_base_mem my_base_mem; `include "my_base_reg.sv" `include "my_base_reg_block.sv" endpackage ``` The following shows an example of how to generate a FPV csr read write assertion module from a register description: ```console $ cd $REPO_TOP/util $ mkdir /tmp/fpv/vip $ ./regtool.py -f -t /tmp/fpv/vip ../hw/ip/uart/data/uart.hjson $ ls /tmp/fpv uart_csr_assert_fpv.sv ``` If the target directory is not specified, the tool creates the DV file under the `hw/ip/{module}/dv/` directory.
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict, List, Optional from .access import SWAccess, HWAccess from .field import Field from .lib import (check_keys, check_str, check_name, check_bool, check_list, check_str_list, check_int) from .params import ReggenParams from .reg_base import RegBase REQUIRED_FIELDS = { 'name': ['s', "name of the register"], 'desc': ['t', "description of the register"], 'fields': ['l', "list of register field description groups"] } OPTIONAL_FIELDS = { 'swaccess': [ 's', "software access permission to use for " "fields that don't specify swaccess" ], 'hwaccess': [ 's', "hardware access permission to use for " "fields that don't specify hwaccess" ], 'hwext': [ 's', "'true' if the register is stored outside " "of the register module" ], 'hwqe': [ 's', "'true' if hardware uses 'q' enable signal, " "which is latched signal of software write pulse." ], 'hwre': [ 's', "'true' if hardware uses 're' signal, " "which is latched signal of software read pulse." ], 'regwen': [ 's', "if register is write-protected by another register, that " "register name should be given here. empty-string for no register " "write protection" ], 'resval': [ 'd', "reset value of full register (default 0)" ], 'tags': [ 's', "tags for the register, following the format 'tag_name:item1:item2...'" ], 'shadowed': [ 's', "'true' if the register is shadowed" ], 'update_err_alert': [ 's', "alert that will be triggered if " "this shadowed register has update error" ], 'storage_err_alert': [ 's', "alert that will be triggered if " "this shadowed register has storage error" ] } class Register(RegBase): '''Code representing a register for reggen''' def __init__(self, offset: int, name: str, desc: str, swaccess: SWAccess, hwaccess: HWAccess, hwext: bool, hwqe: bool, hwre: bool, regwen: Optional[str], tags: List[str], resval: Optional[int], shadowed: bool, fields: List[Field], update_err_alert: Optional[str], storage_err_alert: Optional[str]): super().__init__(offset) self.name = name self.desc = desc self.swaccess = swaccess self.hwaccess = hwaccess self.hwext = hwext if self.hwext and self.hwaccess.key == 'hro' and self.sw_readable(): raise ValueError('hwext flag for {} register is set, but ' 'hwaccess is hro and the register value ' 'is readable by software mode ({}).' .format(self.name, self.swaccess.key)) self.hwqe = hwqe if self.hwext and not self.hwqe and self.sw_writable(): raise ValueError('The {} register has hwext set and is writable ' 'by software (mode {}), so must also have hwqe ' 'enabled.' .format(self.name, self.swaccess.key)) self.hwre = hwre if self.hwre and not self.hwext: raise ValueError('The {} register specifies hwre but not hwext.' .format(self.name)) self.regwen = regwen self.tags = tags self.shadowed = shadowed sounds_shadowy = self.name.lower().endswith('_shadowed') if self.shadowed and not sounds_shadowy: raise ValueError("Register {} has the shadowed flag but its name " "doesn't end with the _shadowed suffix." .format(self.name)) elif sounds_shadowy and not self.shadowed: raise ValueError("Register {} has a name ending in _shadowed, but " "the shadowed flag is not set." .format(self.name)) # Take a copy of fields and then sort by bit index assert fields self.fields = fields.copy() self.fields.sort(key=lambda field: field.bits.lsb) # Index fields by name and check for duplicates self.name_to_field = {} # type: Dict[str, Field] for field in self.fields: if field.name in self.name_to_field: raise ValueError('Register {} has duplicate fields called {}.' .format(self.name, field.name)) self.name_to_field[field.name] = field # Check that field bits are disjoint bits_used = 0 for field in self.fields: field_mask = field.bits.bitmask() if bits_used & field_mask: raise ValueError('Register {} has non-disjoint fields: ' '{} uses bits {:#x} used by other fields.' .format(self.name, field.name, bits_used & field_mask)) # Compute a reset value and mask from our constituent fields. self.resval = 0 self.resmask = 0 for field in self.fields: self.resval |= (field.resval or 0) << field.bits.lsb self.resmask |= field.bits.bitmask() # If the register defined a reset value, make sure it matches. We've # already checked that each field matches, but we still need to make # sure there weren't any bits unaccounted for. if resval is not None and self.resval != resval: raise ValueError('Register {} specifies a reset value of {:#x} but ' 'collecting reset values across its fields yields ' '{:#x}.' .format(self.name, resval, self.resval)) self.update_err_alert = update_err_alert self.storage_err_alert = storage_err_alert @staticmethod def from_raw(reg_width: int, offset: int, params: ReggenParams, raw: object) -> 'Register': rd = check_keys(raw, 'register', list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) name = check_name(rd['name'], 'name of register') desc = check_str(rd['desc'], 'desc for {} register'.format(name)) swaccess = SWAccess('{} register'.format(name), rd.get('swaccess', 'none')) hwaccess = HWAccess('{} register'.format(name), rd.get('hwaccess', 'hro')) hwext = check_bool(rd.get('hwext', False), 'hwext flag for {} register'.format(name)) hwqe = check_bool(rd.get('hwqe', False), 'hwqe flag for {} register'.format(name)) hwre = check_bool(rd.get('hwre', False), 'hwre flag for {} register'.format(name)) raw_regwen = rd.get('regwen', '') if not raw_regwen: regwen = None else: regwen = check_name(raw_regwen, 'regwen for {} register'.format(name)) tags = check_str_list(rd.get('tags', []), 'tags for {} register'.format(name)) raw_resval = rd.get('resval') if raw_resval is None: resval = None else: resval = check_int(raw_resval, 'resval for {} register'.format(name)) if not 0 <= resval < (1 << reg_width): raise ValueError('resval for {} register is {}, ' 'not an unsigned {}-bit number.' .format(name, resval, reg_width)) shadowed = check_bool(rd.get('shadowed', False), 'shadowed flag for {} register' .format(name)) raw_fields = check_list(rd['fields'], 'fields for {} register'.format(name)) if not raw_fields: raise ValueError('Register {} has no fields.'.format(name)) fields = [Field.from_raw(name, idx, len(raw_fields), swaccess, hwaccess, resval, reg_width, hwqe, hwre, params, rf) for idx, rf in enumerate(raw_fields)] raw_uea = rd.get('update_err_alert') if raw_uea is None: update_err_alert = None else: update_err_alert = check_name(raw_uea, 'update_err_alert for {} register' .format(name)) raw_sea = rd.get('storage_err_alert') if raw_sea is None: storage_err_alert = None else: storage_err_alert = check_name(raw_sea, 'storage_err_alert for {} register' .format(name)) return Register(offset, name, desc, swaccess, hwaccess, hwext, hwqe, hwre, regwen, tags, resval, shadowed, fields, update_err_alert, storage_err_alert) def next_offset(self, addrsep: int) -> int: return self.offset + addrsep def sw_readable(self) -> bool: return self.swaccess.key not in ['wo', 'r0w1c'] def sw_writable(self) -> bool: return self.swaccess.key != 'ro' def dv_rights(self) -> str: return self.swaccess.dv_rights() def get_n_bits(self, bittype: List[str]) -> int: return sum(field.get_n_bits(self.hwext, bittype) for field in self.fields) def get_field_list(self) -> List[Field]: return self.fields def is_homogeneous(self) -> bool: return len(self.fields) == 1 def get_width(self) -> int: '''Get the width of the fields in the register in bits This counts dead space between and below fields, so it's calculated as one more than the highest msb. ''' # self.fields is ordered by (increasing) LSB, so we can find the MSB of # the register by taking the MSB of the last field. return 1 + self.fields[-1].bits.msb def make_multi(self, reg_width: int, offset: int, creg_idx: int, creg_count: int, regwen_multi: bool, compact: bool, min_reg_idx: int, max_reg_idx: int, cname: str) -> 'Register': '''Generate a numbered, packed version of the register''' assert 0 <= creg_idx < creg_count assert 0 <= min_reg_idx <= max_reg_idx assert compact or (min_reg_idx == max_reg_idx) new_name = ('{}_{}'.format(self.name, creg_idx) if creg_count > 1 else self.name) if self.regwen is None or not regwen_multi or creg_count == 1: new_regwen = self.regwen else: new_regwen = '{}_{}'.format(self.regwen, creg_idx) strip_field = creg_idx > 0 if compact: # Compacting multiple registers into a single "compacted" register. # This is only supported if we have exactly one field (checked at # the call-site) assert len(self.fields) == 1 new_fields = self.fields[0].make_multi(reg_width, min_reg_idx, max_reg_idx, cname, creg_idx, strip_field) else: # No compacting going on, but we still choose to rename the fields # to match the registers assert creg_idx == min_reg_idx new_fields = [field.make_suffixed('_{}'.format(creg_idx), cname, creg_idx, strip_field) for field in self.fields] # Don't specify a reset value for the new register. Any reset value # defined for the original register will have propagated to its fields, # so when we combine them here, the Register constructor can compute a # reset value for us (which might well be different from self.resval if # we've replicated fields). new_resval = None return Register(offset, new_name, self.desc, self.swaccess, self.hwaccess, self.hwext, self.hwqe, self.hwre, new_regwen, self.tags, new_resval, self.shadowed, new_fields, self.update_err_alert, self.storage_err_alert) def _asdict(self) -> Dict[str, object]: rd = { 'name': self.name, 'desc': self.desc, 'fields': self.fields, 'swaccess': self.swaccess.key, 'hwaccess': self.hwaccess.key, 'hwext': str(self.hwext), 'hwqe': str(self.hwqe), 'hwre': str(self.hwre), 'tags': self.tags, 'shadowed': str(self.shadowed), } if self.regwen is not None: rd['regwen'] = self.regwen if self.update_err_alert is not None: rd['update_err_alert'] = self.update_err_alert if self.storage_err_alert is not None: rd['storage_err_alert'] = self.storage_err_alert return rd
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import List from .field import Field class RegBase: '''An abstract class inherited by Register and MultiRegister This represents a block of one or more registers with a base address. ''' def __init__(self, offset: int): self.offset = offset def get_n_bits(self, bittype: List[str]) -> int: '''Get the size of this register / these registers in bits See Field.get_n_bits() for the precise meaning of bittype. ''' raise NotImplementedError() def get_field_list(self) -> List[Field]: '''Get an ordered list of the fields in the register(s) Registers are ordered from low to high address. Within a register, fields are ordered as Register.fields: from LSB to MSB. ''' raise NotImplementedError() def is_homogeneous(self) -> bool: '''True if every field in the block is identical For a single register, this is true if it only has one field. For a multireg, it is true if the generating register has just one field. Note that if the compact flag is set, the generated registers might have multiple (replicated) fields. ''' raise NotImplementedError()
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Code representing the registers, windows etc. for a block''' import re from typing import Callable, Dict, List, Optional, Sequence, Union from .alert import Alert from .access import SWAccess, HWAccess from .field import Field from .signal import Signal from .lib import check_int, check_list, check_str_dict, check_str from .multi_register import MultiRegister from .params import ReggenParams from .register import Register from .window import Window class RegBlock: def __init__(self, reg_width: int, params: ReggenParams): self._addrsep = (reg_width + 7) // 8 self._reg_width = reg_width self._params = params self.offset = 0 self.multiregs = [] # type: List[MultiRegister] self.registers = [] # type: List[Register] self.windows = [] # type: List[Window] # Boolean indication whether ANY window in regblock has data integrity passthrough self.has_data_intg_passthru = False # A list of all registers, expanding multiregs, ordered by offset self.flat_regs = [] # type: List[Register] # A list of registers and multiregisters (unexpanded) self.all_regs = [] # type: List[Union[Register, MultiRegister]] # A list with everything in order self.entries = [] # type: List[object] # A dict of named entries, mapping name to offset self.name_to_offset = {} # type: Dict[str, int] # A dict of all registers (expanding multiregs), mapping name to the # register object self.name_to_flat_reg = {} # type: Dict[str, Register] # A list of all write enable names self.wennames = [] # type: List[str] @staticmethod def build_blocks(block: 'RegBlock', raw: object) -> Dict[Optional[str], 'RegBlock']: '''Build a dictionary of blocks for a 'registers' field in the hjson There are two different syntaxes we might see here. The simple syntax just consists of a list of entries (register, multireg, window, skipto). If we see that, each entry gets added to init_block and then we return {None: init_block}. The more complicated syntax is a dictionary. This parses from hjson as an OrderedDict which we walk in document order. Entries from the first key/value pair in the dictionary will be added to init_block. Later key/value pairs start empty RegBlocks. The return value is a dictionary mapping the keys we saw to their respective RegBlocks. ''' if isinstance(raw, list): # This is the simple syntax block.add_raw_registers(raw, 'registers field at top-level') return {None: block} # This is the more complicated syntax if not isinstance(raw, dict): raise ValueError('registers field at top-level is ' 'neither a list or a dictionary.') ret = {} # type: Dict[Optional[str], RegBlock] for idx, (r_key, r_val) in enumerate(raw.items()): if idx > 0: block = RegBlock(block._reg_width, block._params) rb_key = check_str(r_key, 'the key for item {} of ' 'the registers dictionary at top-level' .format(idx + 1)) rb_val = check_list(r_val, 'the value for item {} of ' 'the registers dictionary at top-level' .format(idx + 1)) block.add_raw_registers(rb_val, 'item {} of the registers ' 'dictionary at top-level' .format(idx + 1)) block.validate() assert rb_key not in ret ret[rb_key] = block return ret def add_raw_registers(self, raw: object, what: str) -> None: rl = check_list(raw, 'registers field at top-level') for entry_idx, entry_raw in enumerate(rl): where = ('entry {} of the top-level registers field' .format(entry_idx + 1)) self.add_raw(where, entry_raw) def add_raw(self, where: str, raw: object) -> None: entry = check_str_dict(raw, where) handlers = { 'register': self._handle_register, 'reserved': self._handle_reserved, 'skipto': self._handle_skipto, 'window': self._handle_window, 'multireg': self._handle_multireg } entry_type = 'register' entry_body = entry # type: object for t in ['reserved', 'skipto', 'window', 'multireg']: t_body = entry.get(t) if t_body is not None: # Special entries look like { window: { ... } }, so if we # get a hit, this should be the only key in entry. Note # that this also checks that nothing has more than one # entry type. if len(entry) != 1: other_keys = [k for k in entry if k != t] assert other_keys raise ValueError('At offset {:#x}, {} has key {}, which ' 'should give its type. But it also has ' 'other keys too: {}.' .format(self.offset, where, t, ', '.join(other_keys))) entry_type = t entry_body = t_body entry_where = ('At offset {:#x}, {}, type {!r}' .format(self.offset, where, entry_type)) handlers[entry_type](entry_where, entry_body) def _handle_register(self, where: str, body: object) -> None: reg = Register.from_raw(self._reg_width, self.offset, self._params, body) self.add_register(reg) def _handle_reserved(self, where: str, body: object) -> None: nreserved = check_int(body, 'body of ' + where) if nreserved <= 0: raise ValueError('Reserved count in {} is {}, ' 'which is not positive.' .format(where, nreserved)) self.offset += self._addrsep * nreserved def _handle_skipto(self, where: str, body: object) -> None: skipto = check_int(body, 'body of ' + where) if skipto < self.offset: raise ValueError('Destination of skipto in {} is {:#x}, ' 'is less than the current offset, {:#x}.' .format(where, skipto, self.offset)) if skipto % self._addrsep: raise ValueError('Destination of skipto in {} is {:#x}, ' 'not a multiple of addrsep, {:#x}.' .format(where, skipto, self._addrsep)) self.offset = skipto def _handle_window(self, where: str, body: object) -> None: window = Window.from_raw(self.offset, self._reg_width, self._params, body) if window.name is not None: lname = window.name.lower() if lname in self.name_to_offset: raise ValueError('Window {} (at offset {:#x}) has the ' 'same name as something at offset {:#x}.' .format(window.name, window.offset, self.name_to_offset[lname])) self.add_window(window) def _handle_multireg(self, where: str, body: object) -> None: mr = MultiRegister(self.offset, self._addrsep, self._reg_width, self._params, body) for reg in mr.regs: lname = reg.name.lower() if lname in self.name_to_offset: raise ValueError('Multiregister {} (at offset {:#x}) expands ' 'to a register with name {} (at offset ' '{:#x}), but this already names something at ' 'offset {:#x}.' .format(mr.reg.name, mr.reg.offset, reg.name, reg.offset, self.name_to_offset[lname])) self._add_flat_reg(reg) self.name_to_offset[lname] = reg.offset self.multiregs.append(mr) self.all_regs.append(mr) self.entries.append(mr) self.offset = mr.next_offset(self._addrsep) def add_register(self, reg: Register) -> None: assert reg.offset == self.offset lname = reg.name.lower() if lname in self.name_to_offset: raise ValueError('Register {} (at offset {:#x}) has the same ' 'name as something at offset {:#x}.' .format(reg.name, reg.offset, self.name_to_offset[lname])) self._add_flat_reg(reg) self.name_to_offset[lname] = reg.offset self.registers.append(reg) self.all_regs.append(reg) self.entries.append(reg) self.offset = reg.next_offset(self._addrsep) if reg.regwen is not None and reg.regwen not in self.wennames: self.wennames.append(reg.regwen) def _add_flat_reg(self, reg: Register) -> None: # The first assertion is checked at the call site (where we can print # out a nicer message for multiregs). The second assertion should be # implied by the first. assert reg.name not in self.name_to_offset assert reg.name not in self.name_to_flat_reg self.flat_regs.append(reg) self.name_to_flat_reg[reg.name.lower()] = reg def add_window(self, window: Window) -> None: if window.name is not None: lname = window.name.lower() assert lname not in self.name_to_offset self.name_to_offset[lname] = window.offset self.windows.append(window) self.entries.append(window) assert self.offset <= window.offset self.offset = window.next_offset(self._addrsep) self.has_data_intg_passthru |= window.data_intg_passthru def validate(self) -> None: '''Run this to check consistency after all registers have been added''' # Check that every write-enable register has a good name, a valid reset # value, and valid access permissions. for wenname in self.wennames: # check the REGWEN naming convention if re.fullmatch(r'(.+_)*REGWEN(_[0-9]+)?', wenname) is None: raise ValueError("Regwen name {} must have the suffix '_REGWEN'" .format(wenname)) wen_reg = self.name_to_flat_reg.get(wenname.lower()) if wen_reg is None: raise ValueError('One or more registers use {} as a ' 'write-enable, but there is no such register.' .format(wenname)) # If the REGWEN bit is SW controlled, check that the register # defaults to enabled. If this bit is read-only by SW and hence # hardware controlled, we do not enforce this requirement. if wen_reg.swaccess.key != "ro" and not wen_reg.resval: raise ValueError('One or more registers use {} as a ' 'write-enable. Since it is SW-controlled ' 'it should have a nonzero reset value.' .format(wenname)) if wen_reg.swaccess.key == "rw0c": # The register is software managed: all good! continue if wen_reg.swaccess.key == "ro" and wen_reg.hwaccess.key == "hwo": # The register is hardware managed: that's fine too. continue raise ValueError('One or more registers use {} as a write-enable. ' 'However, it has invalid access permissions ' '({} / {}). It should either have swaccess=RW0C ' 'or have swaccess=RO and hwaccess=HWO.' .format(wenname, wen_reg.swaccess.key, wen_reg.hwaccess.key)) def get_n_bits(self, bittype: List[str] = ["q"]) -> int: '''Returns number of bits in registers in this block. This includes those expanded from multiregs. See Field.get_n_bits for a description of the bittype argument. ''' return sum(reg.get_n_bits(bittype) for reg in self.flat_regs) def as_dicts(self) -> List[object]: entries = [] # type: List[object] offset = 0 for entry in self.entries: assert (isinstance(entry, Register) or isinstance(entry, MultiRegister) or isinstance(entry, Window)) next_off = entry.offset assert offset <= next_off res_bytes = next_off - offset if res_bytes: assert res_bytes % self._addrsep == 0 entries.append({'reserved': res_bytes // self._addrsep}) entries.append(entry) offset = entry.next_offset(self._addrsep) return entries _FieldFormatter = Callable[[bool, str], str] def _add_intr_alert_reg(self, signals: Sequence[Signal], reg_name: str, reg_desc: str, field_desc_fmt: Optional[Union[str, _FieldFormatter]], swaccess: str, hwaccess: str, is_testreg: bool, reg_tags: List[str]) -> None: swaccess_obj = SWAccess('RegBlock._make_intr_alert_reg()', swaccess) hwaccess_obj = HWAccess('RegBlock._make_intr_alert_reg()', hwaccess) fields = [] for signal in signals: if field_desc_fmt is None: field_desc = signal.desc elif isinstance(field_desc_fmt, str): field_desc = field_desc_fmt else: width = signal.bits.width() field_desc = field_desc_fmt(width > 1, signal.name) fields.append(Field(signal.name, field_desc or signal.desc, tags=[], swaccess=swaccess_obj, hwaccess=hwaccess_obj, hwqe=is_testreg, hwre=False, bits=signal.bits, resval=0, enum=None)) reg = Register(self.offset, reg_name, reg_desc, swaccess_obj, hwaccess_obj, hwext=is_testreg, hwqe=is_testreg, hwre=False, regwen=None, tags=reg_tags, resval=None, shadowed=False, fields=fields, update_err_alert=None, storage_err_alert=None) self.add_register(reg) def make_intr_regs(self, interrupts: Sequence[Signal]) -> None: assert interrupts assert interrupts[-1].bits.msb < self._reg_width self._add_intr_alert_reg(interrupts, 'INTR_STATE', 'Interrupt State Register', None, 'rw1c', 'hrw', False, # intr_state csr is affected by writes to # other csrs - skip write-check ["excl:CsrNonInitTests:CsrExclWriteCheck"]) self._add_intr_alert_reg(interrupts, 'INTR_ENABLE', 'Interrupt Enable Register', lambda w, n: ('Enable interrupt when ' '{}!!INTR_STATE.{} is set.' .format('corresponding bit in ' if w else '', n)), 'rw', 'hro', False, []) self._add_intr_alert_reg(interrupts, 'INTR_TEST', 'Interrupt Test Register', lambda w, n: ('Write 1 to force ' '{}!!INTR_STATE.{} to 1.' .format('corresponding bit in ' if w else '', n)), 'wo', 'hro', True, # intr_test csr is WO so reads back 0s ["excl:CsrNonInitTests:CsrExclWrite"]) def make_alert_regs(self, alerts: List[Alert]) -> None: assert alerts assert len(alerts) < self._reg_width self._add_intr_alert_reg(alerts, 'ALERT_TEST', 'Alert Test Register', ('Write 1 to trigger ' 'one alert event of this kind.'), 'wo', 'hro', True, []) def get_addr_width(self) -> int: '''Calculate the number of bits to address every byte of the block''' return (self.offset - 1).bit_length()
/* Stylesheet for reggen HTML register output */ /* Copyright lowRISC contributors. */ /* Licensed under the Apache License, Version 2.0, see LICENSE for details. */ /* SPDX-License-Identifier: Apache-2.0 */ table.regpic { width: 95%; border-collapse: collapse; margin-left:auto; margin-right:auto; table-layout:fixed; } table.regdef { border: 1px solid black; width: 80%; border-collapse: collapse; margin-left:auto; margin-right:auto; table-layout:auto; } table.regdef th { border: 1px solid black; font-family: sans-serif; } td.bitnum { font-size: 60%; text-align: center; } td.unused { border: 1px solid black; background-color: gray; } td.fname { border: 1px solid black; text-align: center; font-family: sans-serif; } td.regbits, td.regperm, td.regrv { border: 1px solid black; text-align: center; font-family: sans-serif; } td.regde, td.regfn { border: 1px solid black; } table.cfgtable { border: 1px solid black; width: 80%; border-collapse: collapse; margin-left:auto; margin-right:auto; table-layout:auto; } table.cfgtable th { border: 1px solid black; font-family: sans-serif; font-weight: bold; } table.cfgtable td { border: 1px solid black; font-family: sans-serif; }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Register Package auto-generated by `reggen` containing data structure <% from topgen import lib # TODO: Split lib to common lib module from reggen.access import HwAccess, SwRdAccess, SwWrAccess from reggen.register import Register from reggen.multi_register import MultiRegister from reggen import gen_rtl localparams = block.params.get_localparams() addr_widths = gen_rtl.get_addr_widths(block) lblock = block.name.lower() ublock = lblock.upper() def reg_pfx(reg): return '{}_{}'.format(ublock, reg.name.upper()) def reg_resname(reg): return '{}_RESVAL'.format(reg_pfx(reg)) def field_resname(reg, field): return '{}_{}_RESVAL'.format(reg_pfx(reg), field.name.upper()) %>\ <%def name="typedefs_for_iface(iface_name, iface_desc, for_iface, rb)">\ <% hdr = gen_rtl.make_box_quote('Typedefs for registers' + for_iface) %>\ % for r in rb.all_regs: % if r.get_n_bits(["q"]): % if hdr: ${hdr} % endif <% r0 = gen_rtl.get_r0(r) hdr = None %>\ typedef struct packed { % if r.is_homogeneous(): ## If we have a homogeneous register or multireg, there is just one field ## (possibly replicated many times). The typedef is for one copy of that ## field. <% field = r.get_field_list()[0] field_q_width = field.get_n_bits(r0.hwext, ['q']) field_q_bits = lib.bitarray(field_q_width, 2) %>\ logic ${field_q_bits} q; % if field.hwqe: logic qe; % endif % if field.hwre or (r0.shadowed and r0.hwext): logic re; % endif % if r0.shadowed and not r0.hwext: logic err_update; logic err_storage; % endif % else: ## We are inhomogeneous, which means there is more than one different ## field. Generate a reg2hw typedef that packs together all the fields of ## the register. % for f in r0.fields: % if f.get_n_bits(r0.hwext, ["q"]) >= 1: <% field_q_width = f.get_n_bits(r0.hwext, ['q']) field_q_bits = lib.bitarray(field_q_width, 2) struct_name = f.name.lower() %>\ struct packed { logic ${field_q_bits} q; % if f.hwqe: logic qe; % endif % if f.hwre or (r0.shadowed and r0.hwext): logic re; % endif % if r0.shadowed and not r0.hwext: logic err_update; logic err_storage; % endif } ${struct_name}; %endif %endfor %endif } ${gen_rtl.get_reg_tx_type(block, r, False)}; %endif % endfor % for r in rb.all_regs: % if r.get_n_bits(["d"]): % if hdr: ${hdr} % endif <% r0 = gen_rtl.get_r0(r) hdr = None %>\ typedef struct packed { % if r.is_homogeneous(): ## If we have a homogeneous register or multireg, there is just one field ## (possibly replicated many times). The typedef is for one copy of that ## field. <% field = r.get_field_list()[0] field_d_width = field.get_n_bits(r0.hwext, ['d']) field_d_bits = lib.bitarray(field_d_width, 2) %>\ logic ${field_d_bits} d; % if not r0.hwext: logic de; % endif % else: ## We are inhomogeneous, which means there is more than one different ## field. Generate a hw2reg typedef that packs together all the fields of ## the register. % for f in r0.fields: % if f.get_n_bits(r0.hwext, ["d"]) >= 1: <% field_d_width = f.get_n_bits(r0.hwext, ['d']) field_d_bits = lib.bitarray(field_d_width, 2) struct_name = f.name.lower() %>\ struct packed { logic ${field_d_bits} d; % if not r0.hwext: logic de; % endif } ${struct_name}; %endif %endfor %endif } ${gen_rtl.get_reg_tx_type(block, r, True)}; % endif % endfor </%def>\ <%def name="reg2hw_for_iface(iface_name, iface_desc, for_iface, rb)">\ <% nbits = rb.get_n_bits(["q", "qe", "re"]) packbit = 0 %>\ % if nbits > 0: // Register -> HW type${for_iface} typedef struct packed { % for r in rb.all_regs: % if r.get_n_bits(["q"]): <% r0 = gen_rtl.get_r0(r) struct_type = gen_rtl.get_reg_tx_type(block, r, False) struct_width = r0.get_n_bits(['q', 'qe', 're']) if isinstance(r, MultiRegister): struct_type += " [{}:0]".format(r.count - 1) struct_width *= r.count msb = nbits - packbit - 1 lsb = msb - struct_width + 1 packbit += struct_width %>\ ${struct_type} ${r0.name.lower()}; // [${msb}:${lsb}] % endif % endfor } ${gen_rtl.get_iface_tx_type(block, iface_name, False)}; % endif </%def>\ <%def name="hw2reg_for_iface(iface_name, iface_desc, for_iface, rb)">\ <% nbits = rb.get_n_bits(["d", "de"]) packbit = 0 %>\ % if nbits > 0: // HW -> register type${for_iface} typedef struct packed { % for r in rb.all_regs: % if r.get_n_bits(["d"]): <% r0 = gen_rtl.get_r0(r) struct_type = gen_rtl.get_reg_tx_type(block, r, True) struct_width = r0.get_n_bits(['d', 'de']) if isinstance(r, MultiRegister): struct_type += " [{}:0]".format(r.count - 1) struct_width *= r.count msb = nbits - packbit - 1 lsb = msb - struct_width + 1 packbit += struct_width %>\ ${struct_type} ${r0.name.lower()}; // [${msb}:${lsb}] % endif % endfor } ${gen_rtl.get_iface_tx_type(block, iface_name, True)}; % endif </%def>\ <%def name="offsets_for_iface(iface_name, iface_desc, for_iface, rb)">\ % if not rb.flat_regs: <% return STOP_RENDERING %> % endif // Register offsets${for_iface} <% aw_name, aw = addr_widths[iface_name] %>\ % for r in rb.flat_regs: <% value = "{}'h {:x}".format(aw, r.offset) %>\ parameter logic [${aw_name}-1:0] ${reg_pfx(r)}_OFFSET = ${value}; % endfor </%def>\ <%def name="hwext_resvals_for_iface(iface_name, iface_desc, for_iface, rb)">\ <% hwext_regs = [r for r in rb.flat_regs if r.hwext] %>\ % if hwext_regs: // Reset values for hwext registers and their fields${for_iface} % for reg in hwext_regs: <% reg_width = reg.get_width() reg_msb = reg_width - 1 reg_resval = "{}'h {:x}".format(reg_width, reg.resval) %>\ parameter logic [${reg_msb}:0] ${reg_resname(reg)} = ${reg_resval}; % for field in reg.fields: % if field.resval is not None: <% field_width = field.bits.width() field_msb = field_width - 1 field_resval = "{}'h {:x}".format(field_width, field.resval) %>\ parameter logic [${field_msb}:0] ${field_resname(reg, field)} = ${field_resval}; % endif % endfor % endfor % endif </%def>\ <%def name="windows_for_iface(iface_name, iface_desc, for_iface, rb)">\ % if rb.windows: <% aw_name, aw = addr_widths[iface_name] %>\ // Window parameters${for_iface} % for i,w in enumerate(rb.windows): <% win_pfx = '{}_{}'.format(ublock, w.name.upper()) base_txt_val = "{}'h {:x}".format(aw, w.offset) size_txt_val = "'h {:x}".format(w.size_in_bytes) offset_type = 'logic [{}-1:0]'.format(aw_name) size_type = 'int unsigned' max_type_len = max(len(offset_type), len(size_type)) offset_type += ' ' * (max_type_len - len(offset_type)) size_type += ' ' * (max_type_len - len(size_type)) %>\ parameter ${offset_type} ${win_pfx}_OFFSET = ${base_txt_val}; parameter ${size_type} ${win_pfx}_SIZE = ${size_txt_val}; % endfor % endif </%def>\ <%def name="reg_data_for_iface(iface_name, iface_desc, for_iface, rb)">\ % if rb.flat_regs: <% lpfx = gen_rtl.get_type_name_pfx(block, iface_name) upfx = lpfx.upper() idx_len = len("{}".format(len(rb.flat_regs) - 1)) %>\ // Register index${for_iface} typedef enum int { % for r in rb.flat_regs: ${ublock}_${r.name.upper()}${"" if loop.last else ","} % endfor } ${lpfx}_id_e; // Register width information to check illegal writes${for_iface} parameter logic [3:0] ${upfx}_PERMIT [${len(rb.flat_regs)}] = '{ % for i, r in enumerate(rb.flat_regs): <% index_str = "{}".format(i).rjust(idx_len) width = r.get_width() if width > 24: mask = '1111' elif width > 16: mask = '0111' elif width > 8: mask = '0011' else: mask = '0001' comma = ',' if i < len(rb.flat_regs) - 1 else ' ' %>\ 4'b ${mask}${comma} // index[${index_str}] ${ublock}_${r.name.upper()} % endfor }; % endif </%def>\ package ${lblock}_reg_pkg; % if localparams: // Param list % for param in localparams: parameter ${param.param_type} ${param.name} = ${param.value}; % endfor % endif // Address widths within the block % for param_name, width in addr_widths.values(): parameter int ${param_name} = ${width}; % endfor <% just_default = len(block.reg_blocks) == 1 and None in block.reg_blocks %>\ % for iface_name, rb in block.reg_blocks.items(): <% iface_desc = iface_name or 'default' for_iface = '' if just_default else ' for {} interface'.format(iface_desc) %>\ ${typedefs_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${reg2hw_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${hw2reg_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${offsets_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${hwext_resvals_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${windows_for_iface(iface_name, iface_desc, for_iface, rb)}\ ${reg_data_for_iface(iface_name, iface_desc, for_iface, rb)}\ % endfor endpackage
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Register Top module auto-generated by `reggen` <% from reggen import gen_rtl from reggen.access import HwAccess, SwRdAccess, SwWrAccess from reggen.lib import get_basename from reggen.register import Register from reggen.multi_register import MultiRegister from reggen.ip_block import IpBlock from reggen.bus_interfaces import BusProtocol num_wins = len(rb.windows) num_wins_width = ((num_wins+1).bit_length()) - 1 num_reg_dsp = 1 if rb.all_regs else 0 num_dsp = num_wins + num_reg_dsp regs_flat = rb.flat_regs max_regs_char = len("{}".format(len(regs_flat) - 1)) addr_width = rb.get_addr_width() lblock = block.name.lower() ublock = lblock.upper() u_mod_base = mod_base.upper() reg2hw_t = gen_rtl.get_iface_tx_type(block, if_name, False) hw2reg_t = gen_rtl.get_iface_tx_type(block, if_name, True) # Calculate whether we're going to need an AW parameter. We use it if there # are any registers (obviously). We also use it if there are any windows that # don't start at zero and end at 1 << addr_width (see the "addr_checks" # calculation below for where that comes from). needs_aw = (bool(regs_flat) or num_wins > 1 or rb.windows and ( rb.windows[0].offset != 0 or rb.windows[0].size_in_bytes != (1 << addr_width))) # Check if the interface protocol is reg_interface use_reg_iface = any([interface['protocol'] == BusProtocol.REG_IFACE and not interface['is_host'] for interface in block.bus_interfaces.interface_list]) reg_intf_req = "reg_req_t" reg_intf_rsp = "reg_rsp_t" common_data_intg_gen = 0 if rb.has_data_intg_passthru else 1 adapt_data_intg_gen = 1 if rb.has_data_intg_passthru else 0 assert common_data_intg_gen != adapt_data_intg_gen %> % if use_reg_iface: `include "common_cells/assertions.svh" % else: `include "prim_assert.sv" % endif module ${mod_name} \ % if use_reg_iface: #( parameter type reg_req_t = logic, parameter type reg_rsp_t = logic, parameter int AW = ${addr_width} ) \ % else: % if needs_aw: #( parameter int AW = ${addr_width} ) \ % endif % endif ( input clk_i, input rst_ni, % if use_reg_iface: input ${reg_intf_req} reg_req_i, output ${reg_intf_rsp} reg_rsp_o, % else: input tlul_pkg::tl_h2d_t tl_i, output tlul_pkg::tl_d2h_t tl_o, % endif % if num_wins != 0: // Output port for window % if use_reg_iface: output ${reg_intf_req} [${num_wins}-1:0] reg_req_win_o, input ${reg_intf_rsp} [${num_wins}-1:0] reg_rsp_win_i, % else: output tlul_pkg::tl_h2d_t tl_win_o [${num_wins}], input tlul_pkg::tl_d2h_t tl_win_i [${num_wins}], % endif % endif // To HW % if rb.get_n_bits(["q","qe","re"]): output ${lblock}_reg_pkg::${reg2hw_t} reg2hw, // Write % endif % if rb.get_n_bits(["d","de"]): input ${lblock}_reg_pkg::${hw2reg_t} hw2reg, // Read % endif % if not use_reg_iface: // Integrity check errors output logic intg_err_o, % endif // Config input devmode_i // If 1, explicit error return for unmapped register access ); import ${lblock}_reg_pkg::* ; % if rb.all_regs: localparam int DW = ${block.regwidth}; localparam int DBW = DW/8; // Byte Width // register signals logic reg_we; logic reg_re; logic [AW-1:0] reg_addr; logic [DW-1:0] reg_wdata; logic [DBW-1:0] reg_be; logic [DW-1:0] reg_rdata; logic reg_error; logic addrmiss, wr_err; logic [DW-1:0] reg_rdata_next; % if use_reg_iface: // Below register interface can be changed reg_req_t reg_intf_req; reg_rsp_t reg_intf_rsp; % else: tlul_pkg::tl_h2d_t tl_reg_h2d; tlul_pkg::tl_d2h_t tl_reg_d2h; % endif % endif % if not use_reg_iface: // incoming payload check logic intg_err; tlul_cmd_intg_chk u_chk ( .tl_i, .err_o(intg_err) ); logic intg_err_q; always_ff @(posedge clk_i or negedge rst_ni) begin if (!rst_ni) begin intg_err_q <= '0; end else if (intg_err) begin intg_err_q <= 1'b1; end end // integrity error output is permanent and should be used for alert generation // register errors are transactional assign intg_err_o = intg_err_q | intg_err; // outgoing integrity generation tlul_pkg::tl_d2h_t tl_o_pre; tlul_rsp_intg_gen #( .EnableRspIntgGen(1), .EnableDataIntgGen(${common_data_intg_gen}) ) u_rsp_intg_gen ( .tl_i(tl_o_pre), .tl_o ); % endif % if num_dsp == 1: ## Either no windows (and just registers) or no registers and only ## one window. % if num_wins == 0: % if use_reg_iface: assign reg_intf_req = reg_req_i; assign reg_rsp_o = reg_intf_rsp; % else: assign tl_reg_h2d = tl_i; assign tl_o_pre = tl_reg_d2h; % endif % else: % if use_reg_iface: assign reg_req_win_o = reg_req_i; assign reg_rsp_o = reg_rsp_win_i % else: assign tl_win_o[0] = tl_i; assign tl_o_pre = tl_win_i[0]; % endif % endif % else: logic [${num_wins_width-1}:0] reg_steer; % if use_reg_iface: ${reg_intf_req} [${num_dsp}-1:0] reg_intf_demux_req; ${reg_intf_rsp} [${num_dsp}-1:0] reg_intf_demux_rsp; // demux connection assign reg_intf_req = reg_intf_demux_req[${num_wins}]; assign reg_intf_demux_rsp[${num_wins}] = reg_intf_rsp; % for i,t in enumerate(block.wins): assign reg_req_win_o[${i}] = reg_intf_demux_req[${i}]; assign reg_intf_demux_rsp[${i}] = reg_rsp_win_i[${i}]; % endfor // Create Socket_1n reg_demux #( .NoPorts (${num_dsp}), .req_t (${reg_intf_req}), .rsp_t (${reg_intf_rsp}) ) i_reg_demux ( .clk_i, .rst_ni, .in_req_i (reg_req_i), .in_rsp_o (reg_rsp_o), .out_req_o (reg_intf_demux_req), .out_rsp_i (reg_intf_demux_rsp), .in_select_i (reg_steer) ); % else: tlul_pkg::tl_h2d_t tl_socket_h2d [${num_dsp}]; tlul_pkg::tl_d2h_t tl_socket_d2h [${num_dsp}]; // socket_1n connection % if rb.all_regs: assign tl_reg_h2d = tl_socket_h2d[${num_wins}]; assign tl_socket_d2h[${num_wins}] = tl_reg_d2h; % endif % for i,t in enumerate(rb.windows): assign tl_win_o[${i}] = tl_socket_h2d[${i}]; % if common_data_intg_gen == 0 and rb.windows[i].data_intg_passthru == False: ## If there are multiple windows, and not every window has data integrity ## passthrough, we must generate data integrity for it here. tlul_rsp_intg_gen #( .EnableRspIntgGen(0), .EnableDataIntgGen(1) ) u_win${i}_data_intg_gen ( .tl_i(tl_win_i[${i}]), .tl_o(tl_socket_d2h[${i}]) ); % else: assign tl_socket_d2h[${i}] = tl_win_i[${i}]; % endif % endfor // Create Socket_1n tlul_socket_1n #( .N (${num_dsp}), .HReqPass (1'b1), .HRspPass (1'b1), .DReqPass ({${num_dsp}{1'b1}}), .DRspPass ({${num_dsp}{1'b1}}), .HReqDepth (4'h0), .HRspDepth (4'h0), .DReqDepth ({${num_dsp}{4'h0}}), .DRspDepth ({${num_dsp}{4'h0}}) ) u_socket ( .clk_i, .rst_ni, .tl_h_i (tl_i), .tl_h_o (tl_o_pre), .tl_d_o (tl_socket_h2d), .tl_d_i (tl_socket_d2h), .dev_select_i (reg_steer) ); % endif // Create steering logic always_comb begin reg_steer = ${num_dsp-1}; // Default set to register // TODO: Can below codes be unique case () inside ? % for i,w in enumerate(rb.windows): <% base_addr = w.offset limit_addr = w.offset + w.size_in_bytes if use_reg_iface: hi_check = 'reg_req_i.addr[AW-1:0] < {}'.format(limit_addr) else: hi_check = 'tl_i.a_address[AW-1:0] < {}'.format(limit_addr) addr_checks = [] if base_addr > 0: if use_reg_iface: addr_checks.append('reg_req_i.addr[AW-1:0] >= {}'.format(base_addr)) else: addr_checks.append('tl_i.a_address[AW-1:0] >= {}'.format(base_addr)) if limit_addr < 2**addr_width: if use_reg_iface: addr_checks.append('reg_req_i.addr[AW-1:0] < {}'.format(limit_addr)) else: addr_checks.append('tl_i.a_address[AW-1:0] < {}'.format(limit_addr)) addr_test = ' && '.join(addr_checks) %>\ % if addr_test: if (${addr_test}) begin % endif reg_steer = ${i}; % if addr_test: end % endif % endfor % if not use_reg_iface: if (intg_err) begin reg_steer = ${num_dsp-1}; end % endif end % endif % if rb.all_regs: % if use_reg_iface: assign reg_we = reg_intf_req.valid & reg_intf_req.write; assign reg_re = reg_intf_req.valid & ~reg_intf_req.write; assign reg_addr = reg_intf_req.addr; assign reg_wdata = reg_intf_req.wdata; assign reg_be = reg_intf_req.wstrb; assign reg_intf_rsp.rdata = reg_rdata; assign reg_intf_rsp.error = reg_error; assign reg_intf_rsp.ready = 1'b1; % else: tlul_adapter_reg #( .RegAw(AW), .RegDw(DW), .EnableDataIntgGen(${adapt_data_intg_gen}) ) u_reg_if ( .clk_i, .rst_ni, .tl_i (tl_reg_h2d), .tl_o (tl_reg_d2h), .we_o (reg_we), .re_o (reg_re), .addr_o (reg_addr), .wdata_o (reg_wdata), .be_o (reg_be), .rdata_i (reg_rdata), .error_i (reg_error) ); % endif assign reg_rdata = reg_rdata_next ; % if use_reg_iface: assign reg_error = (devmode_i & addrmiss) | wr_err; % else: assign reg_error = (devmode_i & addrmiss) | wr_err | intg_err; % endif // Define SW related signals // Format: <reg>_<field>_{wd|we|qs} // or <reg>_{wd|we|qs} if field == 1 or 0 % for r in regs_flat: % if len(r.fields) == 1: ${sig_gen(r.fields[0], r.name.lower(), r.hwext, r.shadowed)}\ % else: % for f in r.fields: ${sig_gen(f, r.name.lower() + "_" + f.name.lower(), r.hwext, r.shadowed)}\ % endfor % endif % endfor // Register instances % for r in rb.all_regs: ######################## multiregister ########################### % if isinstance(r, MultiRegister): <% k = 0 %> % for sr in r.regs: // Subregister ${k} of Multireg ${r.reg.name.lower()} // R[${sr.name.lower()}]: V(${str(sr.hwext)}) % if len(sr.fields) == 1: <% f = sr.fields[0] finst_name = sr.name.lower() fsig_name = r.reg.name.lower() + "[%d]" % k k = k + 1 %> ${finst_gen(f, finst_name, fsig_name, sr.hwext, sr.regwen, sr.shadowed)} % else: % for f in sr.fields: <% finst_name = sr.name.lower() + "_" + f.name.lower() if r.is_homogeneous(): fsig_name = r.reg.name.lower() + "[%d]" % k k = k + 1 else: fsig_name = r.reg.name.lower() + "[%d]" % k + "." + get_basename(f.name.lower()) %> // F[${f.name.lower()}]: ${f.bits.msb}:${f.bits.lsb} ${finst_gen(f, finst_name, fsig_name, sr.hwext, sr.regwen, sr.shadowed)} % endfor <% if not r.is_homogeneous(): k += 1 %> % endif ## for: mreg_flat % endfor ######################## register with single field ########################### % elif len(r.fields) == 1: // R[${r.name.lower()}]: V(${str(r.hwext)}) <% f = r.fields[0] finst_name = r.name.lower() fsig_name = r.name.lower() %> ${finst_gen(f, finst_name, fsig_name, r.hwext, r.regwen, r.shadowed)} ######################## register with multiple fields ########################### % else: // R[${r.name.lower()}]: V(${str(r.hwext)}) % for f in r.fields: <% finst_name = r.name.lower() + "_" + f.name.lower() fsig_name = r.name.lower() + "." + f.name.lower() %> // F[${f.name.lower()}]: ${f.bits.msb}:${f.bits.lsb} ${finst_gen(f, finst_name, fsig_name, r.hwext, r.regwen, r.shadowed)} % endfor % endif ## for: rb.all_regs % endfor logic [${len(regs_flat)-1}:0] addr_hit; always_comb begin addr_hit = '0; % for i,r in enumerate(regs_flat): addr_hit[${"{}".format(i).rjust(max_regs_char)}] = (reg_addr == ${ublock}_${r.name.upper()}_OFFSET); % endfor end assign addrmiss = (reg_re || reg_we) ? ~|addr_hit : 1'b0 ; % if regs_flat: <% # We want to signal wr_err if reg_be (the byte enable signal) is true for # any bytes that aren't supported by a register. That's true if a # addr_hit[i] and a bit is set in reg_be but not in *_PERMIT[i]. wr_err_terms = ['(addr_hit[{idx}] & (|({mod}_PERMIT[{idx}] & ~reg_be)))' .format(idx=str(i).rjust(max_regs_char), mod=u_mod_base) for i in range(len(regs_flat))] wr_err_expr = (' |\n' + (' ' * 15)).join(wr_err_terms) %>\ // Check sub-word write is permitted always_comb begin wr_err = (reg_we & (${wr_err_expr})); end % else: assign wr_error = 1'b0; % endif\ % for i, r in enumerate(regs_flat): % if len(r.fields) == 1: ${we_gen(r.fields[0], r.name.lower(), r.hwext, r.shadowed, i)}\ % else: % for f in r.fields: ${we_gen(f, r.name.lower() + "_" + f.name.lower(), r.hwext, r.shadowed, i)}\ % endfor % endif % endfor // Read data return always_comb begin reg_rdata_next = '0; unique case (1'b1) % for i, r in enumerate(regs_flat): % if len(r.fields) == 1: addr_hit[${i}]: begin ${rdata_gen(r.fields[0], r.name.lower())}\ end % else: addr_hit[${i}]: begin % for f in r.fields: ${rdata_gen(f, r.name.lower() + "_" + f.name.lower())}\ % endfor end % endif % endfor default: begin reg_rdata_next = '1; end endcase end % endif // Unused signal tieoff % if rb.all_regs: // wdata / byte enable are not always fully used // add a blanket unused statement to handle lint waivers logic unused_wdata; logic unused_be; assign unused_wdata = ^reg_wdata; assign unused_be = ^reg_be; % else: // devmode_i is not used if there are no registers logic unused_devmode; assign unused_devmode = ^devmode_i; % endif % if rb.all_regs: // Assertions for Register Interface % if not use_reg_iface: `ASSERT_PULSE(wePulse, reg_we) `ASSERT_PULSE(rePulse, reg_re) `ASSERT(reAfterRv, $rose(reg_re || reg_we) |=> tl_o.d_valid) // this is formulated as an assumption such that the FPV testbenches do disprove this // property by mistake //`ASSUME(reqParity, tl_reg_h2d.a_valid |-> tl_reg_h2d.a_user.chk_en == tlul_pkg::CheckDis) % endif `ASSERT(en2addrHit, (reg_we || reg_re) |-> $onehot0(addr_hit)) % endif endmodule <%def name="str_bits_sv(bits)">\ % if bits.msb != bits.lsb: ${bits.msb}:${bits.lsb}\ % else: ${bits.msb}\ % endif </%def>\ <%def name="str_arr_sv(bits)">\ % if bits.msb != bits.lsb: [${bits.msb-bits.lsb}:0] \ % endif </%def>\ <%def name="sig_gen(field, sig_name, hwext, shadowed)">\ % if field.swaccess.allows_read(): logic ${str_arr_sv(field.bits)}${sig_name}_qs; % endif % if field.swaccess.allows_write(): logic ${str_arr_sv(field.bits)}${sig_name}_wd; logic ${sig_name}_we; % endif % if (field.swaccess.allows_read() and hwext) or shadowed: logic ${sig_name}_re; % endif </%def>\ <%def name="finst_gen(field, finst_name, fsig_name, hwext, regwen, shadowed)">\ % if hwext: ## if hwext, instantiate prim_subreg_ext prim_subreg_ext #( .DW (${field.bits.width()}) ) u_${finst_name} ( % if field.swaccess.allows_read(): .re (${finst_name}_re), % else: .re (1'b0), % endif % if field.swaccess.allows_write(): % if regwen: // qualified with register enable .we (${finst_name}_we & ${regwen.lower()}_qs), % else: .we (${finst_name}_we), % endif .wd (${finst_name}_wd), % else: .we (1'b0), .wd ('0), % endif % if field.hwaccess.allows_write(): .d (hw2reg.${fsig_name}.d), % else: .d ('0), % endif % if field.hwre or shadowed: .qre (reg2hw.${fsig_name}.re), % else: .qre (), % endif % if not field.hwaccess.allows_read(): .qe (), .q (), % else: % if field.hwqe: .qe (reg2hw.${fsig_name}.qe), % else: .qe (), % endif .q (reg2hw.${fsig_name}.q ), % endif % if field.swaccess.allows_read(): .qs (${finst_name}_qs) % else: .qs () % endif ); % else: ## if not hwext, instantiate prim_subreg, prim_subreg_shadow or constant assign % if ((not field.hwaccess.allows_read() and\ not field.hwaccess.allows_write() and\ field.swaccess.swrd() == SwRdAccess.RD and\ not field.swaccess.allows_write())): // constant-only read assign ${finst_name}_qs = ${field.bits.width()}'h${"%x" % (field.resval or 0)}; % else: ## not hwext not constant % if not shadowed: prim_subreg #( % else: prim_subreg_shadow #( % endif .DW (${field.bits.width()}), .SWACCESS("${field.swaccess.value[1].name.upper()}"), .RESVAL (${field.bits.width()}'h${"%x" % (field.resval or 0)}) ) u_${finst_name} ( .clk_i (clk_i ), .rst_ni (rst_ni ), % if shadowed: .re (${finst_name}_re), % endif % if field.swaccess.allows_write(): ## non-RO types % if regwen: // from register interface (qualified with register enable) .we (${finst_name}_we & ${regwen.lower()}_qs), % else: // from register interface .we (${finst_name}_we), % endif .wd (${finst_name}_wd), % else: ## RO types .we (1'b0), .wd ('0 ), % endif // from internal hardware % if field.hwaccess.allows_write(): .de (hw2reg.${fsig_name}.de), .d (hw2reg.${fsig_name}.d ), % else: .de (1'b0), .d ('0 ), % endif // to internal hardware % if not field.hwaccess.allows_read(): .qe (), .q (), % else: % if field.hwqe: .qe (reg2hw.${fsig_name}.qe), % else: .qe (), % endif .q (reg2hw.${fsig_name}.q ), % endif % if not shadowed: % if field.swaccess.allows_read(): // to register interface (read) .qs (${finst_name}_qs) % else: .qs () % endif % else: % if field.swaccess.allows_read(): // to register interface (read) .qs (${finst_name}_qs), % else: .qs (), % endif // Shadow register error conditions .err_update (reg2hw.${fsig_name}.err_update ), .err_storage (reg2hw.${fsig_name}.err_storage) % endif ); % endif ## end non-constant prim_subreg % endif </%def>\ <%def name="we_gen(field, sig_name, hwext, shadowed, idx)">\ <% needs_we = field.swaccess.allows_write() needs_re = (field.swaccess.allows_read() and hwext) or shadowed space = '\n' if needs_we or needs_re else '' %>\ ${space}\ % if needs_we: % if field.swaccess.swrd() != SwRdAccess.RC: assign ${sig_name}_we = addr_hit[${idx}] & reg_we & !reg_error; assign ${sig_name}_wd = reg_wdata[${str_bits_sv(field.bits)}]; % else: ## Generate WE based on read request, read should clear assign ${sig_name}_we = addr_hit[${idx}] & reg_re & !reg_error; assign ${sig_name}_wd = '1; % endif % endif % if needs_re: assign ${sig_name}_re = addr_hit[${idx}] & reg_re & !reg_error; % endif </%def>\ <%def name="rdata_gen(field, sig_name)">\ % if field.swaccess.allows_read(): reg_rdata_next[${str_bits_sv(field.bits)}] = ${sig_name}_qs; % else: reg_rdata_next[${str_bits_sv(field.bits)}] = '0; % endif </%def>\
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict, Sequence from .bits import Bits from .lib import check_keys, check_name, check_str, check_int, check_list class Signal: def __init__(self, name: str, desc: str, bits: Bits): self.name = name self.desc = desc self.bits = bits @staticmethod def from_raw(what: str, lsb: int, raw: object) -> 'Signal': rd = check_keys(raw, what, ['name', 'desc'], ['width']) name = check_name(rd['name'], 'name field of ' + what) desc = check_str(rd['desc'], 'desc field of ' + what) width = check_int(rd.get('width', 1), 'width field of ' + what) if width <= 0: raise ValueError('The width field of signal {} ({}) ' 'has value {}, but should be positive.' .format(name, what, width)) bits = Bits(lsb + width - 1, lsb) return Signal(name, desc, bits) @staticmethod def from_raw_list(what: str, raw: object) -> Sequence['Signal']: lsb = 0 ret = [] for idx, entry in enumerate(check_list(raw, what)): entry_what = 'entry {} of {}'.format(idx, what) interrupt = Signal.from_raw(entry_what, lsb, entry) ret.append(interrupt) lsb += interrupt.bits.width() return ret def _asdict(self) -> Dict[str, object]: return { 'name': self.name, 'desc': self.desc, 'width': str(self.bits.width()) } def as_nwt_dict(self, type_field: str) -> Dict[str, object]: '''Return a view of the signal as a dictionary The dictionary has fields "name", "width" and "type", the last of which comes from the type_field argument. Used for topgen integration. ''' return {'name': self.name, 'width': self.bits.width(), 'type': type_field}
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // UVM Registers auto-generated by `reggen` containing data structure ## ## ## We use functions from uvm_reg_base.sv.tpl to define ## per-device-interface code. ## <%namespace file="uvm_reg_base.sv.tpl" import="*"/>\ ## ## ${make_ral_pkg(dv_base_prefix, block.regwidth, reg_block_path, rb, esc_if_name)}
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 <%! from reggen import gen_dv from reggen.access import HwAccess, SwRdAccess, SwWrAccess %> ## ## ## make_ral_pkg ## ============ ## ## Generate the RAL package for a device interface. ## ## dv_base_prefix a string naming the base register type. If it is FOO, ## then we will inherit from FOO_reg (assumed to ## be a subclass of uvm_reg). ## ## reg_width an integer giving the width of registers in bits ## ## reg_block_path the hierarchical path to the relevant register block in the ## design ## ## rb a RegBlock object ## ## esc_if_name a string giving the full, escaped, interface name. For ## a device interface called FOO on block BAR, ## this will be bar__foo. For an unnamed interface ## on block BAR, this will be just bar. ## <%def name="make_ral_pkg(dv_base_prefix, reg_width, reg_block_path, rb, esc_if_name)">\ package ${esc_if_name}_ral_pkg; ${make_ral_pkg_hdr(dv_base_prefix, [])} ${make_ral_pkg_fwd_decls(esc_if_name, rb.flat_regs, rb.windows)} % for reg in rb.flat_regs: ${make_ral_pkg_reg_class(dv_base_prefix, reg_width, esc_if_name, reg_block_path, reg)} % endfor % for window in rb.windows: ${make_ral_pkg_window_class(dv_base_prefix, esc_if_name, window)} % endfor <% reg_block_name = gen_dv.bcname(esc_if_name) %>\ class ${reg_block_name} extends ${dv_base_prefix}_reg_block; % if rb.flat_regs: // registers % for r in rb.flat_regs: rand ${gen_dv.rcname(esc_if_name, r)} ${r.name.lower()}; % endfor % endif % if rb.windows: // memories % for window in rb.windows: rand ${gen_dv.mcname(esc_if_name, window)} ${gen_dv.miname(window)}; % endfor % endif `uvm_object_utils(${reg_block_name}) function new(string name = "${reg_block_name}", int has_coverage = UVM_NO_COVERAGE); super.new(name, has_coverage); endfunction : new virtual function void build(uvm_reg_addr_t base_addr, csr_excl_item csr_excl = null); // create default map this.default_map = create_map(.name("default_map"), .base_addr(base_addr), .n_bytes(${reg_width//8}), .endian(UVM_LITTLE_ENDIAN)); if (csr_excl == null) begin csr_excl = csr_excl_item::type_id::create("csr_excl"); this.csr_excl = csr_excl; end % if rb.flat_regs: set_hdl_path_root("tb.dut", "BkdrRegPathRtl"); set_hdl_path_root("tb.dut", "BkdrRegPathRtlCommitted"); set_hdl_path_root("tb.dut", "BkdrRegPathRtlShadow"); // create registers % for r in rb.flat_regs: <% reg_name = r.name.lower() reg_right = r.dv_rights() reg_offset = "{}'h{:x}".format(reg_width, r.offset) reg_tags = r.tags reg_shadowed = r.shadowed type_id_indent = ' ' * (len(reg_name) + 4) %>\ ${reg_name} = (${gen_dv.rcname(esc_if_name, r)}:: ${type_id_indent}type_id::create("${reg_name}")); ${reg_name}.configure(.blk_parent(this)); ${reg_name}.build(csr_excl); default_map.add_reg(.rg(${reg_name}), .offset(${reg_offset}), .rights("${reg_right}")); % if reg_shadowed: ${reg_name}.set_is_shadowed(); % endif % if reg_tags: // create register tags % for reg_tag in reg_tags: <% tag = reg_tag.split(":") %>\ % if tag[0] == "excl": csr_excl.add_excl(${reg_name}.get_full_name(), ${tag[2]}, ${tag[1]}); % endif % endfor % endif % endfor <% any_regwen = False for r in rb.flat_regs: if r.regwen: any_regwen = True break %>\ % if any_regwen: // assign locked reg to its regwen reg % for r in rb.flat_regs: % if r.regwen: % for reg in rb.flat_regs: % if r.regwen.lower() == reg.name.lower(): ${r.regwen.lower()}.add_lockable_reg_or_fld(${r.name.lower()}); <% break %>\ % elif reg.name.lower() in r.regwen.lower(): % for field in reg.get_field_list(): % if r.regwen.lower() == (reg.name.lower() + "_" + field.name.lower()): ${r.regwen.lower()}.${field.name.lower()}.add_lockable_reg_or_fld(${r.name.lower()}); <% break %>\ % endif % endfor % endif % endfor % endif % endfor % endif % endif ${make_ral_pkg_window_instances(reg_width, esc_if_name, rb)} endfunction : build endclass : ${reg_block_name} endpackage </%def>\ ## ## ## make_ral_pkg_hdr ## ================ ## ## Generate the header for a RAL package ## ## dv_base_prefix as for make_ral_pkg ## ## deps a list of names for packages that should be explicitly ## imported ## <%def name="make_ral_pkg_hdr(dv_base_prefix, deps)">\ // dep packages import uvm_pkg::*; import dv_base_reg_pkg::*; % if dv_base_prefix != "dv_base": import ${dv_base_prefix}_reg_pkg::*; % endif % for dep in deps: import ${dep}::*; % endfor // macro includes `include "uvm_macros.svh"\ </%def>\ ## ## ## make_ral_pkg_fwd_decls ## ====================== ## ## Generate the forward declarations for a RAL package ## ## esc_if_name as for make_ral_pkg ## ## flat_regs a list of Register objects (expanding multiregs) ## ## windows a list of Window objects ## <%def name="make_ral_pkg_fwd_decls(esc_if_name, flat_regs, windows)">\ // Forward declare all register/memory/block classes % for r in flat_regs: typedef class ${gen_dv.rcname(esc_if_name, r)}; % endfor % for w in windows: typedef class ${gen_dv.mcname(esc_if_name, w)}; % endfor typedef class ${gen_dv.bcname(esc_if_name)};\ </%def>\ ## ## ## make_ral_pkg_reg_class ## ====================== ## ## Generate the classes for a register inside a RAL package ## ## dv_base_prefix as for make_ral_pkg ## ## reg_width as for make_ral_pkg ## ## esc_if_name as for make_ral_pkg ## ## reg_block_path as for make_ral_pkg ## ## reg a Register object <%def name="make_ral_pkg_reg_class(dv_base_prefix, reg_width, esc_if_name, reg_block_path, reg)">\ <% reg_name = reg.name.lower() is_ext = reg.hwext for field in reg.fields: if (field.hwaccess.value[1] == HwAccess.NONE and field.swaccess.swrd() == SwRdAccess.RD and not field.swaccess.allows_write()): is_ext = 1 class_name = gen_dv.rcname(esc_if_name, reg) %>\ class ${class_name} extends ${dv_base_prefix}_reg; // fields % for f in reg.fields: rand ${dv_base_prefix}_reg_field ${f.name.lower()}; % endfor `uvm_object_utils(${class_name}) function new(string name = "${class_name}", int unsigned n_bits = ${reg_width}, int has_coverage = UVM_NO_COVERAGE); super.new(name, n_bits, has_coverage); endfunction : new virtual function void build(csr_excl_item csr_excl = null); // create fields % for field in reg.fields: <% if len(reg.fields) == 1: reg_field_name = reg_name else: reg_field_name = reg_name + "_" + field.name.lower() %>\ ${_create_reg_field(dv_base_prefix, reg_width, reg_block_path, reg.shadowed, reg.hwext, reg_field_name, field)} % endfor % if reg.shadowed and reg.hwext: <% shadowed_reg_path = '' for tag in reg.tags: parts = tag.split(':') if parts[0] == 'shadowed_reg_path': shadowed_reg_path = parts[1] if not shadowed_reg_path: print("ERROR: ext shadow_reg does not have tags for shadowed_reg_path!") assert 0 bit_idx = reg.fields[-1].bits.msb + 1 %>\ add_update_err_alert("${reg.update_err_alert}"); add_storage_err_alert("${reg.storage_err_alert}"); add_hdl_path_slice("${shadowed_reg_path}.committed_reg.q", 0, ${bit_idx}, 0, "BkdrRegPathRtlCommitted"); add_hdl_path_slice("${shadowed_reg_path}.shadow_reg.q", 0, ${bit_idx}, 0, "BkdrRegPathRtlShadow"); % endif % if is_ext: set_is_ext_reg(1); % endif endfunction : build endclass : ${class_name}\ </%def>\ ## ## ## _create_reg_field ## ================= ## ## Generate the code that creates a uvm_reg_field object for a field ## in a register. ## ## dv_base_prefix as for make_ral_pkg ## ## reg_width as for make_ral_pkg ## ## reg_block_path as for make_ral_pkg ## ## shadowed true if the field's register is shadowed ## ## hwext true if the field's register is hwext ## ## reg_field_name a string with the name to give the field in the HDL ## ## field a Field object <%def name="_create_reg_field(dv_base_prefix, reg_width, reg_block_path, shadowed, hwext, reg_field_name, field)">\ <% field_size = field.bits.width() if field.swaccess.key == "r0w1c": field_access = "W1C" else: field_access = field.swaccess.value[1].name if not field.hwaccess.allows_write(): field_volatile = 0 else: field_volatile = 1 field_tags = field.tags fname = field.name.lower() type_id_indent = ' ' * (len(fname) + 4) %>\ ${fname} = (${dv_base_prefix}_reg_field:: ${type_id_indent}type_id::create("${fname}")); ${fname}.configure( .parent(this), .size(${field_size}), .lsb_pos(${field.bits.lsb}), .access("${field_access}"), .volatile(${field_volatile}), .reset(${reg_width}'h${format(field.resval or 0, 'x')}), .has_reset(1), .is_rand(1), .individually_accessible(1)); ${fname}.set_original_access("${field_access}"); % if ((field.hwaccess.value[1] == HwAccess.NONE and\ field.swaccess.swrd() == SwRdAccess.RD and\ not field.swaccess.allows_write())): // constant reg add_hdl_path_slice("${reg_block_path}.${reg_field_name}_qs", ${field.bits.lsb}, ${field_size}, 0, "BkdrRegPathRtl"); % else: add_hdl_path_slice("${reg_block_path}.u_${reg_field_name}.q${"s" if hwext else ""}", ${field.bits.lsb}, ${field_size}, 0, "BkdrRegPathRtl"); % endif % if shadowed and not hwext: add_hdl_path_slice("${reg_block_path}.u_${reg_field_name}.committed_reg.q", ${field.bits.lsb}, ${field_size}, 0, "BkdrRegPathRtlCommitted"); add_hdl_path_slice("${reg_block_path}.u_${reg_field_name}.shadow_reg.q", ${field.bits.lsb}, ${field_size}, 0, "BkdrRegPathRtlShadow"); % endif % if field_tags: // create field tags % for field_tag in field_tags: <% tag = field_tag.split(":") %>\ % if tag[0] == "excl": csr_excl.add_excl(${field.name.lower()}.get_full_name(), ${tag[2]}, ${tag[1]}); % endif % endfor % endif </%def>\ ## ## ## make_ral_pkg_window_class ## ========================= ## ## Generate the classes for a window inside a RAL package ## ## dv_base_prefix as for make_ral_pkg ## ## esc_if_name as for make_ral_pkg ## ## window a Window object <%def name="make_ral_pkg_window_class(dv_base_prefix, esc_if_name, window)">\ <% mem_name = window.name.lower() mem_right = window.swaccess.dv_rights() mem_n_bits = window.validbits mem_size = window.items class_name = gen_dv.mcname(esc_if_name, window) %>\ class ${class_name} extends ${dv_base_prefix}_mem; `uvm_object_utils(${class_name}) function new(string name = "${class_name}", longint unsigned size = ${mem_size}, int unsigned n_bits = ${mem_n_bits}, string access = "${mem_right}", int has_coverage = UVM_NO_COVERAGE); super.new(name, size, n_bits, access, has_coverage); % if window.byte_write: set_mem_partial_write_support(1); % endif endfunction : new endclass : ${class_name} </%def>\ ## ## ## make_ral_pkg_window_instances ## ============================= ## ## Generate the classes for a window inside a RAL package ## ## reg_width as for make_ral_pkg ## ## esc_if_name as for make_ral_pkg ## ## rb a RegBlock object ## <%def name="make_ral_pkg_window_instances(reg_width, esc_if_name, rb)">\ % if rb.windows: // create memories % for w in rb.windows: <% mem_name = w.name.lower() mem_right = w.swaccess.dv_rights() mem_offset = "{}'h{:x}".format(reg_width, w.offset) mem_n_bits = w.validbits mem_size = w.items %>\ ${mem_name} = ${gen_dv.mcname(esc_if_name, w)}::type_id::create("${mem_name}"); ${mem_name}.configure(.parent(this)); default_map.add_mem(.mem(${mem_name}), .offset(${mem_offset}), .rights("${mem_right}")); % endfor % endif </%def>\
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """ Register JSON validation """ import logging as log # validating version of int(x, 0) # returns int value, error flag # if error flag is True value will be zero def check_int(x, err_prefix, suppress_err_msg=False): if isinstance(x, int): return x, False if x[0] == '0' and len(x) > 2: if x[1] in 'bB': validch = '01' elif x[1] in 'oO': validch = '01234567' elif x[1] in 'xX': validch = '0123456789abcdefABCDEF' else: if not suppress_err_msg: log.error(err_prefix + ": int must start digit, 0b, 0B, 0o, 0O, 0x or 0X") return 0, True for c in x[2:]: if c not in validch: if not suppress_err_msg: log.error(err_prefix + ": Bad character " + c + " in " + x) return 0, True else: if not x.isdecimal(): if not suppress_err_msg: log.error(err_prefix + ": Number not valid int " + x) return 0, True return int(x, 0), False def check_bool(x, err_prefix): """check_bool checks if input 'x' is one of the list: "true", "false" It returns value as Bool type and Error condition. """ if isinstance(x, bool): # if Bool returns as it is return x, False if not x.lower() in ["true", "false"]: log.error(err_prefix + ": Bad field value " + x) return False, True else: return (x.lower() == "true"), False def check_ln(obj, x, withwidth, err_prefix): error = 0 if not isinstance(obj[x], list): log.error(err_prefix + ' element ' + x + ' not a list') return 1 for y in obj[x]: error += check_keys(y, ln_required, ln_optional if withwidth else {}, {}, err_prefix + ' element ' + x) if withwidth: if 'width' in y: w, err = check_int(y['width'], err_prefix + ' width in ' + x) if err: error += 1 w = 1 else: w = 1 y['width'] = str(w) return error def check_keys(obj, required_keys, optional_keys, added_keys, err_prefix): error = 0 for x in required_keys: if x not in obj: error += 1 log.error(err_prefix + " missing required key " + x) for x in obj: type = None if x in required_keys: type = required_keys[x][0] elif x in optional_keys: type = optional_keys[x][0] elif x not in added_keys: log.warning(err_prefix + " contains extra key " + x) if type is not None: if type[:2] == 'ln': error += check_ln(obj, x, type == 'lnw', err_prefix) return error val_types = { 'd': ["int", "integer (binary 0b, octal 0o, decimal, hex 0x)"], 'x': ["xint", "x for undefined otherwise int"], 'b': [ "bitrange", "bit number as decimal integer, " "or bit-range as decimal integers msb:lsb" ], 'l': ["list", "comma separated list enclosed in `[]`"], 'ln': [ "name list", 'comma separated list enclosed in `[]` of ' 'one or more groups that have just name and dscr keys.' ' e.g. `{ name: "name", desc: "description"}`' ], 'lnw': ["name list+", 'name list that optionally contains a width'], 'lp': ["parameter list", 'parameter list having default value optionally'], 'g': ["group", "comma separated group of key:value enclosed in `{}`"], 'lg': [ "list of group", "comma separated group of key:value enclosed in `{}`" " the second entry of the list is the sub group format" ], 's': ["string", "string, typically short"], 't': [ "text", "string, may be multi-line enclosed in `'''` " "may use `**bold**`, `*italic*` or `!!Reg` markup" ], 'T': ["tuple", "tuple enclosed in ()"], 'pi': ["python int", "Native Python type int (generated)"], 'pb': ["python Bool", "Native Python type Bool (generated)"], 'pl': ["python list", "Native Python type list (generated)"], 'pe': ["python enum", "Native Python type enum (generated)"] } # ln type has list of groups with only name and description # (was called "subunit" in cfg_validate) ln_required = { 'name': ['s', "name of the item"], 'desc': ['s', "description of the item"], } ln_optional = { 'width': ['d', "bit width of the item (if not 1)"], } # Registers list may have embedded keys list_optone = { 'reserved': ['d', "number of registers to reserve space for"], 'skipto': ['d', "set next register offset to value"], 'window': [ 'g', "group defining an address range " "for something other than standard registers" ], 'multireg': ['g', "group defining registers generated " "from a base instance."] } key_use = {'r': "required", 'o': "optional", 'a': "added by tool"}
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r"""Standard version printing """ import os import subprocess import sys import pkg_resources # part of setuptools def show_and_exit(clitool, packages): util_path = os.path.dirname(os.path.realpath(clitool)) os.chdir(util_path) ver = subprocess.run( ["git", "describe", "--always", "--dirty", "--broken"], stdout=subprocess.PIPE).stdout.strip().decode('ascii') if (ver == ''): ver = 'not found (not in Git repository?)' sys.stderr.write(clitool + " Git version " + ver + '\n') for p in packages: sys.stderr.write(p + ' ' + pkg_resources.require(p)[0].version + '\n') exit(0)
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from typing import Dict from .access import SWAccess from .lib import check_keys, check_str, check_bool, check_int from .params import ReggenParams REQUIRED_FIELDS = { 'name': ['s', "name of the window"], 'desc': ['t', "description of the window"], 'items': ['d', "size in fieldaccess width words of the window"], 'swaccess': ['s', "software access permitted"], } # TODO potential for additional optional to give more type info? # eg sram-hw-port: "none", "sync", "async" OPTIONAL_FIELDS = { 'data-intg-passthru': [ 's', "True if the window has data integrity pass through. " "Defaults to false if not present." ], 'byte-write': [ 's', "True if byte writes are supported. " "Defaults to false if not present." ], 'validbits': [ 'd', "Number of valid data bits within " "regwidth sized word. " "Defaults to regwidth. If " "smaller than the regwidth then in each " "word of the window bits " "[regwidth-1:validbits] are unused and " "bits [validbits-1:0] are valid." ], 'unusual': [ 's', "True if window has unusual parameters " "(set to prevent Unusual: errors)." "Defaults to false if not present." ] } class Window: '''A class representing a memory window''' def __init__(self, name: str, desc: str, unusual: bool, byte_write: bool, data_intg_passthru: bool, validbits: int, items: int, size_in_bytes: int, offset: int, swaccess: SWAccess): assert 0 < validbits assert 0 < items <= size_in_bytes self.name = name self.desc = desc self.unusual = unusual self.byte_write = byte_write self.data_intg_passthru = data_intg_passthru self.validbits = validbits self.items = items self.size_in_bytes = size_in_bytes self.offset = offset self.swaccess = swaccess # Check that offset has been adjusted so that the first item in the # window has all zeros in the low bits. po2_size = 1 << (self.size_in_bytes - 1).bit_length() assert not (offset & (po2_size - 1)) @staticmethod def from_raw(offset: int, reg_width: int, params: ReggenParams, raw: object) -> 'Window': rd = check_keys(raw, 'window', list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) wind_desc = 'window at offset {:#x}'.format(offset) name = check_str(rd['name'], wind_desc) wind_desc = '{!r} {}'.format(name, wind_desc) desc = check_str(rd['desc'], 'desc field for ' + wind_desc) unusual = check_bool(rd.get('unusual', False), 'unusual field for ' + wind_desc) byte_write = check_bool(rd.get('byte-write', False), 'byte-write field for ' + wind_desc) data_intg_passthru = check_bool(rd.get('data-intg-passthru', False), 'data-intg-passthru field for ' + wind_desc) validbits = check_int(rd.get('validbits', reg_width), 'validbits field for ' + wind_desc) if validbits <= 0: raise ValueError('validbits field for {} is not positive.' .format(wind_desc)) if validbits > reg_width: raise ValueError('validbits field for {} is {}, ' 'which is greater than {}, the register width.' .format(wind_desc, validbits, reg_width)) r_items = check_str(rd['items'], 'items field for ' + wind_desc) items = params.expand(r_items, 'items field for ' + wind_desc) if items <= 0: raise ValueError("Items field for {} is {}, " "which isn't positive." .format(wind_desc, items)) assert reg_width % 8 == 0 size_in_bytes = items * (reg_width // 8) # Round size_in_bytes up to the next power of 2. The calculation is # like clog2 calculations in SystemVerilog, where we start with the # last index, rather than the number of elements. assert size_in_bytes > 0 po2_size = 1 << (size_in_bytes - 1).bit_length() # A size that isn't a power of 2 is not allowed unless the unusual flag # is set. if po2_size != size_in_bytes and not unusual: raise ValueError('Items field for {} is {}, which gives a size of ' '{} bytes. This is not a power of 2 (next power ' 'of 2 is {}). If you want to do this even so, ' 'set the "unusual" flag.' .format(wind_desc, items, size_in_bytes, po2_size)) # Adjust offset if necessary to make sure the base address of the first # item in the window has all zeros in the low bits. addr_mask = po2_size - 1 if offset & addr_mask: offset = (offset | addr_mask) + 1 offset = offset swaccess = SWAccess(wind_desc, rd['swaccess']) if not (swaccess.value[4] or unusual): raise ValueError('swaccess field for {} is {}, which is an ' 'unusual access type for a window. If you want ' 'to do this, set the "unusual" flag.' .format(wind_desc, swaccess.key)) return Window(name, desc, unusual, byte_write, data_intg_passthru, validbits, items, size_in_bytes, offset, swaccess) def next_offset(self, addrsep: int) -> int: return self.offset + self.size_in_bytes def _asdict(self) -> Dict[str, object]: rd = { 'desc': self.desc, 'items': self.items, 'swaccess': self.swaccess.key, 'byte-write': self.byte_write, 'validbits': self.validbits, 'unusual': self.unusual } if self.name is not None: rd['name'] = self.name return {'window': rd}
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """This contains a class which is used to help generate `top_{name}.h` and `top_{name}.h`. """ from collections import OrderedDict from typing import Dict, List, Optional, Tuple from mako.template import Template from .lib import get_base_and_size, Name from reggen.ip_block import IpBlock class MemoryRegion(object): def __init__(self, name: Name, base_addr: int, size_bytes: int): assert isinstance(base_addr, int) self.name = name self.base_addr = base_addr self.size_bytes = size_bytes self.size_words = (size_bytes + 3) // 4 def base_addr_name(self): return self.name + Name(["base", "addr"]) def offset_name(self): return self.name + Name(["offset"]) def size_bytes_name(self): return self.name + Name(["size", "bytes"]) def size_words_name(self): return self.name + Name(["size", "words"]) class CEnum(object): def __init__(self, name): self.name = name self.enum_counter = 0 self.finalized = False self.constants = [] def add_constant(self, constant_name, docstring=""): assert not self.finalized full_name = self.name + constant_name value = self.enum_counter self.enum_counter += 1 self.constants.append((full_name, value, docstring)) return full_name def add_last_constant(self, docstring=""): assert not self.finalized full_name = self.name + Name(["last"]) _, last_val, _ = self.constants[-1] self.constants.append((full_name, last_val, r"\internal " + docstring)) self.finalized = True def render(self): template = ("typedef enum ${enum.name.as_snake_case()} {\n" "% for name, value, docstring in enum.constants:\n" " ${name.as_c_enum()} = ${value}, /**< ${docstring} */\n" "% endfor\n" "} ${enum.name.as_c_type()};") return Template(template).render(enum=self) class CArrayMapping(object): def __init__(self, name, output_type_name): self.name = name self.output_type_name = output_type_name self.mapping = OrderedDict() def add_entry(self, in_name, out_name): self.mapping[in_name] = out_name def render_declaration(self): template = ( "extern const ${mapping.output_type_name.as_c_type()}\n" " ${mapping.name.as_snake_case()}[${len(mapping.mapping)}];") return Template(template).render(mapping=self) def render_definition(self): template = ( "const ${mapping.output_type_name.as_c_type()}\n" " ${mapping.name.as_snake_case()}[${len(mapping.mapping)}] = {\n" "% for in_name, out_name in mapping.mapping.items():\n" " [${in_name.as_c_enum()}] = ${out_name.as_c_enum()},\n" "% endfor\n" "};\n") return Template(template).render(mapping=self) class TopGenC: def __init__(self, top_info, name_to_block: Dict[str, IpBlock]): self.top = top_info self._top_name = Name(["top"]) + Name.from_snake_case(top_info["name"]) self._name_to_block = name_to_block # The .c file needs the .h file's relative path, store it here self.header_path = None self._init_plic_targets() self._init_plic_mapping() self._init_alert_mapping() self._init_pinmux_mapping() self._init_pwrmgr_wakeups() self._init_rstmgr_sw_rsts() self._init_pwrmgr_reset_requests() self._init_clkmgr_clocks() def devices(self) -> List[Tuple[Tuple[str, Optional[str]], MemoryRegion]]: '''Return a list of MemoryRegion objects for devices on the bus The list returned is pairs (full_if, region) where full_if is itself a pair (inst_name, if_name). inst_name is the name of some IP block instantiation. if_name is the name of the interface (may be None). region is a MemoryRegion object representing the device. ''' ret = [] # type: List[Tuple[Tuple[str, Optional[str]], MemoryRegion]] for inst in self.top['module']: block = self._name_to_block[inst['type']] for if_name, rb in block.reg_blocks.items(): full_if = (inst['name'], if_name) full_if_name = Name.from_snake_case(full_if[0]) if if_name is not None: full_if_name += Name.from_snake_case(if_name) name = self._top_name + full_if_name base, size = get_base_and_size(self._name_to_block, inst, if_name) region = MemoryRegion(name, base, size) ret.append((full_if, region)) return ret def memories(self): return [(m["name"], MemoryRegion(self._top_name + Name.from_snake_case(m["name"]), int(m["base_addr"], 0), int(m["size"], 0))) for m in self.top["memory"]] def _init_plic_targets(self): enum = CEnum(self._top_name + Name(["plic", "target"])) for core_id in range(int(self.top["num_cores"])): enum.add_constant(Name(["ibex", str(core_id)]), docstring="Ibex Core {}".format(core_id)) enum.add_last_constant("Final PLIC target") self.plic_targets = enum def _init_plic_mapping(self): """We eventually want to generate a mapping from interrupt id to the source peripheral. In order to do so, we generate two enums (one for interrupts, one for sources), and store the generated names in a dictionary that represents the mapping. PLIC Interrupt ID 0 corresponds to no interrupt, and so no peripheral, so we encode that in the enum as "unknown". The interrupts have to be added in order, with "none" first, to ensure that they get the correct mapping to their PLIC id, which is used for addressing the right registers and bits. """ sources = CEnum(self._top_name + Name(["plic", "peripheral"])) interrupts = CEnum(self._top_name + Name(["plic", "irq", "id"])) plic_mapping = CArrayMapping( self._top_name + Name(["plic", "interrupt", "for", "peripheral"]), sources.name) unknown_source = sources.add_constant(Name(["unknown"]), docstring="Unknown Peripheral") none_irq_id = interrupts.add_constant(Name(["none"]), docstring="No Interrupt") plic_mapping.add_entry(none_irq_id, unknown_source) # When we generate the `interrupts` enum, the only info we have about # the source is the module name. We'll use `source_name_map` to map a # short module name to the full name object used for the enum constant. source_name_map = {} for name in self.top["interrupt_module"]: source_name = sources.add_constant(Name.from_snake_case(name), docstring=name) source_name_map[name] = source_name sources.add_last_constant("Final PLIC peripheral") for intr in self.top["interrupt"]: # Some interrupts are multiple bits wide. Here we deal with that by # adding a bit-index suffix if "width" in intr and int(intr["width"]) != 1: for i in range(int(intr["width"])): name = Name.from_snake_case(intr["name"]) + Name([str(i)]) irq_id = interrupts.add_constant(name, docstring="{} {}".format( intr["name"], i)) source_name = source_name_map[intr["module_name"]] plic_mapping.add_entry(irq_id, source_name) else: name = Name.from_snake_case(intr["name"]) irq_id = interrupts.add_constant(name, docstring=intr["name"]) source_name = source_name_map[intr["module_name"]] plic_mapping.add_entry(irq_id, source_name) interrupts.add_last_constant("The Last Valid Interrupt ID.") self.plic_sources = sources self.plic_interrupts = interrupts self.plic_mapping = plic_mapping def _init_alert_mapping(self): """We eventually want to generate a mapping from alert id to the source peripheral. In order to do so, we generate two enums (one for alerts, one for sources), and store the generated names in a dictionary that represents the mapping. Alert Handler has no concept of "no alert", unlike the PLIC. The alerts have to be added in order, to ensure that they get the correct mapping to their alert id, which is used for addressing the right registers and bits. """ sources = CEnum(self._top_name + Name(["alert", "peripheral"])) alerts = CEnum(self._top_name + Name(["alert", "id"])) alert_mapping = CArrayMapping( self._top_name + Name(["alert", "for", "peripheral"]), sources.name) # When we generate the `alerts` enum, the only info we have about the # source is the module name. We'll use `source_name_map` to map a short # module name to the full name object used for the enum constant. source_name_map = {} for name in self.top["alert_module"]: source_name = sources.add_constant(Name.from_snake_case(name), docstring=name) source_name_map[name] = source_name sources.add_last_constant("Final Alert peripheral") for alert in self.top["alert"]: if "width" in alert and int(alert["width"]) != 1: for i in range(int(alert["width"])): name = Name.from_snake_case(alert["name"]) + Name([str(i)]) irq_id = alerts.add_constant(name, docstring="{} {}".format( alert["name"], i)) source_name = source_name_map[alert["module_name"]] alert_mapping.add_entry(irq_id, source_name) else: name = Name.from_snake_case(alert["name"]) alert_id = alerts.add_constant(name, docstring=alert["name"]) source_name = source_name_map[alert["module_name"]] alert_mapping.add_entry(alert_id, source_name) alerts.add_last_constant("The Last Valid Alert ID.") self.alert_sources = sources self.alert_alerts = alerts self.alert_mapping = alert_mapping def _init_pinmux_mapping(self): """Generate C enums for addressing pinmux registers and in/out selects. Inputs/outputs are connected in the order the modules are listed in the hjson under the "mio_modules" key. For each module, the corresponding inouts are connected first, followed by either the inputs or the outputs. Inputs: - Peripheral chooses register field (pinmux_peripheral_in) - Insel chooses MIO input (pinmux_insel) Outputs: - MIO chooses register field (pinmux_mio_out) - Outsel chooses peripheral output (pinmux_outsel) Insel and outsel have some special values which are captured here too. """ pinmux_info = self.top['pinmux'] pinout_info = self.top['pinout'] # Peripheral Inputs peripheral_in = CEnum(self._top_name + Name(['pinmux', 'peripheral', 'in'])) i = 0 for sig in pinmux_info['ios']: if sig['connection'] == 'muxed' and sig['type'] in ['inout', 'input']: index = Name([str(sig['idx'])]) if sig['idx'] != -1 else Name([]) name = Name.from_snake_case(sig['name']) + index peripheral_in.add_constant(name, docstring='Peripheral Input {}'.format(i)) i += 1 peripheral_in.add_last_constant('Last valid peripheral input') # Pinmux Input Selects insel = CEnum(self._top_name + Name(['pinmux', 'insel'])) insel.add_constant(Name(['constant', 'zero']), docstring='Tie constantly to zero') insel.add_constant(Name(['constant', 'one']), docstring='Tie constantly to one') i = 0 for pad in pinout_info['pads']: if pad['connection'] == 'muxed': insel.add_constant(Name([pad['name']]), docstring='MIO Pad {}'.format(i)) i += 1 insel.add_last_constant('Last valid insel value') # MIO Outputs mio_out = CEnum(self._top_name + Name(['pinmux', 'mio', 'out'])) i = 0 for pad in pinout_info['pads']: if pad['connection'] == 'muxed': mio_out.add_constant(Name.from_snake_case(pad['name']), docstring='MIO Pad {}'.format(i)) i += 1 mio_out.add_last_constant('Last valid mio output') # Pinmux Output Selects outsel = CEnum(self._top_name + Name(['pinmux', 'outsel'])) outsel.add_constant(Name(['constant', 'zero']), docstring='Tie constantly to zero') outsel.add_constant(Name(['constant', 'one']), docstring='Tie constantly to one') outsel.add_constant(Name(['constant', 'high', 'z']), docstring='Tie constantly to high-Z') i = 0 for sig in pinmux_info['ios']: if sig['connection'] == 'muxed' and sig['type'] in ['inout', 'output']: index = Name([str(sig['idx'])]) if sig['idx'] != -1 else Name([]) name = Name.from_snake_case(sig['name']) + index outsel.add_constant(name, docstring='Peripheral Output {}'.format(i)) i += 1 outsel.add_last_constant('Last valid outsel value') self.pinmux_peripheral_in = peripheral_in self.pinmux_insel = insel self.pinmux_mio_out = mio_out self.pinmux_outsel = outsel def _init_pwrmgr_wakeups(self): enum = CEnum(self._top_name + Name(["power", "manager", "wake", "ups"])) for signal in self.top["wakeups"]: enum.add_constant( Name.from_snake_case(signal["module"]) + Name.from_snake_case(signal["name"])) enum.add_last_constant("Last valid pwrmgr wakeup signal") self.pwrmgr_wakeups = enum # Enumerates the positions of all software controllable resets def _init_rstmgr_sw_rsts(self): sw_rsts = [ rst for rst in self.top["resets"]["nodes"] if 'sw' in rst and rst['sw'] == 1 ] enum = CEnum(self._top_name + Name(["reset", "manager", "sw", "resets"])) for rst in sw_rsts: enum.add_constant(Name.from_snake_case(rst["name"])) enum.add_last_constant("Last valid rstmgr software reset request") self.rstmgr_sw_rsts = enum def _init_pwrmgr_reset_requests(self): enum = CEnum(self._top_name + Name(["power", "manager", "reset", "requests"])) for signal in self.top["reset_requests"]: enum.add_constant( Name.from_snake_case(signal["module"]) + Name.from_snake_case(signal["name"])) enum.add_last_constant("Last valid pwrmgr reset_request signal") self.pwrmgr_reset_requests = enum def _init_clkmgr_clocks(self): """ Creates CEnums for accessing the software-controlled clocks in the design. The logic here matches the logic in topgen.py in how it instantiates the clock manager with the described clocks. We differentiate "gateable" clocks and "hintable" clocks because the clock manager has separate register interfaces for each group. """ aon_clocks = set() for src in self.top['clocks']['srcs'] + self.top['clocks'][ 'derived_srcs']: if src['aon'] == 'yes': aon_clocks.add(src['name']) gateable_clocks = CEnum(self._top_name + Name(["gateable", "clocks"])) hintable_clocks = CEnum(self._top_name + Name(["hintable", "clocks"])) # This replicates the behaviour in `topgen.py` in deriving `hints` and # `sw_clocks`. for group in self.top['clocks']['groups']: for (name, source) in group['clocks'].items(): if source not in aon_clocks: # All these clocks start with `clk_` which is redundant. clock_name = Name.from_snake_case(name).remove_part("clk") docstring = "Clock {} in group {}".format( name, group['name']) if group["sw_cg"] == "yes": gateable_clocks.add_constant(clock_name, docstring) elif group["sw_cg"] == "hint": hintable_clocks.add_constant(clock_name, docstring) gateable_clocks.add_last_constant("Last Valid Gateable Clock") hintable_clocks.add_last_constant("Last Valid Hintable Clock") self.clkmgr_gateable_clocks = gateable_clocks self.clkmgr_hintable_clocks = hintable_clocks
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import logging as log from typing import Optional, Tuple from mako import exceptions # type: ignore from mako.lookup import TemplateLookup # type: ignore from pkg_resources import resource_filename from reggen.gen_dv import gen_core_file from .top import Top def sv_base_addr(top: Top, if_name: Tuple[str, Optional[str]]) -> str: '''Get the base address of a device interface in SV syntax''' return "{}'h{:x}".format(top.regwidth, top.if_addrs[if_name]) def gen_dv(top: Top, dv_base_prefix: str, outdir: str) -> int: '''Generate DV RAL model for a Top''' # Read template lookup = TemplateLookup(directories=[resource_filename('topgen', '.'), resource_filename('reggen', '.')]) uvm_reg_tpl = lookup.get_template('top_uvm_reg.sv.tpl') # Expand template try: to_write = uvm_reg_tpl.render(top=top, dv_base_prefix=dv_base_prefix) except: # noqa: E722 log.error(exceptions.text_error_template().render()) return 1 # Dump to output file dest_path = '{}/chip_ral_pkg.sv'.format(outdir) with open(dest_path, 'w') as fout: fout.write(to_write) gen_core_file(outdir, 'chip', dv_base_prefix, ['chip_ral_pkg.sv']) return 0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import logging as log import re from collections import OrderedDict from enum import Enum from typing import Dict, List, Tuple from reggen.ip_block import IpBlock from reggen.inter_signal import InterSignal from reggen.validate import check_int from topgen import lib IM_TYPES = ['uni', 'req_rsp'] IM_ACTS = ['req', 'rsp', 'rcv'] IM_VALID_TYPEACT = {'uni': ['req', 'rcv'], 'req_rsp': ['req', 'rsp']} IM_CONN_TYPE = ['1-to-1', '1-to-N', 'broadcast'] class ImType(Enum): Uni = 1 ReqRsp = 2 class ImAct(Enum): Req = 1 Rsp = 2 Rcv = 3 class ImConn(Enum): OneToOne = 1 # req <-> {rsp,rcv} with same width OneToN = 2 # req width N <-> N x {rsp,rcv}s width 1 Broadcast = 3 # req width 1 <-> N x rcvs width 1 def intersignal_format(req: Dict) -> str: """Determine the signal format of the inter-module connections @param[req] Request struct. It has instance name, package format and etc. """ # TODO: Handle array signal result = "{req}_{struct}".format(req=req["inst_name"], struct=req["name"]) # check signal length if exceeds 100 # 7 : space + . # 3 : _{i|o}( # 6 : _{req|rsp}), req_length = 7 + len(req["name"]) + 3 + len(result) + 6 if req_length > 100: logmsg = "signal {0} length cannot be greater than 100" log.warning(logmsg.format(result)) log.warning("Please consider shorten the instance name") return result def get_suffixes(ims: OrderedDict) -> Tuple[str, str]: """Get suffixes of the struct. TL-UL struct uses `h2d`, `d2h` suffixes for req, rsp pair. """ if ims["package"] == "tlul_pkg" and ims["struct"] == "tl": return ("_h2d", "_d2h") return ("_req", "_rsp") def add_intermodule_connection(obj: OrderedDict, req_m: str, req_s: str, rsp_m: str, rsp_s: str): """Add if doesn't exist the connection Add a connection into obj['inter_module']['connect'] dictionary if doesn't exist. Parameters: obj: Top dictionary object req_m: Requester module name req_s: Requester signal name rsp_m: Responder module name rsp_s: Responder signal name Returns: No return type for this function """ req_key = "{}.{}".format(req_m, req_s) rsp_key = "{}.{}".format(rsp_m, rsp_s) connect = obj["inter_module"]["connect"] if req_key in connect: # check if rsp has data if rsp_key in connect[req_key]: return req_key.append(rsp_key) return # req_key is not in connect: # check if rsp_key if rsp_key in connect: # check if rsp has data if req_key in connect[rsp_key]: return rsp_key.append(req_key) return # Add new key and connect connect[req_key] = [rsp_key] def autoconnect_xbar(topcfg: OrderedDict, name_to_block: Dict[str, IpBlock], xbar: OrderedDict) -> None: # The crossbar is connecting to modules and memories in topcfg, plus # possible external connections. Make indices for the modules and memories # for quick lookup and add some assertions to make sure no name appears in # multiple places. name_to_module = {} for mod in topcfg['module']: assert mod['name'] not in name_to_module if lib.is_inst(mod): name_to_module[mod['name']] = mod name_to_memory = {} for mem in topcfg['memory']: assert mem['name'] not in name_to_memory if lib.is_inst(mem): name_to_memory[mem['name']] = mem # The names of modules and memories should be disjoint assert not (set(name_to_module.keys()) & set(name_to_memory.keys())) external_names = (set(topcfg['inter_module']['top']) | set(topcfg["inter_module"]["external"].keys())) ports = [x for x in xbar["nodes"] if x["type"] in ["host", "device"]] for port in ports: # Here, we expect port_name to either be a single identifier (in which # case, it's taken as the name of some module or memory) to be a dotted # pair MOD.INAME where MOD is the name of some module and INAME is the # associated interface name. name_parts = port['name'].split('.', 1) port_base = name_parts[0] port_iname = name_parts[1] if len(name_parts) > 1 else None esc_name = port['name'].replace('.', '__') if port["xbar"]: if port_iname is not None: log.error('A crossbar connection may not ' 'have a target of the form MOD.INAME (saw {!r})' .format(port['name'])) continue if port["type"] == "host": # Skip as device will add connection continue # Device port adds signal add_intermodule_connection(obj=topcfg, req_m=xbar["name"], req_s="tl_" + esc_name, rsp_m=esc_name, rsp_s="tl_" + xbar["name"]) continue # xbar port case port_mod = name_to_module.get(port_base) port_mem = name_to_memory.get(port_base) assert port_mod is None or port_mem is None if not (port_mod or port_mem): # if not in module, memory, should be existed in top or ext field module_key = "{}.tl_{}".format(xbar["name"], esc_name) if module_key not in external_names: log.error("Inter-module key {} cannot be found in module, " "memory, top, or external lists.".format(module_key)) continue if port_iname is not None and port_mem is not None: log.error('Cannot make connection for {!r}: the base of the name ' 'points to a memory but memories do not support ' 'interface names.' .format(port['name'])) is_host = port['type'] == 'host' # If the hit is a module, it originally came from reggen (via # merge.py's amend_ip() function). In this case, we should have a # BusInterfaces object as well as a list of InterSignal objects. # # If not, this is a memory that will just have a dictionary of inter # signals. if port_mod is not None: block = name_to_block[port_mod['type']] try: sig_name = block.bus_interfaces.find_port_name(is_host, port_iname) except KeyError: log.error('Cannot make {} connection for {!r}: the base of ' 'the target module has no matching bus interface.' .format('host' if is_host else 'device', port['name'])) continue else: inter_signal_list = port_mem['inter_signal_list'] act = 'req' if is_host else 'rsp' matches = [ x for x in inter_signal_list if (x.get('package') == 'tlul_pkg' and x['struct'] == 'tl' and x['act'] == act) ] if not matches: log.error('Cannot make {} connection for {!r}: the memory ' 'has no signal with an action of {}.' .format('host' if is_host else 'device', port['name'], act)) continue assert len(matches) == 1 sig_name = matches[0]['name'] add_intermodule_connection(obj=topcfg, req_m=port_base, req_s=sig_name, rsp_m=xbar["name"], rsp_s="tl_" + esc_name) def autoconnect(topcfg: OrderedDict, name_to_block: Dict[str, IpBlock]): """Matching the connection based on the naming rule between {memory, module} <-> Xbar. """ # Add xbar connection to the modules, memories for xbar in topcfg["xbar"]: autoconnect_xbar(topcfg, name_to_block, xbar) def _get_default_name(sig, suffix): """Generate default for a net if one does not already exist. """ # The else case covers the scenario where neither package nor default is provided. # Specifically, the interface is 'logic' and has no default value. # In this situation, just return 0's if sig['default']: return sig['default'] elif sig['package']: return "{}::{}_DEFAULT".format(sig['package'], (sig["struct"] + suffix).upper()) else: return "'0" def elab_intermodule(topcfg: OrderedDict): """Check the connection of inter-module and categorize them In the top template, it uses updated inter_module fields to create connections between the modules (incl. memories). This function is to create and check the validity of the connections `inter_module` using IPs' `inter_signal_list`. """ list_of_intersignals = [] if "inter_signal" not in topcfg: topcfg["inter_signal"] = OrderedDict() # Gather the inter_signal_list instances = topcfg["module"] + topcfg["memory"] + topcfg["xbar"] + \ topcfg["host"] + topcfg["port"] for x in instances: old_isl = x.get('inter_signal_list') if old_isl is None: continue new_isl = [] for entry in old_isl: # Convert any InterSignal objects to the expected dictionary format. sig = (entry.as_dict() if isinstance(entry, InterSignal) else entry.copy()) # Add instance name to the entry and add to list_of_intersignals sig["inst_name"] = x["name"] list_of_intersignals.append(sig) new_isl.append(sig) x['inter_signal_list'] = new_isl # Add field to the topcfg topcfg["inter_signal"]["signals"] = list_of_intersignals # TODO: Cross check Can be done here not in validate as ipobj is not # available in validate error = check_intermodule(topcfg, "Inter-module Check") assert error == 0, "Inter-module validation is failed cannot move forward." # intermodule definitions = [] # Check the originator # As inter-module connection allow only 1:1, 1:N, or N:1, pick the most # common signals. If a requester connects to multiple responders/receivers, # the requester is main connector so that the definition becomes array. # # For example: # inter_module: { # 'connect': { # 'pwr_mgr.pwrup': ['lc.pwrup', 'otp.pwrup'] # } # } # The tool adds `struct [1:0] pwr_mgr_pwrup` # It doesn't matter whether `pwr_mgr.pwrup` is requester or responder. # If the key is responder type, then the connection is made in reverse, # such that `lc.pwrup --> pwr_mgr.pwrup[0]` and # `otp.pwrup --> pwr_mgr.pwrup[1]` uid = 0 # Unique connection ID across the top for req, rsps in topcfg["inter_module"]["connect"].items(): log.info("{req} --> {rsps}".format(req=req, rsps=rsps)) # Split index req_module, req_signal, req_index = filter_index(req) # get the module signal req_struct = find_intermodule_signal(list_of_intersignals, req_module, req_signal) # decide signal format based on the `key` sig_name = intersignal_format(req_struct) req_struct["top_signame"] = sig_name # Find package in req, rsps if "package" in req_struct: package = req_struct["package"] else: for rsp in rsps: rsp_module, rsp_signal, rsp_index = filter_index(rsp) rsp_struct = find_intermodule_signal(list_of_intersignals, rsp_module, rsp_signal) if "package" in rsp_struct: package = rsp_struct["package"] break if not package: package = "" # Add to definition if req_struct["type"] == "req_rsp": req_suffix, rsp_suffix = get_suffixes(req_struct) req_default = _get_default_name(req_struct, req_suffix) rsp_default = _get_default_name(req_struct, rsp_suffix) # based on the active direction of the req_struct, one of the directions does not # need a default since it will be an output if (req_struct["act"] == 'req'): req_default = '' else: rsp_default = '' # Add two definitions definitions.append( OrderedDict([('package', package), ('struct', req_struct["struct"] + req_suffix), ('signame', sig_name + "_req"), ('width', req_struct["width"]), ('type', req_struct["type"]), ('end_idx', req_struct["end_idx"]), ('act', req_struct["act"]), ('suffix', "req"), ('default', req_default)])) definitions.append( OrderedDict([('package', package), ('struct', req_struct["struct"] + rsp_suffix), ('signame', sig_name + "_rsp"), ('width', req_struct["width"]), ('type', req_struct["type"]), ('end_idx', req_struct["end_idx"]), ('act', req_struct["act"]), ('suffix', "rsp"), ('default', rsp_default)])) else: # unidirection default = _get_default_name(req_struct, "") definitions.append( OrderedDict([('package', package), ('struct', req_struct["struct"]), ('signame', sig_name), ('width', req_struct["width"]), ('type', req_struct["type"]), ('end_idx', req_struct["end_idx"]), ('act', req_struct["act"]), ('suffix', ""), ('default', default)])) req_struct["index"] = -1 for i, rsp in enumerate(rsps): # Split index rsp_module, rsp_signal, rsp_index = filter_index(rsp) rsp_struct = find_intermodule_signal(list_of_intersignals, rsp_module, rsp_signal) # determine the signal name rsp_struct["top_signame"] = sig_name if req_struct["type"] == "uni" and req_struct[ "top_type"] == "broadcast": rsp_struct["index"] = -1 elif rsp_struct["width"] == req_struct["width"] and len(rsps) == 1: rsp_struct["index"] = -1 else: rsp_struct["index"] = -1 if req_struct["width"] == 1 else i # Assume it is logic # req_rsp doesn't allow logic if req_struct["struct"] == "logic": assert req_struct[ "type"] != "req_rsp", "logic signal cannot have req_rsp type" # increase Unique ID uid += 1 # TODO: Check unconnected port if "top" not in topcfg["inter_module"]: topcfg["inter_module"]["top"] = [] for s in topcfg["inter_module"]["top"]: sig_m, sig_s, sig_i = filter_index(s) assert sig_i == -1, 'top net connection should not use bit index' sig = find_intermodule_signal(list_of_intersignals, sig_m, sig_s) sig_name = intersignal_format(sig) sig["top_signame"] = sig_name if "index" not in sig: sig["index"] = -1 if sig["type"] == "req_rsp": req_suffix, rsp_suffix = get_suffixes(sig) # Add two definitions definitions.append( OrderedDict([('package', sig["package"]), ('struct', sig["struct"] + req_suffix), ('signame', sig_name + "_req"), ('width', sig["width"]), ('type', sig["type"]), ('end_idx', -1), ('default', sig["default"])])) definitions.append( OrderedDict([('package', sig["package"]), ('struct', sig["struct"] + rsp_suffix), ('signame', sig_name + "_rsp"), ('width', sig["width"]), ('type', sig["type"]), ('end_idx', -1), ('default', sig["default"])])) else: # if sig["type"] == "uni": definitions.append( OrderedDict([('package', sig["package"]), ('struct', sig["struct"]), ('signame', sig_name), ('width', sig["width"]), ('type', sig["type"]), ('end_idx', -1), ('default', sig["default"])])) topcfg["inter_module"].setdefault('external', []) topcfg["inter_signal"].setdefault('external', []) for s, port in topcfg["inter_module"]["external"].items(): sig_m, sig_s, sig_i = filter_index(s) assert sig_i == -1, 'top net connection should not use bit index' sig = find_intermodule_signal(list_of_intersignals, sig_m, sig_s) # To make netname `_o` or `_i` sig['external'] = True sig_name = port if port != "" else intersignal_format(sig) # if top signame already defined, then a previous connection category # is already connected to external pin. Sig name is only used for # port definition conn_type = False if "top_signame" not in sig: sig["top_signame"] = sig_name else: conn_type = True if "index" not in sig: sig["index"] = -1 # Add the port definition to top external ports index = sig["index"] netname = sig["top_signame"] if sig["type"] == "req_rsp": req_suffix, rsp_suffix = get_suffixes(sig) if sig["act"] == "req": req_sigsuffix, rsp_sigsuffix = ("_o", "_i") else: req_sigsuffix, rsp_sigsuffix = ("_i", "_o") topcfg["inter_signal"]["external"].append( OrderedDict([('package', sig["package"]), ('struct', sig["struct"] + req_suffix), ('signame', sig_name + "_req" + req_sigsuffix), ('width', sig["width"]), ('type', sig["type"]), ('default', sig["default"]), ('direction', 'out' if sig['act'] == "req" else 'in'), ('conn_type', conn_type), ('index', index), ('netname', netname + req_suffix)])) topcfg["inter_signal"]["external"].append( OrderedDict([('package', sig["package"]), ('struct', sig["struct"] + rsp_suffix), ('signame', sig_name + "_rsp" + rsp_sigsuffix), ('width', sig["width"]), ('type', sig["type"]), ('default', sig["default"]), ('direction', 'in' if sig['act'] == "req" else 'out'), ('conn_type', conn_type), ('index', index), ('netname', netname + rsp_suffix)])) else: # uni if sig["act"] == "req": sigsuffix = "_o" else: sigsuffix = "_i" topcfg["inter_signal"]["external"].append( OrderedDict([('package', sig.get("package", "")), ('struct', sig["struct"]), ('signame', sig_name + sigsuffix), ('width', sig["width"]), ('type', sig["type"]), ('default', sig["default"]), ('direction', 'out' if sig['act'] == "req" else 'in'), ('conn_type', conn_type), ('index', index), ('netname', netname)])) for sig in topcfg["inter_signal"]["signals"]: # Check if it exist in definitions if "top_signame" in sig: continue # Set index to -1 sig["index"] = -1 # TODO: Handle the unconnected port rule if "definitions" not in topcfg["inter_signal"]: topcfg["inter_signal"]["definitions"] = definitions def filter_index(signame: str) -> Tuple[str, str, int]: """If the signal has array indicator `[N]` then split and return name and array index. If not, array index is -1. param signame module.sig{[N]} result (module_name, signal_name, array_index) """ m = re.match(r'(\w+)\.(\w+)(\[(\d+)\])*', signame) if not m: # Cannot match the pattern return "", "", -1 if m.group(3): # array index is not None return m.group(1), m.group(2), m.group(4) return m.group(1), m.group(2), -1 def find_intermodule_signal(sig_list, m_name, s_name) -> Dict: """Return the intermodule signal structure """ filtered = [ x for x in sig_list if x["name"] == s_name and x["inst_name"] == m_name ] if len(filtered) == 1: return filtered[0] log.error("Found {num} entry/entries for {m_name}.{s_name}:".format( num=len(filtered), m_name=m_name, s_name=s_name)) return None # Validation def check_intermodule_field(sig: OrderedDict, prefix: str = "") -> Tuple[int, OrderedDict]: error = 0 # type check if sig["type"] not in IM_TYPES: log.error("{prefix} Inter_signal {name} " "type {type} is incorrect.".format(prefix=prefix, name=sig["name"], type=sig["type"])) error += 1 if sig["act"] not in IM_ACTS: log.error("{prefix} Inter_signal {name} " "act {act} is incorrect.".format(prefix=prefix, name=sig["name"], act=sig["act"])) error += 1 # Check if type and act are matched if error == 0: if sig["act"] not in IM_VALID_TYPEACT[sig['type']]: log.error("{type} and {act} of {name} are not a valid pair." "".format(type=sig['type'], act=sig['act'], name=sig['name'])) error += 1 # Check 'width' field width = 1 if "width" not in sig: sig["width"] = 1 elif not isinstance(sig["width"], int): width, err = check_int(sig["width"], sig["name"]) if err: log.error("{prefix} Inter-module {inst}.{sig} 'width' " "should be int type.".format(prefix=prefix, inst=sig["inst_name"], sig=sig["name"])) error += 1 else: # convert to int value sig["width"] = width # Add empty string if no explicit default for dangling pins is given. # In that case, dangling pins of type struct will be tied to the default # parameter in the corresponding package, and dangling pins of type logic # will be tied off to '0. if "default" not in sig: sig["default"] = "" if "package" not in sig: sig["package"] = "" return error, sig def find_otherside_modules(topcfg: OrderedDict, m, s) -> List[Tuple[str, str, str]]: """Find far-end port based on given module and signal name """ # TODO: handle special cases special_inst_names = { ('main', 'tl_rom'): ('tl_adapter_rom', 'tl'), ('main', 'tl_ram_main'): ('tl_adapter_ram_main', 'tl'), ('main', 'tl_eflash'): ('tl_adapter_eflash', 'tl'), ('peri', 'tl_ram_ret_aon'): ('tl_adapter_ram_ret_aon', 'tl'), ('main', 'tl_corei'): ('rv_core_ibex', 'tl_i'), ('main', 'tl_cored'): ('rv_core_ibex', 'tl_d'), ('main', 'tl_dm_sba'): ('dm_top', 'tl_h'), ('main', 'tl_debug_mem'): ('dm_top', 'tl_d'), ('peri', 'tl_ast'): ('ast', 'tl') } special_result = special_inst_names.get((m, s)) if special_result is not None: return [('top', special_result[0], special_result[1])] signame = "{}.{}".format(m, s) for req, rsps in topcfg["inter_module"]["connect"].items(): if req.startswith(signame): # return rsps after splitting module instance name and the port result = [] for rsp in rsps: rsp_m, rsp_s, rsp_i = filter_index(rsp) result.append(('connect', rsp_m, rsp_s)) return result for rsp in rsps: if signame == rsp: req_m, req_s, req_i = filter_index(req) return [('connect', req_m, req_s)] # if reaches here, it means either the format is wrong, or floating port. log.error("`find_otherside_modules()`: " "No such signal {}.{} exists.".format(m, s)) return [] def check_intermodule(topcfg: Dict, prefix: str) -> int: if "inter_module" not in topcfg: return 0 total_error = 0 for req, rsps in topcfg["inter_module"]["connect"].items(): error = 0 # checking the key, value are in correct format # Allowed format # 1. module.signal # 2. module.signal[index] // Remember array is not yet supported # // But allow in format checker # # Example: # inter_module: { # 'connect': { # 'flash_ctrl.flash': ['eflash.flash_ctrl'], # 'life_cycle.provision': ['debug_tap.dbg_en', 'dft_ctrl.en'], # 'otp.pwr_hold': ['pwrmgr.peri[0]'], # 'flash_ctrl.pwr_hold': ['pwrmgr.peri[1]'], # } # } # # If length of value list is > 1, then key should be array (width need to match) # If key is format #2, then length of value list shall be 1 # If one of the value is format #2, then the key should be 1 bit width and # entries of value list should be 1 req_m, req_s, req_i = filter_index(req) if req_s == "": log.error( "Cannot parse the inter-module signal key '{req}'".format( req=req)) error += 1 # Check rsps signal format is list if not isinstance(rsps, list): log.error("Value of key '{req}' should be a list".format(req=req)) error += 1 continue req_struct = find_intermodule_signal(topcfg["inter_signal"]["signals"], req_m, req_s) err, req_struct = check_intermodule_field(req_struct) error += err if req_i != -1 and len(rsps) != 1: # Array format should have one entry log.error( "If key {req} has index, only one entry is allowed.".format( req=req)) error += 1 total_width = 0 widths = [] # Check rsp format for i, rsp in enumerate(rsps): rsp_m, rsp_s, rsp_i = filter_index(rsp) if rsp_s == "": log.error( "Cannot parse the inter-module signal key '{req}->{rsp}'". format(req=req, rsp=rsp)) error += 1 rsp_struct = find_intermodule_signal( topcfg["inter_signal"]["signals"], rsp_m, rsp_s) err, rsp_struct = check_intermodule_field(rsp_struct) error += err total_width += rsp_struct["width"] widths.append(rsp_struct["width"]) # Type check # If no package was declared, it is declared with an empty string if not rsp_struct["package"]: rsp_struct["package"] = req_struct.get("package", "") elif req_struct["package"] != rsp_struct["package"]: log.error( "Inter-module package should be matched: " "{req}->{rsp} exp({expected}), actual({actual})".format( req=req_struct["name"], rsp=rsp_struct["name"], expected=req_struct["package"], actual=rsp_struct["package"])) error += 1 if req_struct["type"] != rsp_struct["type"]: log.error( "Inter-module type should be matched: " "{req}->{rsp} exp({expected}), actual({actual})".format( req=req_struct["name"], rsp=rsp_struct["name"], expected=req_struct["type"], actual=rsp_struct["type"])) error += 1 # If len(rsps) is 1, then the width should be matched to req if req_struct["width"] != 1: if rsp_struct["width"] not in [1, req_struct["width"]]: log.error( "If req {req} is an array, " "rsp {rsp} shall be non-array or array with same width" .format(req=req, rsp=rsp)) error += 1 elif rsp_i != -1: # If rsp has index, req should be width 1 log.error( "If rsp {rsp} has an array index, only one-to-one map is allowed." .format(rsp=rsp)) error += 1 # Determine if broadcast or one-to-N log.debug("Handling inter-sig {} {}".format(req_struct['name'], total_width)) req_struct["end_idx"] = -1 if req_struct["width"] > 1 or len(rsps) != 1: # If req width is same to the every width of rsps ==> broadcast if len(rsps) * [req_struct["width"]] == widths: log.debug("broadcast type") req_struct["top_type"] = "broadcast" # If req width is same as total width of rsps ==> one-to-N elif req_struct["width"] == total_width: log.debug("one-to-N type") req_struct["top_type"] = "one-to-N" # one-to-N connection is not fully populated elif req_struct["width"] > total_width: log.debug("partial one-to-N type") req_struct["top_type"] = "partial-one-to-N" req_struct["end_idx"] = len(rsps) # If not, error else: log.error("'uni' type connection {req} should be either " "OneToN or Broadcast".format(req=req)) error += 1 elif req_struct["type"] == "uni": # one-to-one connection req_struct["top_type"] = "broadcast" # If req is array, it is not allowed to have partial connections. # Doing for loop again here: Make code separate from other checker # for easier maintenance total_error += error if error != 0: # Skip the check continue for item in topcfg["inter_module"]["top"] + list( topcfg["inter_module"]["external"].keys()): sig_m, sig_s, sig_i = filter_index(item) if sig_i != -1: log.error("{item} cannot have index".format(item=item)) total_error += 1 sig_struct = find_intermodule_signal(topcfg["inter_signal"]["signals"], sig_m, sig_s) err, sig_struct = check_intermodule_field(sig_struct) total_error += err return total_error # Template functions def im_defname(obj: OrderedDict) -> str: """return definition struct name e.g. flash_ctrl::flash_req_t """ if obj["package"] == "": # should be logic return "logic" return "{package}::{struct}_t".format(package=obj["package"], struct=obj["struct"]) def im_netname(sig: OrderedDict, suffix: str = "", default_name=False) -> str: """return top signal name with index It also adds suffix for external signal. The default name input forces function to return default name, even if object has a connection. """ # Basic check and add missing fields err, obj = check_intermodule_field(sig) assert not err # Floating signals # TODO: Find smarter way to assign default? if "top_signame" not in obj or default_name: if obj["act"] == "req" and suffix == "req": return "" if obj["act"] == "rsp" and suffix == "rsp": return "" if obj["act"] == "req" and suffix == "rsp": # custom default has been specified if obj["default"]: return obj["default"] if obj["package"] == "tlul_pkg" and obj["struct"] == "tl": return "{package}::{struct}_D2H_DEFAULT".format( package=obj["package"], struct=obj["struct"].upper()) return "{package}::{struct}_RSP_DEFAULT".format( package=obj["package"], struct=obj["struct"].upper()) if obj["act"] == "rsp" and suffix == "req": # custom default has been specified if obj["default"]: return obj["default"] if obj.get("package") == "tlul_pkg" and obj["struct"] == "tl": return "{package}::{struct}_H2D_DEFAULT".format( package=obj["package"], struct=obj["struct"].upper()) # default is used for dangling ports in definitions. # the struct name already has `_req` suffix return "{package}::{struct}_REQ_DEFAULT".format( package=obj.get("package", ''), struct=obj["struct"].upper()) if obj["act"] == "rcv" and suffix == "" and obj["struct"] == "logic": # custom default has been specified if obj["default"]: return obj["default"] return "'0" if obj["act"] == "rcv" and suffix == "": # custom default has been specified if obj["default"]: return obj["default"] return "{package}::{struct}_DEFAULT".format( package=obj["package"], struct=obj["struct"].upper()) return "" # Connected signals assert suffix in ["", "req", "rsp"] suffix_s = "_{suffix}".format(suffix=suffix) if suffix != "" else suffix # External signal handling if "external" in obj and obj["external"]: pairs = { # act , suffix: additional suffix ("req", "req"): "_o", ("req", "rsp"): "_i", ("rsp", "req"): "_i", ("rsp", "rsp"): "_o", ("req", ""): "_o", ("rcv", ""): "_i" } suffix_s += pairs[(obj['act'], suffix)] return "{top_signame}{suffix}{index}".format( top_signame=obj["top_signame"], suffix=suffix_s, index=lib.index(obj["index"])) def im_portname(obj: OrderedDict, suffix: str = "") -> str: """return IP's port name e.g signame_o for requester req signal """ act = obj['act'] name = obj['name'] if suffix == "": suffix_s = "_o" if act == "req" else "_i" elif suffix == "req": suffix_s = "_o" if act == "req" else "_i" else: suffix_s = "_o" if act == "rsp" else "_i" return name + suffix_s def get_dangling_im_def(objs: OrderedDict) -> str: """return partial inter-module definitions Dangling intermodule connections happen when a one-to-N assignment is not fully populated. This can result in two types of dangling: - outgoing requests not used - incoming responses not driven The determination of which category we fall into follows similar rules as those used by im_netname. When the direction of the net is the same as the active direction of the the connecting module, it is "unused". When the direction of the net is opposite of the active direction of the the connecting module, it is "undriven". As an example, edn is defined as "rsp" of a "req_rsp" pair. It is also used as the "active" module in inter-module connection. If there are not enough connecting modules, the 'req' line is undriven, while the 'rsp' line is unused. """ unused_def = [obj for obj in objs if obj['end_idx'] > 0 and obj['act'] == obj['suffix']] undriven_def = [obj for obj in objs if obj['end_idx'] > 0 and (obj['act'] == 'req' and obj['suffix'] == 'rsp' or obj['act'] == 'rsp' and obj['suffix'] == 'req')] return unused_def, undriven_def
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import logging as log import re import sys from collections import OrderedDict from copy import deepcopy from pathlib import Path from typing import Dict, List, Optional, Tuple import hjson from reggen.ip_block import IpBlock # Ignore flake8 warning as the function is used in the template # disable isort formating, as conflicting with flake8 from .intermodule import find_otherside_modules # noqa : F401 # isort:skip from .intermodule import im_portname, im_defname, im_netname # noqa : F401 # isort:skip from .intermodule import get_dangling_im_def # noqa : F401 # isort:skip class Name: """ We often need to format names in specific ways; this class does so. To simplify parsing and reassembling of name strings, this class stores the name parts as a canonical list of strings internally (in self.parts). The "from_*" functions parse and split a name string into the canonical list, whereas the "as_*" functions reassemble the canonical list in the format specified. For example, ex = Name.from_snake_case("example_name") gets split into ["example", "name"] internally, and ex.as_camel_case() reassembles this internal representation into "ExampleName". """ def __add__(self, other): return Name(self.parts + other.parts) @staticmethod def from_snake_case(input: str) -> 'Name': return Name(input.split("_")) def __init__(self, parts: List[str]): self.parts = parts for p in parts: assert len(p) > 0, "cannot add zero-length name piece" def as_snake_case(self) -> str: return "_".join([p.lower() for p in self.parts]) def as_camel_case(self) -> str: out = "" for p in self.parts: # If we're about to join two parts which would introduce adjacent # numbers, put an underscore between them. if out[-1:].isnumeric() and p[:1].isnumeric(): out += "_" + p else: out += p.capitalize() return out def as_c_define(self) -> str: return "_".join([p.upper() for p in self.parts]) def as_c_enum(self) -> str: return "k" + self.as_camel_case() def as_c_type(self) -> str: return self.as_snake_case() + "_t" def remove_part(self, part_to_remove: str) -> "Name": return Name([p for p in self.parts if p != part_to_remove]) def is_ipcfg(ip: Path) -> bool: # return bool log.info("IP Path: %s" % repr(ip)) ip_name = ip.parents[1].name hjson_name = ip.name log.info("IP Name(%s) and HJSON name (%s)" % (ip_name, hjson_name)) if ip_name + ".hjson" == hjson_name or ip_name + "_reg.hjson" == hjson_name: return True return False def search_ips(ip_path): # return list of config files # list the every Hjson file p = ip_path.glob('*/data/*.hjson') # filter only ip_name/data/ip_name{_reg|''}.hjson ips = [x for x in p if is_ipcfg(x)] log.info("Filtered-in IP files: %s" % repr(ips)) return ips def is_xbarcfg(xbar_obj): if "type" in xbar_obj and xbar_obj["type"] == "xbar": return True return False def get_hjsonobj_xbars(xbar_path): """ Search crossbars Hjson files from given path. Search every Hjson in the directory and check Hjson type. It could be type: "top" or type: "xbar" returns [(name, obj), ... ] """ p = xbar_path.glob('*.hjson') try: xbar_objs = [ hjson.load(x.open('r'), use_decimal=True, object_pairs_hook=OrderedDict) for x in p ] except ValueError: raise SystemExit(sys.exc_info()[1]) xbar_objs = [x for x in xbar_objs if is_xbarcfg(x)] return xbar_objs def get_module_by_name(top, name): """Search in top["module"] by name """ module = None for m in top["module"]: if m["name"] == name: module = m break return module def intersignal_to_signalname(top, m_name, s_name) -> str: # TODO: Find the signal in the `inter_module_list` and get the correct signal name return "{m_name}_{s_name}".format(m_name=m_name, s_name=s_name) def get_package_name_by_intermodule_signal(top, struct) -> str: """Search inter-module signal package with the struct name For instance, if `flash_ctrl` has inter-module signal package, this function returns the package name """ instances = top["module"] + top["memory"] intermodule_instances = [ x["inter_signal_list"] for x in instances if "inter_signal_list" in x ] for m in intermodule_instances: if m["name"] == struct and "package" in m: return m["package"] return "" def get_signal_by_name(module, name): """Return the signal struct with the type input/output/inout """ result = None for s in module["available_input_list"] + module[ "available_output_list"] + module["available_inout_list"]: if s["name"] == name: result = s break return result def add_module_prefix_to_signal(signal, module): """Add module prefix to module signal format { name: "sig_name", width: NN } """ result = deepcopy(signal) if "name" not in signal: raise SystemExit("signal {} doesn't have name field".format(signal)) result["name"] = module + "_" + signal["name"] result["module_name"] = module return result def get_ms_name(name): """Split module_name.signal_name to module_name , signal_name """ tokens = name.split('.') if len(tokens) == 0: raise SystemExit("This to be catched in validate.py") module = tokens[0] signal = None if len(tokens) == 2: signal = tokens[1] return module, signal def parse_pad_field(padstr): """Parse PadName[NN...NN] or PadName[NN] or just PadName """ match = re.match(r'^([A-Za-z0-9_]+)(\[([0-9]+)(\.\.([0-9]+))?\]|)', padstr) return match.group(1), match.group(3), match.group(5) def get_pad_list(padstr): pads = [] pad, first, last = parse_pad_field(padstr) if first is None: first = 0 last = 0 elif last is None: last = first first = int(first, 0) last = int(last, 0) # width = first - last + 1 for p in range(first, last + 1): pads.append(OrderedDict([("name", pad), ("index", p)])) return pads # Template functions def ljust(x, width): return "{:<{width}}".format(x, width=width) def bitarray(d, width): """Print Systemverilog bit array @param d the bit width of the signal @param width max character width of the signal group For instance, if width is 4, the max d value in the signal group could be 9999. If d is 2, then this function pads 3 spaces at the end of the bit slice. "[1:0] " <- d:=2, width=4 "[9999:0]" <- max d-1 value If d is 1, it means array slice isn't necessary. So it returns empty spaces """ if d <= 0: log.error("lib.bitarray: Given value {} is smaller than 1".format(d)) raise ValueError if d == 1: return " " * (width + 4) # [x:0] needs 4 more space than char_width out = "[{}:0]".format(d - 1) return out + (" " * (width - len(str(d)))) def parameterize(text): """Return the value wrapping with quote if not integer nor bits """ if re.match(r'(\d+\'[hdb]\s*[0-9a-f_A-F]+|[0-9]+)', text) is None: return "\"{}\"".format(text) return text def index(i: int) -> str: """Return index if it is not -1 """ return "[{}]".format(i) if i != -1 else "" def get_clk_name(clk): """Return the appropriate clk name """ if clk == 'main': return 'clk_i' else: return "clk_{}_i".format(clk) def get_reset_path(reset, domain, reset_cfg): """Return the appropriate reset path given name """ # find matching node for reset node_match = [node for node in reset_cfg['nodes'] if node['name'] == reset] assert len(node_match) == 1 reset_type = node_match[0]['type'] # find matching path hier_path = "" if reset_type == "int": log.debug("{} used as internal reset".format(reset["name"])) else: hier_path = reset_cfg['hier_paths'][reset_type] # find domain selection domain_sel = '' if reset_type not in ["ext", "int"]: domain_sel = "[rstmgr_pkg::Domain{}Sel]".format(domain) reset_path = "" if reset_type == "ext": reset_path = reset else: reset_path = "{}rst_{}_n{}".format(hier_path, reset, domain_sel) return reset_path def get_unused_resets(top): """Return dict of unused resets and associated domain """ unused_resets = OrderedDict() unused_resets = { reset['name']: domain for reset in top['resets']['nodes'] for domain in top['power']['domains'] if reset['type'] == 'top' and domain not in reset['domains'] } log.debug("Unused resets are {}".format(unused_resets)) return unused_resets def is_templated(module): """Returns an indication where a particular module is templated """ if "attr" not in module: return False elif module["attr"] in ["templated"]: return True else: return False def is_top_reggen(module): """Returns an indication where a particular module is NOT templated and requires top level specific reggen """ if "attr" not in module: return False elif module["attr"] in ["reggen_top", "reggen_only"]: return True else: return False def is_inst(module): """Returns an indication where a particular module should be instantiated in the top level """ top_level_module = False top_level_mem = False if "attr" not in module: top_level_module = True elif module["attr"] in ["normal", "templated", "reggen_top"]: top_level_module = True elif module["attr"] in ["reggen_only"]: top_level_module = False else: raise ValueError('Attribute {} in {} is not valid' .format(module['attr'], module['name'])) if module['type'] in ['rom', 'ram_1p_scr', 'eflash']: top_level_mem = True return top_level_mem or top_level_module def get_base_and_size(name_to_block: Dict[str, IpBlock], inst: Dict[str, object], ifname: Optional[str]) -> Tuple[int, int]: min_device_spacing = 0x1000 block = name_to_block.get(inst['type']) if block is None: # If inst isn't the instantiation of a block, it came from some memory. # Memories have their sizes defined, so we can just look it up there. bytes_used = int(inst['size'], 0) # Memories don't have multiple or named interfaces, so this will only # work if ifname is None. assert ifname is None base_addr = inst['base_addr'] else: # If inst is the instantiation of some block, find the register block # that corresponds to ifname rb = block.reg_blocks.get(ifname) if rb is None: log.error('Cannot connect to non-existent {} device interface ' 'on {!r} (an instance of the {!r} block)' .format('default' if ifname is None else repr(ifname), inst['name'], block.name)) bytes_used = 0 else: bytes_used = 1 << rb.get_addr_width() base_addr = inst['base_addrs'][ifname] # Round up to min_device_spacing if necessary size_byte = max(bytes_used, min_device_spacing) if isinstance(base_addr, str): base_addr = int(base_addr, 0) else: assert isinstance(base_addr, int) return (base_addr, size_byte) def get_io_enum_literal(sig: Dict, prefix: str) -> str: """Returns the DIO pin enum literal with value assignment""" name = Name.from_snake_case(prefix) + Name.from_snake_case(sig["name"]) # In this case, the signal is a multibit signal, and hence # we have to make the signal index part of the parameter # name to uniquify it. if sig['width'] > 1: name += Name([str(sig['idx'])]) return name.as_camel_case() def make_bit_concatenation(sig_name: str, indices: List[int], end_indent: int) -> str: '''Return SV code for concatenating certain indices from a signal sig_name is the name of the signal and indices is a non-empty list of the indices to use, MSB first. So make_bit_concatenation("foo", [0, 100, 20]) should give {foo[0], foo[100], foo[20]} Adjacent bits turn into a range select. For example: make_bit_concatenation("foo", [0, 1, 2]) should give foo[0:2] If there are multiple ranges, they are printed one to a line. end_indent gives the indentation of the closing brace and the range selects in between get indented to end_indent + 2. ''' assert 0 <= end_indent ranges = [] cur_range_start = indices[0] cur_range_end = indices[0] for idx in indices[1:]: if idx == cur_range_end + 1 and cur_range_start <= cur_range_end: cur_range_end += 1 continue if idx == cur_range_end - 1 and cur_range_start >= cur_range_end: cur_range_end -= 1 continue ranges.append((cur_range_start, cur_range_end)) cur_range_start = idx cur_range_end = idx ranges.append((cur_range_start, cur_range_end)) items = [] for range_start, range_end in ranges: if range_start == range_end: select = str(range_start) else: select = '{}:{}'.format(range_start, range_end) items.append('{}[{}]'.format(sig_name, select)) if len(items) == 1: return items[0] item_indent = '\n' + (' ' * (end_indent + 2)) acc = ['{', item_indent, items[0]] for item in items[1:]: acc += [',', item_indent, item] acc += ['\n', ' ' * end_indent, '}'] return ''.join(acc)
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import logging as log import random from collections import OrderedDict from copy import deepcopy from math import ceil, log2 from typing import Dict, List from topgen import c, lib from reggen.ip_block import IpBlock from reggen.params import LocalParam, Parameter, RandParameter def _get_random_data_hex_literal(width): """ Fetch 'width' random bits and return them as hex literal""" width = int(width) literal_str = hex(random.getrandbits(width)) return literal_str def _get_random_perm_hex_literal(numel): """ Compute a random permutation of 'numel' elements and return as packed hex literal""" num_elements = int(numel) width = int(ceil(log2(num_elements))) idx = [x for x in range(num_elements)] random.shuffle(idx) literal_str = "" for k in idx: literal_str += format(k, '0' + str(width) + 'b') # convert to hex for space efficiency literal_str = hex(int(literal_str, 2)) return literal_str def elaborate_instances(top, name_to_block: Dict[str, IpBlock]): '''Add additional fields to the elements of top['module'] These elements represent instantiations of IP blocks. This function adds extra fields to them to carry across information from the IpBlock objects that represent the blocks being instantiated. See elaborate_instance for more details of what gets added. ''' # Initialize RNG for compile-time netlist constants. random.seed(int(top['rnd_cnst_seed'])) for instance in top['module']: block = name_to_block[instance['type']] elaborate_instance(instance, block) def elaborate_instance(instance, block: IpBlock): """Add additional fields to a single instance of a module. instance is the instance to be filled in. block is the block that it's instantiating. Altered fields: - param_list (list of parameters for the instance) - inter_signal_list (list of inter-module signals) - base_addrs (a map from interface name to its base address) Removed fields: - base_addr (this is reflected in base_addrs) """ mod_name = instance["name"] # param_list new_params = [] for param in block.params.by_name.values(): if isinstance(param, LocalParam): # Remove local parameters. continue new_param = param.as_dict() param_expose = param.expose if isinstance(param, Parameter) else False # Check for security-relevant parameters that are not exposed, # adding a top-level name. if param.name.lower().startswith("sec") and not param_expose: log.warning("{} has security-critical parameter {} " "not exposed to top".format( mod_name, param.name)) # Move special prefixes to the beginnining of the parameter name. param_prefixes = ["Sec", "RndCnst"] cc_mod_name = c.Name.from_snake_case(mod_name).as_camel_case() name_top = cc_mod_name + param.name for prefix in param_prefixes: if param.name.lower().startswith(prefix.lower()): name_top = (prefix + cc_mod_name + param.name[len(prefix):]) break new_param['name_top'] = name_top # Generate random bits or permutation, if needed if isinstance(param, RandParameter): if param.randtype == 'data': new_default = _get_random_data_hex_literal(param.randcount) # Effective width of the random vector randwidth = param.randcount else: assert param.randtype == 'perm' new_default = _get_random_perm_hex_literal(param.randcount) # Effective width of the random vector randwidth = param.randcount * ceil(log2(param.randcount)) new_param['default'] = new_default new_param['randwidth'] = randwidth new_params.append(new_param) instance["param_list"] = new_params # These objects get added-to in place by code in intermodule.py, so we have # to convert and copy them here. instance["inter_signal_list"] = [s.as_dict() for s in block.inter_signals] # An instance must either have a 'base_addr' address or a 'base_addrs' # address, but can't have both. base_addrs = instance.get('base_addrs') if base_addrs is None: if 'base_addr' not in instance: log.error('Instance {!r} has neither a base_addr ' 'nor a base_addrs field.' .format(instance['name'])) else: # If the instance has a base_addr field, make sure that the block # has just one device interface. if len(block.reg_blocks) != 1: log.error('Instance {!r} has a base_addr field but it ' 'instantiates the block {!r}, which has {} ' 'device interfaces.' .format(instance['name'], block.name, len(block.reg_blocks))) else: if_name = next(iter(block.reg_blocks)) base_addrs = {if_name: instance['base_addr']} # Fill in a bogus base address (we don't have proper error handling, so # have to do *something*) if base_addrs is None: base_addrs = {None: 0} instance['base_addrs'] = base_addrs else: if 'base_addr' in instance: log.error('Instance {!r} has both a base_addr ' 'and a base_addrs field.' .format(instance['name'])) # Since the instance already has a base_addrs field, make sure that # it's got the same set of keys as the name of the interfaces in the # block. inst_if_names = set(base_addrs.keys()) block_if_names = set(block.reg_blocks.keys()) if block_if_names != inst_if_names: log.error('Instance {!r} has a base_addrs field with keys {} ' 'but the block it instantiates ({!r}) has device ' 'interfaces {}.' .format(instance['name'], inst_if_names, block.name, block_if_names)) if 'base_addr' in instance: del instance['base_addr'] # TODO: Replace this part to be configurable from Hjson or template predefined_modules = { "corei": "rv_core_ibex", "cored": "rv_core_ibex", "dm_sba": "rv_dm", "debug_mem": "rv_dm" } def is_xbar(top, name): """Check if the given name is crossbar """ xbars = list(filter(lambda node: node["name"] == name, top["xbar"])) if len(xbars) == 0: return False, None if len(xbars) > 1: log.error("Matching crossbar {} is more than one.".format(name)) raise SystemExit() return True, xbars[0] def xbar_addhost(top, xbar, host): """Add host nodes information - xbar: bool, true if the host port is from another Xbar """ # Check and fetch host if exists in nodes obj = list(filter(lambda node: node["name"] == host, xbar["nodes"])) if len(obj) == 0: log.warning( "host %s doesn't exist in the node list. Using default values" % host) obj = OrderedDict([ ("name", host), ("clock", xbar['clock']), ("reset", xbar['reset']), ("type", "host"), ("inst_type", ""), ("stub", False), # The default matches RTL default # pipeline_byp is don't care if pipeline is false ("pipeline", "true"), ("pipeline_byp", "true") ]) xbar["nodes"].append(obj) return xbar_bool, xbar_h = is_xbar(top, host) if xbar_bool: log.info("host {} is a crossbar. Nothing to deal with.".format(host)) obj[0]["xbar"] = xbar_bool if 'clock' not in obj[0]: obj[0]["clock"] = xbar['clock'] if 'reset' not in obj[0]: obj[0]["reset"] = xbar["reset"] obj[0]["stub"] = False obj[0]["inst_type"] = predefined_modules[ host] if host in predefined_modules else "" obj[0]["pipeline"] = obj[0]["pipeline"] if "pipeline" in obj[0] else "true" obj[0]["pipeline_byp"] = obj[0]["pipeline_byp"] if obj[0][ "pipeline"] == "true" and "pipeline_byp" in obj[0] else "true" def process_pipeline_var(node): """Add device nodes pipeline / pipeline_byp information - Supply a default of true / true if not defined by xbar """ node["pipeline"] = node["pipeline"] if "pipeline" in node else "true" node["pipeline_byp"] = node[ "pipeline_byp"] if "pipeline_byp" in node else "true" def xbar_adddevice(top: Dict[str, object], name_to_block: Dict[str, IpBlock], xbar: Dict[str, object], other_xbars: List[str], device: str) -> None: """Add or amend an entry in xbar['nodes'] to represent the device interface - clock: comes from module if exist, use xbar default otherwise - reset: comes from module if exist, use xbar default otherwise - inst_type: comes from module or memory if exist. - base_addr: comes from module or memory, or assume rv_plic? - size_byte: comes from module or memory - xbar: bool, true if the device port is another xbar - stub: There is no backing module / memory, instead a tlul port is created and forwarded above the current hierarchy """ device_parts = device.split('.', 1) device_base = device_parts[0] device_ifname = device_parts[1] if len(device_parts) > 1 else None # Try to find a block or memory instance with name device_base. Object # names should be unique, so there should never be more than one hit. instances = [ node for node in top["module"] + top["memory"] if node['name'] == device_base ] assert len(instances) <= 1 inst = instances[0] if instances else None # Try to find a node in the crossbar called device. Node names should be # unique, so there should never be more than one hit. nodes = [ node for node in xbar['nodes'] if node['name'] == device ] assert len(nodes) <= 1 node = nodes[0] if nodes else None log.info("Handling xbar device {} (matches instance? {}; matches node? {})" .format(device, inst is not None, node is not None)) # case 1: another xbar --> check in xbar list if node is None and device in other_xbars: log.error( "Another crossbar %s needs to be specified in the 'nodes' list" % device) return # If there is no module or memory with the right name, this might still be # ok: we might be connecting to another crossbar or to a predefined module. if inst is None: # case 1: Crossbar handling if device in other_xbars: log.info( "device {} in Xbar {} is connected to another Xbar".format( device, xbar["name"])) assert node is not None node["xbar"] = True node["stub"] = False process_pipeline_var(node) return # case 2: predefined_modules (debug_mem, rv_plic) # TODO: Find configurable solution not from predefined but from object? if device in predefined_modules: if device == "debug_mem": if node is None: # Add new debug_mem xbar["nodes"].append({ "name": "debug_mem", "type": "device", "clock": xbar['clock'], "reset": xbar['reset'], "inst_type": predefined_modules["debug_mem"], "addr_range": [OrderedDict([ ("base_addr", top["debug_mem_base_addr"]), ("size_byte", "0x1000"), ])], "xbar": False, "stub": False, "pipeline": "true", "pipeline_byp": "true" }) # yapf: disable else: # Update if exists node["inst_type"] = predefined_modules["debug_mem"] node["addr_range"] = [ OrderedDict([("base_addr", top["debug_mem_base_addr"]), ("size_byte", "0x1000")]) ] node["xbar"] = False node["stub"] = False process_pipeline_var(node) else: log.error("device %s shouldn't be host type" % device) return # case 3: not defined # Crossbar check log.error("Device %s doesn't exist in 'module', 'memory', predefined, " "or as a node object" % device) return # If we get here, inst points an instance of some block or memory. It # shouldn't point at a crossbar (because that would imply a naming clash) assert device_base not in other_xbars base_addr, size_byte = lib.get_base_and_size(name_to_block, inst, device_ifname) addr_range = {"base_addr": hex(base_addr), "size_byte": hex(size_byte)} stub = not lib.is_inst(inst) if node is None: log.error('Cannot connect to {!r} because ' 'the crossbar defines no node for {!r}.' .format(device, device_base)) return node["inst_type"] = inst["type"] node["addr_range"] = [addr_range] node["xbar"] = False node["stub"] = stub process_pipeline_var(node) def amend_xbar(top: Dict[str, object], name_to_block: Dict[str, IpBlock], xbar: Dict[str, object]): """Amend crossbar informations to the top list Amended fields - clock: Adopt from module clock if exists - inst_type: Module instance some module will be hard-coded the tool searches module list and memory list then put here - base_addr: from top["module"] - size: from top["module"] """ xbar_list = [x["name"] for x in top["xbar"]] if not xbar["name"] in xbar_list: log.info( "Xbar %s doesn't belong to the top %s. Check if the xbar doesn't need" % (xbar["name"], top["name"])) return topxbar = list( filter(lambda node: node["name"] == xbar["name"], top["xbar"]))[0] topxbar["connections"] = deepcopy(xbar["connections"]) if "nodes" in xbar: topxbar["nodes"] = deepcopy(xbar["nodes"]) else: topxbar["nodes"] = [] # xbar primary clock and reset topxbar["clock"] = xbar["clock_primary"] topxbar["reset"] = xbar["reset_primary"] # Build nodes from 'connections' device_nodes = set() for host, devices in xbar["connections"].items(): # add host first xbar_addhost(top, topxbar, host) # add device if doesn't exist device_nodes.update(devices) other_xbars = [x["name"] for x in top["xbar"] if x["name"] != xbar["name"]] log.info(device_nodes) for device in device_nodes: xbar_adddevice(top, name_to_block, topxbar, other_xbars, device) def xbar_cross(xbar, xbars): """Check if cyclic dependency among xbars And gather the address range for device port (to another Xbar) @param node_name if not "", the function only search downstream devices starting from the node_name @param visited The nodes it visited to reach this port. If any downstream port from node_name in visited, it means circular path exists. It should be fatal error. """ # Step 1: Visit devices (gather the address range) log.info("Processing circular path check for {}".format(xbar["name"])) addr = [] for node in [ x for x in xbar["nodes"] if x["type"] == "device" and "xbar" in x and x["xbar"] is False ]: addr.extend(node["addr_range"]) # Step 2: visit xbar device ports xbar_nodes = [ x for x in xbar["nodes"] if x["type"] == "device" and "xbar" in x and x["xbar"] is True ] # Now call function to get the device range # the node["name"] is used to find the host_xbar and its connection. The # assumption here is that there's only one connection from crossbar A to # crossbar B. # # device_xbar is the crossbar has a device port with name as node["name"]. # host_xbar is the crossbar has a host port with name as node["name"]. for node in xbar_nodes: xbar_addr = xbar_cross_node(node["name"], xbar, xbars, visited=[]) node["addr_range"] = xbar_addr def xbar_cross_node(node_name, device_xbar, xbars, visited=[]): # 1. Get the connected xbar host_xbars = [x for x in xbars if x["name"] == node_name] assert len(host_xbars) == 1 host_xbar = host_xbars[0] log.info("Processing node {} in Xbar {}.".format(node_name, device_xbar["name"])) result = [] # [(base_addr, size), .. ] # Sweep the devices using connections and gather the address. # If the device is another xbar, call recursive visited.append(host_xbar["name"]) devices = host_xbar["connections"][device_xbar["name"]] for node in host_xbar["nodes"]: if not node["name"] in devices: continue if "xbar" in node and node["xbar"] is True: if "addr_range" not in node: # Deeper dive into another crossbar xbar_addr = xbar_cross_node(node["name"], host_xbar, xbars, visited) node["addr_range"] = xbar_addr result.extend(deepcopy(node["addr_range"])) visited.pop() return result # find the first instance name of a given type def _find_module_name(modules, module_type): for m in modules: if m['type'] == module_type: return m['name'] return None def amend_clocks(top: OrderedDict): """Add a list of clocks to each clock group Amend the clock connections of each entry to reflect the actual gated clock """ clks_attr = top['clocks'] clk_paths = clks_attr['hier_paths'] clkmgr_name = _find_module_name(top['module'], 'clkmgr') groups_in_top = [x["name"].lower() for x in clks_attr['groups']] exported_clks = OrderedDict() trans_eps = [] # Assign default parameters to source clocks for src in clks_attr['srcs']: if 'derived' not in src: src['derived'] = "no" src['params'] = OrderedDict() # Default assignments for group in clks_attr['groups']: # if unique not defined, it defaults to 'no' if 'unique' not in group: group['unique'] = "no" # if no hardwired clocks, define an empty set group['clocks'] = OrderedDict( ) if 'clocks' not in group else group['clocks'] for ep in top['module'] + top['memory'] + top['xbar']: clock_connections = OrderedDict() # Ensure each module has a default case export_if = ep.get('clock_reset_export', []) # if no clock group assigned, default is unique ep['clock_group'] = 'secure' if 'clock_group' not in ep else ep[ 'clock_group'] ep_grp = ep['clock_group'] # if ep is in the transactional group, collect into list below if ep['clock_group'] == 'trans': trans_eps.append(ep['name']) # end point names and clocks ep_name = ep['name'] ep_clks = [] # clock group index cg_idx = groups_in_top.index(ep_grp) # unique property of each group unique = clks_attr['groups'][cg_idx]['unique'] # src property of each group src = clks_attr['groups'][cg_idx]['src'] for port, clk in ep['clock_srcs'].items(): ep_clks.append(clk) name = '' hier_name = clk_paths[src] if src == 'ext': # clock comes from top ports if clk == 'main': name = "i" else: name = "{}_i".format(clk) elif unique == "yes": # new unqiue clock name name = "{}_{}".format(clk, ep_name) else: # new group clock name name = "{}_{}".format(clk, ep_grp) clk_name = "clk_" + name # add clock to a particular group clks_attr['groups'][cg_idx]['clocks'][clk_name] = clk # add clock connections clock_connections[port] = hier_name + clk_name # clocks for this module are exported for intf in export_if: log.info("{} export clock name is {}".format(ep_name, name)) # create dict entry if it does not exit if intf not in exported_clks: exported_clks[intf] = OrderedDict() # if first time encounter end point, declare if ep_name not in exported_clks[intf]: exported_clks[intf][ep_name] = [] # append clocks exported_clks[intf][ep_name].append(name) # Add to endpoint structure ep['clock_connections'] = clock_connections # add entry to top level json top['exported_clks'] = exported_clks # add entry to inter_module automatically for intf in top['exported_clks']: top['inter_module']['external']['{}.clocks_{}'.format( clkmgr_name, intf)] = "clks_{}".format(intf) # add to intermodule connections for ep in trans_eps: entry = ep + ".idle" top['inter_module']['connect']['{}.idle'.format(clkmgr_name)].append(entry) def amend_resets(top): """Generate exported reset structure and automatically connect to intermodule. """ rstmgr_name = _find_module_name(top['module'], 'rstmgr') # Generate exported reset list exported_rsts = OrderedDict() for module in top["module"]: # This code is here to ensure if amend_clocks/resets switched order # everything would still work export_if = module.get('clock_reset_export', []) # There may be multiple export interfaces for intf in export_if: # create dict entry if it does not exit if intf not in exported_rsts: exported_rsts[intf] = OrderedDict() # grab directly from reset_connections definition rsts = [rst for rst in module['reset_connections'].values()] exported_rsts[intf][module['name']] = rsts # add entry to top level json top['exported_rsts'] = exported_rsts # add entry to inter_module automatically for intf in top['exported_rsts']: top['inter_module']['external']['{}.resets_{}'.format( rstmgr_name, intf)] = "rsts_{}".format(intf) """Discover the full path and selection to each reset connection. This is done by modifying the reset connection of each end point. """ for end_point in top['module'] + top['memory'] + top['xbar']: for port, net in end_point['reset_connections'].items(): reset_path = lib.get_reset_path(net, end_point['domain'], top['resets']) end_point['reset_connections'][port] = reset_path # reset paths are still needed temporarily until host only modules are properly automated reset_paths = OrderedDict() reset_hiers = top["resets"]['hier_paths'] for reset in top["resets"]["nodes"]: if "type" not in reset: log.error("{} missing type field".format(reset["name"])) return if reset["type"] == "top": reset_paths[reset["name"]] = "{}rst_{}_n".format( reset_hiers["top"], reset["name"]) elif reset["type"] == "ext": reset_paths[reset["name"]] = reset_hiers["ext"] + reset['name'] elif reset["type"] == "int": log.info("{} used as internal reset".format(reset["name"])) else: log.error("{} type is invalid".format(reset["type"])) top["reset_paths"] = reset_paths return def ensure_interrupt_modules(top: OrderedDict, name_to_block: Dict[str, IpBlock]): '''Populate top['interrupt_module'] if necessary Do this by adding each module in top['modules'] that defines at least one interrupt. ''' if 'interrupt_module' in top: return modules = [] for module in top['module']: block = name_to_block[module['type']] if block.interrupts: modules.append(module['name']) top['interrupt_module'] = modules def amend_interrupt(top: OrderedDict, name_to_block: Dict[str, IpBlock]): """Check interrupt_module if exists, or just use all modules """ ensure_interrupt_modules(top, name_to_block) if "interrupt" not in top or top["interrupt"] == "": top["interrupt"] = [] for m in top["interrupt_module"]: ips = list(filter(lambda module: module["name"] == m, top["module"])) if len(ips) == 0: log.warning( "Cannot find IP %s which is used in the interrupt_module" % m) continue ip = ips[0] block = name_to_block[ip['type']] log.info("Adding interrupts from module %s" % ip["name"]) for signal in block.interrupts: sig_dict = signal.as_nwt_dict('interrupt') qual = lib.add_module_prefix_to_signal(sig_dict, module=m.lower()) top["interrupt"].append(qual) def ensure_alert_modules(top: OrderedDict, name_to_block: Dict[str, IpBlock]): '''Populate top['alert_module'] if necessary Do this by adding each module in top['modules'] that defines at least one alert. ''' if 'alert_module' in top: return modules = [] for module in top['module']: block = name_to_block[module['type']] if block.alerts: modules.append(module['name']) top['alert_module'] = modules def amend_alert(top: OrderedDict, name_to_block: Dict[str, IpBlock]): """Check interrupt_module if exists, or just use all modules """ ensure_alert_modules(top, name_to_block) if "alert" not in top or top["alert"] == "": top["alert"] = [] # Find the alert handler and extract the name of its clock alert_clock = None for instance in top['module']: if instance['type'].lower() == 'alert_handler': alert_clock = instance['clock_srcs']['clk_i'] break assert alert_clock is not None for m in top["alert_module"]: ips = list(filter(lambda module: module["name"] == m, top["module"])) if len(ips) == 0: log.warning("Cannot find IP %s which is used in the alert_module" % m) continue ip = ips[0] block = name_to_block[ip['type']] log.info("Adding alert from module %s" % ip["name"]) has_async_alerts = ip['clock_srcs']['clk_i'] != alert_clock for alert in block.alerts: alert_dict = alert.as_nwt_dict('alert') alert_dict['async'] = '1' if has_async_alerts else '0' qual_sig = lib.add_module_prefix_to_signal(alert_dict, module=m.lower()) top["alert"].append(qual_sig) def amend_wkup(topcfg: OrderedDict, name_to_block: Dict[str, IpBlock]): pwrmgr_name = _find_module_name(topcfg['module'], 'pwrmgr') if "wakeups" not in topcfg or topcfg["wakeups"] == "": topcfg["wakeups"] = [] # create list of wakeup signals for m in topcfg["module"]: log.info("Adding wakeup from module %s" % m["name"]) block = name_to_block[m['type']] for signal in block.wakeups: log.info("Adding signal %s" % signal.name) topcfg["wakeups"].append({ 'name': signal.name, 'width': str(signal.bits.width()), 'module': m["name"] }) # add wakeup signals to pwrmgr connections signal_names = [ "{}.{}".format(s["module"].lower(), s["name"].lower()) for s in topcfg["wakeups"] ] topcfg["inter_module"]["connect"]["{}.wakeups".format(pwrmgr_name)] = signal_names log.info("Intermodule signals: {}".format( topcfg["inter_module"]["connect"])) # Handle reset requests from modules def amend_reset_request(topcfg: OrderedDict, name_to_block: Dict[str, IpBlock]): pwrmgr_name = _find_module_name(topcfg['module'], 'pwrmgr') if "reset_requests" not in topcfg or topcfg["reset_requests"] == "": topcfg["reset_requests"] = [] # create list of reset signals for m in topcfg["module"]: log.info("Adding reset requests from module %s" % m["name"]) block = name_to_block[m['type']] for signal in block.reset_requests: log.info("Adding signal %s" % signal.name) topcfg["reset_requests"].append({ 'name': signal.name, 'width': str(signal.bits.width()), 'module': m["name"] }) # add reset requests to pwrmgr connections signal_names = [ "{}.{}".format(s["module"].lower(), s["name"].lower()) for s in topcfg["reset_requests"] ] topcfg["inter_module"]["connect"]["{}.rstreqs".format(pwrmgr_name)] = signal_names log.info("Intermodule signals: {}".format( topcfg["inter_module"]["connect"])) def append_io_signal(temp: Dict, sig_inst: Dict) -> None: '''Appends the signal to the correct list''' if sig_inst['type'] == 'inout': temp['inouts'].append(sig_inst) if sig_inst['type'] == 'input': temp['inputs'].append(sig_inst) if sig_inst['type'] == 'output': temp['outputs'].append(sig_inst) def get_index_and_incr(ctrs: Dict, connection: str, io_dir: str) -> Dict: '''Get correct index counter and increment''' if connection != 'muxed': connection = 'dedicated' if io_dir in 'inout': result = ctrs[connection]['inouts'] ctrs[connection]['inouts'] += 1 elif connection == 'muxed': # For MIOs, the input/output arrays differ in RTL # I.e., the input array contains {inputs, inouts}, whereas # the output array contains {outputs, inouts}. if io_dir == 'input': result = ctrs[connection]['inputs'] + ctrs[connection]['inouts'] ctrs[connection]['inputs'] += 1 elif io_dir == 'output': result = ctrs[connection]['outputs'] + ctrs[connection]['inouts'] ctrs[connection]['outputs'] += 1 else: assert(0) # should not happen else: # For DIOs, the input/output arrays are identical in terms of index layout. # Unused inputs are left unconnected and unused outputs are tied off. if io_dir == 'input': result = ctrs[connection]['inputs'] + ctrs[connection]['inouts'] ctrs[connection]['inputs'] += 1 elif io_dir == 'output': result = (ctrs[connection]['outputs'] + ctrs[connection]['inouts'] + ctrs[connection]['inputs']) ctrs[connection]['outputs'] += 1 else: assert(0) # should not happen return result def amend_pinmux_io(top: Dict, name_to_block: Dict[str, IpBlock]): """ Process pinmux/pinout configuration and assign available IOs """ pinmux = top['pinmux'] pinout = top['pinout'] targets = top['targets'] temp = {} temp['inouts'] = [] temp['inputs'] = [] temp['outputs'] = [] for sig in pinmux['signals']: # Get the signal information from the IP block type of this instance/ mod_name = sig['instance'] m = lib.get_module_by_name(top, mod_name) if m is None: raise SystemExit("Module {} is not searchable.".format(mod_name)) block = name_to_block[m['type']] # If the signal is explicitly named. if sig['port'] != '': # If this is a bus signal with explicit indexes. if '[' in sig['port']: name_split = sig['port'].split('[') sig_name = name_split[0] idx = int(name_split[1][:-1]) else: idx = -1 sig_name = sig['port'] sig_inst = deepcopy(block.get_signal_by_name_as_dict(sig_name)) if idx >= 0 and idx >= sig_inst['width']: raise SystemExit("Index {} is out of bounds for signal {}" " with width {}.".format(idx, sig_name, sig_inst['width'])) if idx == -1 and sig_inst['width'] != 1: raise SystemExit("Bus signal {} requires an index.".format(sig_name)) # If we got this far we know that the signal is valid and exists. # Augment this signal instance with additional information. sig_inst.update({'idx': idx, 'pad': sig['pad'], 'attr': sig['attr'], 'connection': sig['connection']}) sig_inst['name'] = mod_name + '_' + sig_inst['name'] append_io_signal(temp, sig_inst) # Otherwise the name is a wildcard for selecting all available IO signals # of this block and we need to extract them here one by one signals here. else: sig_list = deepcopy(block.get_signals_as_list_of_dicts()) for sig_inst in sig_list: # If this is a multibit signal, unroll the bus and # generate a single bit IO signal entry for each one. if sig_inst['width'] > 1: for idx in range(sig_inst['width']): sig_inst_copy = deepcopy(sig_inst) sig_inst_copy.update({'idx': idx, 'pad': sig['pad'], 'attr': sig['attr'], 'connection': sig['connection']}) sig_inst_copy['name'] = sig['instance'] + '_' + sig_inst_copy['name'] append_io_signal(temp, sig_inst_copy) else: sig_inst.update({'idx': -1, 'pad': sig['pad'], 'attr': sig['attr'], 'connection': sig['connection']}) sig_inst['name'] = sig['instance'] + '_' + sig_inst['name'] append_io_signal(temp, sig_inst) # Now that we've collected all input and output signals, # we can go through once again and stack them into one unified # list, and calculate MIO/DIO global indices. pinmux['ios'] = (temp['inouts'] + temp['inputs'] + temp['outputs']) # Remember these counts to facilitate the RTL generation pinmux['io_counts'] = {'dedicated': {'inouts': 0, 'inputs': 0, 'outputs': 0, 'pads': 0}, 'muxed': {'inouts': 0, 'inputs': 0, 'outputs': 0, 'pads': 0}} for sig in pinmux['ios']: glob_idx = get_index_and_incr(pinmux['io_counts'], sig['connection'], sig['type']) sig['glob_idx'] = glob_idx # Calculate global indices for pads. j = k = 0 for pad in pinout['pads']: if pad['connection'] == 'muxed': pad['idx'] = j j += 1 else: pad['idx'] = k k += 1 pinmux['io_counts']['muxed']['pads'] = j pinmux['io_counts']['dedicated']['pads'] = k # For each target configuration, calculate the special signal indices. known_muxed_pads = {} for pad in pinout['pads']: if pad['connection'] == 'muxed': known_muxed_pads[pad['name']] = pad known_mapped_dio_pads = {} for sig in pinmux['ios']: if sig['connection'] in ['muxed', 'manual']: continue if sig['pad'] in known_mapped_dio_pads: raise SystemExit('Cannot have multiple IOs mapped to the same DIO pad {}' .format(sig['pad'])) known_mapped_dio_pads[sig['pad']] = sig for target in targets: for entry in target['pinmux']['special_signals']: # If this is a muxed pad, the resolution is # straightforward. I.e., we just assign the MIO index. if entry['pad'] in known_muxed_pads: entry['idx'] = known_muxed_pads[entry['pad']]['idx'] # Otherwise we need to find out which DIO this pad is mapped to. # Note that we can't have special_signals that are manual, since # there needs to exist a DIO connection. elif entry['pad'] in known_mapped_dio_pads: # This index refers to the stacked {dio, mio} array # on the chip-level, hence we have to add the amount of MIO pads. idx = (known_mapped_dio_pads[entry['pad']]['glob_idx'] + pinmux['io_counts']['muxed']['pads']) entry['idx'] = idx else: assert(0) # Entry should be guaranteed to exist at this point def merge_top(topcfg: OrderedDict, name_to_block: Dict[str, IpBlock], xbarobjs: OrderedDict) -> OrderedDict: # Combine ip cfg into topcfg elaborate_instances(topcfg, name_to_block) # Create clock connections for each block # Assign clocks into appropriate groups # Note, elaborate_instances references clock information to establish async handling # as part of alerts. # amend_clocks(topcfg) # Combine the wakeups amend_wkup(topcfg, name_to_block) amend_reset_request(topcfg, name_to_block) # Combine the interrupt (should be processed prior to xbar) amend_interrupt(topcfg, name_to_block) # Combine the alert (should be processed prior to xbar) amend_alert(topcfg, name_to_block) # Creates input/output list in the pinmux log.info("Processing PINMUX") amend_pinmux_io(topcfg, name_to_block) # Combine xbar into topcfg for xbar in xbarobjs: amend_xbar(topcfg, name_to_block, xbar) # 2nd phase of xbar (gathering the devices address range) for xbar in topcfg["xbar"]: xbar_cross(xbar, topcfg["xbar"]) # Add path names to declared resets. # Declare structure for exported resets. amend_resets(topcfg) # remove unwanted fields 'debug_mem_base_addr' topcfg.pop('debug_mem_base_addr', None) return topcfg
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Code representing the entire chip for reggen''' from typing import Dict, List, Optional, Tuple, Union from reggen.ip_block import IpBlock from reggen.params import ReggenParams from reggen.reg_block import RegBlock from reggen.window import Window _IFName = Tuple[str, Optional[str]] _Triple = Tuple[int, str, IpBlock] class Top: '''An object representing the entire chip, as seen by reggen. This contains instances of some blocks (possibly multiple instances of each block), starting at well-defined base addresses. It may also contain some windows. These are memories that don't have their own comportable IP (so aren't defined in a block), but still take up address space. ''' def __init__(self, regwidth: int, blocks: Dict[str, IpBlock], instances: Dict[str, str], if_addrs: Dict[Tuple[str, Optional[str]], int], windows: List[Window], attrs: Dict[str, str]): '''Class initializer. regwidth is the width of the registers (which must match for all the blocks) in bits. blocks is a map from block name to IpBlock object. instances is a map from instance name to the name of the block it instantiates. Every block name that appears in instances must be a key of blocks. if_addrs is a dictionary that maps the name of a device interface on some instance of some block to its base address. A key of the form (n, i) means "the device interface called i on an instance called n". If i is None, this is an unnamed device interface. Every instance name (n) that appears in connections must be a key of instances. windows is a list of windows (these contain base addresses already). attrs is a map from instance name to attr field of the block ''' self.regwidth = regwidth self.blocks = blocks self.instances = instances self.if_addrs = if_addrs self.attrs = attrs self.window_block = RegBlock(regwidth, ReggenParams()) # Generate one list of base addresses and objects (with each object # either a block name and interface name or a window). While we're at # it, construct inst_to_block_name and if_addrs. merged = [] # type: List[Tuple[int, Union[_IFName, Window]]] for full_if_name, addr in if_addrs.items(): merged.append((addr, full_if_name)) inst_name, if_name = full_if_name # The instance name must match some key in instances, whose value # should in turn match some key in blocks. assert inst_name in instances block_name = instances[inst_name] assert block_name in blocks # Check that if_name is indeed the name of a device interface for # that block. block = blocks[block_name] assert block.bus_interfaces.has_interface(False, if_name) for window in sorted(windows, key=lambda w: w.offset): merged.append((window.offset, window)) self.window_block.add_window(window) # A map from block name to the list of its instances. These instances # are listed in increasing order of the lowest base address of one of # their interfaces. The entries are added into the dict in the same # order, so an iteration over items() will give blocks ordered by their # first occurrence in the address map. self.block_instances = {} # type: Dict[str, List[str]] # Walk the merged list in order of increasing base address. Check for # overlaps and construct block_instances. offset = 0 for base_addr, item in sorted(merged, key=lambda pr: pr[0]): # Make sure that this item doesn't overlap with the previous one assert offset <= base_addr, item if isinstance(item, Window): addrsep = (regwidth + 7) // 8 offset = item.next_offset(addrsep) continue inst_name, if_name = item block_name = instances[inst_name] block = blocks[block_name] lst = self.block_instances.setdefault(block_name, []) if inst_name not in lst: lst.append(inst_name) # This should be guaranteed by the fact that we've already checked # the existence of a device interface. assert if_name in block.reg_blocks reg_block = block.reg_blocks[if_name] offset = base_addr + reg_block.offset
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // UVM registers auto-generated by `reggen` containing UVM definitions for the entire top-level <%! from topgen.gen_dv import sv_base_addr from reggen.gen_dv import bcname, mcname, miname %> ## ## This template is used for chip-wide tests. It expects to be run with the ## following arguments ## ## top a Top object ## ## dv_base_prefix a string for the base register type. If it is FOO, then ## we will inherit from FOO_reg (assumed to be a subclass ## of uvm_reg). ## ## Like uvm_reg.sv.tpl, we use functions from uvm_reg_base.sv.tpl to define ## per-device-interface code. ## <%namespace file="uvm_reg_base.sv.tpl" import="*"/>\ ## ## ## Waive the package-filename check: we're going to be defining all sorts of ## packages in a single file. // verilog_lint: waive-start package-filename ## ## Iterate over the device interfaces of blocks in Top, constructing a package ## for each. Sorting items like this guarantees we'll work alphabetically in ## block name. % for block_name, block in sorted(top.blocks.items()): % for if_name, rb in block.reg_blocks.items(): <% if_suffix = '' if if_name is None else '_' + if_name esc_if_name = block_name.lower() + if_suffix if_desc = '' if if_name is None else '; interface {}'.format(if_name) reg_block_path = 'u_reg' + if_suffix reg_block_path = reg_block_path if block.hier_path is None else block.hier_path + "." + reg_block_path %>\ // Block: ${block_name.lower()}${if_desc} ${make_ral_pkg(dv_base_prefix, top.regwidth, reg_block_path, rb, esc_if_name)} % endfor % endfor ## ## ## Now that we've made the block-level packages, re-instate the ## package-filename check. The only package left is chip_ral_pkg, which should ## match the generated filename. // verilog_lint: waive-start package-filename // Block: chip package chip_ral_pkg; <% if_packages = [] for block_name, block in sorted(top.blocks.items()): for if_name in block.reg_blocks: if_suffix = '' if if_name is None else '_' + if_name if_packages.append('{}{}_ral_pkg'.format(block_name.lower(), if_suffix)) windows = top.window_block.windows %>\ ${make_ral_pkg_hdr(dv_base_prefix, if_packages)} ${make_ral_pkg_fwd_decls('chip', [], windows)} % for window in windows: ${make_ral_pkg_window_class(dv_base_prefix, 'chip', window)} % endfor class chip_reg_block extends ${dv_base_prefix}_reg_block; // sub blocks % for block_name, block in sorted(top.blocks.items()): % for inst_name in top.block_instances[block_name.lower()]: % for if_name, rb in block.reg_blocks.items(): <% if_suffix = '' if if_name is None else '_' + if_name esc_if_name = block_name.lower() + if_suffix if_inst = inst_name + if_suffix %>\ rand ${bcname(esc_if_name)} ${if_inst}; % endfor % endfor % endfor % if windows: // memories % for window in windows: rand ${mcname('chip', window)} ${miname(window)}; % endfor % endif `uvm_object_utils(chip_reg_block) function new(string name = "chip_reg_block", int has_coverage = UVM_NO_COVERAGE); super.new(name, has_coverage); endfunction : new virtual function void build(uvm_reg_addr_t base_addr, csr_excl_item csr_excl = null); // create default map this.default_map = create_map(.name("default_map"), .base_addr(base_addr), .n_bytes(${top.regwidth//8}), .endian(UVM_LITTLE_ENDIAN)); if (csr_excl == null) begin csr_excl = csr_excl_item::type_id::create("csr_excl"); this.csr_excl = csr_excl; end // create sub blocks and add their maps % for block_name, block in sorted(top.blocks.items()): % for inst_name in top.block_instances[block_name.lower()]: % for if_name, rb in block.reg_blocks.items(): <% if_suffix = '' if if_name is None else '_' + if_name esc_if_name = block_name.lower() + if_suffix if_inst = inst_name + if_suffix if top.attrs.get(inst_name) == 'reggen_only': hdl_path = 'tb.dut.u_' + inst_name else: hdl_path = 'tb.dut.top_earlgrey.u_' + inst_name qual_if_name = (inst_name, if_name) base_addr = top.if_addrs[qual_if_name] base_addr_txt = sv_base_addr(top, qual_if_name) hpr_indent = (len(if_inst) + len('.set_hdl_path_root(')) * ' ' %>\ ${if_inst} = ${bcname(esc_if_name)}::type_id::create("${if_inst}"); ${if_inst}.configure(.parent(this)); ${if_inst}.build(.base_addr(base_addr + ${base_addr_txt}), .csr_excl(csr_excl)); ${if_inst}.set_hdl_path_root("${hdl_path}", ${hpr_indent}"BkdrRegPathRtl"); ${if_inst}.set_hdl_path_root("${hdl_path}", ${hpr_indent}"BkdrRegPathRtlCommitted"); ${if_inst}.set_hdl_path_root("${hdl_path}", ${hpr_indent}"BkdrRegPathRtlShadow"); default_map.add_submap(.child_map(${if_inst}.default_map), .offset(base_addr + ${base_addr_txt})); % endfor % endfor % endfor ${make_ral_pkg_window_instances(top.regwidth, 'chip', top.window_block)} endfunction : build endclass : chip_reg_block endpackage
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import re import logging as log from collections import OrderedDict from enum import Enum from typing import Dict, List from reggen.validate import check_keys from reggen.ip_block import IpBlock # For the reference # val_types = { # 'd': ["int", "integer (binary 0b, octal 0o, decimal, hex 0x)"], # 'x': ["xint", "x for undefined otherwise int"], # 'b': [ # "bitrange", "bit number as decimal integer, \ # or bit-range as decimal integers msb:lsb" # ], # 'l': ["list", "comma separated list enclosed in `[]`"], # 'ln': ["name list", 'comma separated list enclosed in `[]` of '\ # 'one or more groups that have just name and dscr keys.'\ # ' e.g. `{ name: "name", desc: "description"}`'], # 'lnw': ["name list+", 'name list that optionally contains a width'], # 'lp': ["parameter list", 'parameter list having default value optionally'], # 'g': ["group", "comma separated group of key:value enclosed in `{}`"], # 's': ["string", "string, typically short"], # 't': ["text", "string, may be multi-line enclosed in `'''` "\ # "may use `**bold**`, `*italic*` or `!!Reg` markup"], # 'T': ["tuple", "tuple enclosed in ()"], # 'pi': ["python int", "Native Python type int (generated)"], # 'pb': ["python Bool", "Native Python type Bool (generated)"], # 'pl': ["python list", "Native Python type list (generated)"], # 'pe': ["python enum", "Native Python type enum (generated)"] # } # Required/optional field in top hjson top_required = { 'name': ['s', 'Top name'], 'type': ['s', 'type of hjson. Shall be "top" always'], 'clocks': ['g', 'group of clock properties'], 'resets': ['l', 'list of resets'], 'module': ['l', 'list of modules to instantiate'], 'memory': ['l', 'list of memories. At least one memory ' 'is needed to run the software'], 'debug_mem_base_addr': ['d', 'Base address of RV_DM. ' 'Planned to move to module'], 'xbar': ['l', 'List of the xbar used in the top'], 'rnd_cnst_seed': ['int', "Seed for random netlist constant computation"], 'pinout': ['g', 'Pinout configuration'], 'targets': ['l', ' Target configurations'], 'pinmux': ['g', 'pinmux configuration'], } top_optional = { 'alert_async': ['l', 'async alerts (generated)'], 'alert': ['lnw', 'alerts (generated)'], 'alert_module': [ 'l', 'list of the modules that connects to alert_handler' ], 'datawidth': ['pn', "default data width"], 'exported_clks': ['g', 'clock signal routing rules'], 'host': ['g', 'list of host-only components in the system'], 'inter_module': ['g', 'define the signal connections between the modules'], 'interrupt': ['lnw', 'interrupts (generated)'], 'interrupt_module': ['l', 'list of the modules that connects to rv_plic'], 'num_cores': ['pn', "number of computing units"], 'power': ['g', 'power domains supported by the design'], 'port': ['g', 'assign special attributes to specific ports'] } top_added = {} pinmux_required = {} pinmux_optional = { 'num_wkup_detect': [ 'd', 'Number of wakeup detectors' ], 'wkup_cnt_width': [ 'd', 'Number of bits in wakeup detector counters' ], 'signals': ['l', 'List of Dedicated IOs.'], } pinmux_added = { 'ios': ['l', 'Full list of IO'], } pinmux_sig_required = { 'instance': ['s', 'Module instance name'], 'connection': ['s', 'Specification of connection type, ' 'can be direct, manual or muxed'], } pinmux_sig_optional = { 'port': ['s', 'Port name of module'], 'pad': ['s', 'Pad name for direct connections'], 'desc': ['s', 'Signal description'], 'attr': ['s', 'Pad type for generating the correct attribute CSR'] } pinmux_sig_added = {} pinout_required = { 'banks': ['l', 'List of IO power banks'], 'pads': ['l', 'List of pads'] } pinout_optional = { } pinout_added = {} pad_required = { 'name': ['l', 'Pad name'], 'type': ['s', 'Pad type'], 'bank': ['s', 'IO power bank for the pad'], 'connection': ['s', 'Specification of connection type, ' 'can be direct, manual or muxed'], } pad_optional = { 'desc': ['s', 'Pad description'], } pad_added = {} target_required = { 'name': ['s', 'Name of target'], 'pinout': ['g', 'Target-specific pinout configuration'], 'pinmux': ['g', 'Target-specific pinmux configuration'] } target_optional = { } target_added = {} target_pinmux_required = { 'special_signals': ['l', 'List of special signals and the pad they are mapped to.'], } target_pinmux_optional = {} target_pinmux_added = {} target_pinout_required = { 'remove_pads': ['l', 'List of pad names to remove and stub out'], 'add_pads': ['l', 'List of manual pads to add'], } target_pinout_optional = {} target_pinout_added = {} straps_required = { 'tap0': ['s', 'Name of tap0 pad'], 'tap1': ['s', 'Name of tap1 pad'], 'dft0': ['s', 'Name of dft0 pad'], 'dft1': ['s', 'Name of dft1 pad'], } straps_optional = {} straps_added = {} straps_required = { 'tap0': ['s', 'Name of tap0 pad'], 'tap1': ['s', 'Name of tap1 pad'], 'dft0': ['s', 'Name of dft0 pad'], 'dft1': ['s', 'Name of dft1 pad'], } straps_optional = {} straps_added = {} special_sig_required = { 'name': ['s', 'DIO name'], 'pad': ['s', 'Pad name'], } special_sig_optional = { 'desc': ['s', 'Description of signal connection'], } special_sig_added = {} clock_srcs_required = { 'name': ['s', 'name of clock group'], 'aon': ['s', 'yes, no. aon attribute of a clock'], 'freq': ['s', 'frequency of clock in Hz'], } clock_srcs_optional = { 'derived': ['s', 'whether clock is derived'], 'params': ['s', 'extra clock parameters'] } derived_clock_srcs_required = { 'name': ['s', 'name of clock group'], 'aon': ['s', 'yes, no. aon attribute of a clock'], 'freq': ['s', 'frequency of clock in Hz'], 'src': ['s', 'source clock'], 'div': ['d', 'ratio between source clock and derived clock'], } clock_groups_required = { 'name': ['s', 'name of clock group'], 'src': ['s', 'yes, no. This clock group is directly from source'], 'sw_cg': ['s', 'yes, no, hint. Software clock gate attributes'], } clock_groups_optional = { 'unique': ['s', 'whether clocks in the group are unique'], 'clocks': ['g', 'groups of clock name to source'], } clock_groups_added = {} eflash_required = { 'banks': ['d', 'number of flash banks'], 'base_addr': ['s', 'strarting hex address of memory'], 'clock_connections': ['g', 'generated, elaborated version of clock_srcs'], 'clock_group': ['s', 'associated clock attribute group'], 'clock_srcs': ['g', 'clock connections'], 'inter_signal_list': ['lg', 'intersignal list'], 'name': ['s', 'name of flash memory'], 'pages_per_bank': ['d', 'number of data pages per flash bank'], 'program_resolution': ['d', 'maximum number of flash words allowed to program'], 'reset_connections': ['g', 'reset connections'], 'swaccess': ['s', 'software accessibility'], 'type': ['s', 'type of memory'] } eflash_optional = {} eflash_added = {} # Supported PAD types. # Needs to coincide with enum definition in prim_pad_wrapper_pkg.sv class PadType(Enum): INPUT_STD = 'InputStd' BIDIR_STD = 'BidirStd' BIDIR_TOL = 'BidirTol' BIDIR_OD = 'BidirOd' ANALOG_IN0 = 'AnalogIn0' def is_valid_pad_type(obj): try: PadType(obj) except ValueError: return False return True class TargetType(Enum): MODULE = "module" XBAR = "xbar" class Target: """Target class informs the checkers if we are validating a module or xbar """ def __init__(self, target_type): # The type of this target self.target_type = target_type # The key to search against if target_type == TargetType.MODULE: self.key = "type" else: self.key = "name" class Flash: """Flash class contains information regarding parameter defaults. For now, only expose banks / pages_per_bank for user configuration. For now, also enforce power of 2 requiremnt. """ max_banks = 4 max_pages_per_bank = 1024 def __init__(self, mem): self.banks = mem['banks'] self.pages_per_bank = mem['pages_per_bank'] self.program_resolution = mem['program_resolution'] self.words_per_page = 256 self.data_width = 64 self.metadata_width = 12 self.info_types = 3 self.infos_per_bank = [10, 1, 2] def is_pow2(self, n): return (n != 0) and (n & (n - 1) == 0) def check_values(self): pow2_check = (self.is_pow2(self.banks) and self.is_pow2(self.pages_per_bank) and self.is_pow2(self.program_resolution)) limit_check = ((self.banks <= Flash.max_banks) and (self.pages_per_bank <= Flash.max_pages_per_bank)) return pow2_check and limit_check def calc_size(self): word_bytes = self.data_width / 8 bytes_per_page = word_bytes * self.words_per_page bytes_per_bank = bytes_per_page * self.pages_per_bank return bytes_per_bank * self.banks def populate(self, mem): mem['words_per_page'] = self.words_per_page mem['data_width'] = self.data_width mem['metadata_width'] = self.metadata_width mem['info_types'] = self.info_types mem['infos_per_bank'] = self.infos_per_bank mem['size'] = hex(int(self.calc_size())) word_bytes = self.data_width / 8 mem['pgm_resolution_bytes'] = int(self.program_resolution * word_bytes) # Check to see if each module/xbar defined in top.hjson exists as ip/xbar.hjson # Also check to make sure there are not multiple definitions of ip/xbar.hjson for each # top level definition # If it does, return a dictionary of instance names to index in ip/xbarobjs def check_target(top, objs, tgtobj): error = 0 idxs = OrderedDict() # Collect up counts of object names. We support entries of objs that are # either dicts (for top-levels) or IpBlock objects. name_indices = {} for idx, obj in enumerate(objs): if isinstance(obj, IpBlock): name = obj.name.lower() else: name = obj['name'].lower() log.info("%d Order is %s" % (idx, name)) name_indices.setdefault(name, []).append(idx) tgt_type = tgtobj.target_type.value inst_key = tgtobj.key for cfg in top[tgt_type]: cfg_name = cfg['name'].lower() log.info("Checking target %s %s" % (tgt_type, cfg_name)) indices = name_indices.get(cfg[inst_key], []) if not indices: log.error("Could not find %s.hjson" % cfg_name) error += 1 elif len(indices) > 1: log.error("Duplicate %s.hjson" % cfg_name) error += 1 else: idxs[cfg_name] = indices[0] log.info("Current state %s" % idxs) return error, idxs def check_pad(top: Dict, pad: Dict, known_pad_names: Dict, valid_connections: List[str], prefix: str) -> int: error = 0 error += check_keys(pad, pad_required, pad_optional, pad_added, prefix) # check name uniqueness if pad['name'] in known_pad_names: log.warning('Pad name {} is not unique'.format(pad['name'])) error += 1 known_pad_names[pad['name']] = 1 if not is_valid_pad_type(pad['type']): log.warning('Unkown pad type {}'.format(pad['type'])) error += 1 if pad['bank'] not in top['pinout']['banks']: log.warning('Unkown io power bank {}'.format(pad['bank'])) error += 1 if pad['connection'] not in valid_connections: log.warning('Connection type {} of pad {} is invalid' .format(pad['connection'], pad['name'])) error += 1 return error def check_pinout(top: Dict, prefix: str) -> int: error = check_keys(top['pinout'], pinout_required, pinout_optional, pinout_added, prefix + ' Pinout') known_names = {} for pad in top['pinout']['pads']: error += check_keys(pad, pad_required, pad_optional, pad_added, prefix + ' Pinout') error += check_pad(top, pad, known_names, ['direct', 'manual', 'muxed'], prefix + ' Pad') return error def check_pinmux(top: Dict, prefix: str) -> int: error = check_keys(top['pinmux'], pinmux_required, pinmux_optional, pinmux_added, prefix + ' Pinmux') # This is used for the direct connection accounting below, # where we tick off already connected direct pads. known_direct_pads = {} direct_pad_attr = {} for pad in top['pinout']['pads']: if pad['connection'] == 'direct': known_direct_pads[pad['name']] = 1 direct_pad_attr[pad['name']] = pad['type'] # Note: the actual signal crosscheck is deferred until the merge stage, # since we have no idea at this point which IOs comportable IPs expose. for sig in top['pinmux']['signals']: error += check_keys(sig, pinmux_sig_required, pinmux_sig_optional, pinmux_sig_added, prefix + ' Pinmux signal') if sig['connection'] not in ['direct', 'manual', 'muxed']: log.warning('Invalid connection type {}'.format(sig['connection'])) error += 1 # The pad needs to refer to a valid pad name in the pinout that is of # connection type "direct". We tick off all direct pads that have been # referenced in order to make sure there are no double connections # and unconnected direct pads. padname = sig.setdefault('pad', '') if padname != '': if padname in known_direct_pads: if known_direct_pads[padname] == 1: known_direct_pads[padname] = 0 padattr = direct_pad_attr[padname] else: log.warning('Warning, direct pad {} is already connected' .format(padname)) error += 1 else: log.warning('Unknown direct pad {}'.format(padname)) error += 1 # Check port naming scheme. port = sig.setdefault('port', '') pattern = r'^[a-zA-Z0-9_]*(\[[0-9]*\]){0,1}' matches = re.match(pattern, port) if matches is None: log.warning('Port name {} has wrong format' .format(port)) error += 1 # Check that only direct connections have pad keys if sig['connection'] == 'direct': if sig.setdefault('attr', '') != '': log.warning('Direct connection of instance {} port {} ' 'must not have an associated pad attribute field' .format(sig['instance'], sig['port'])) error += 1 # Since the signal is directly connected, we can automatically infer # the pad type needed to instantiate the correct attribute CSR WARL # module inside the pinmux. sig['attr'] = padattr if padname == '': log.warning('Instance {} port {} connection is of direct type ' 'and therefore must have an associated pad name.' .format(sig['instance'], sig['port'])) error += 1 if port == '': log.warning('Instance {} port {} connection is of direct type ' 'and therefore must have an associated port name.' .format(sig['instance'], sig['port'])) error += 1 elif sig['connection'] == 'muxed': # Muxed signals do not have a corresponding pad and attribute CSR, # since they first go through the pinmux matrix. if sig.setdefault('attr', '') != '': log.warning('Muxed connection of instance {} port {} ' 'must not have an associated pad attribute field' .format(sig['instance'], sig['port'])) error += 1 if padname != '': log.warning('Muxed connection of instance {} port {} ' 'must not have an associated pad' .format(sig['instance'], sig['port'])) error += 1 elif sig['connection'] == 'manual': # This pad attr key is only allowed in the manual case, # as there is no way to infer the pad type automatically. sig.setdefault('attr', 'BidirStd') if padname != '': log.warning('Manual connection of instance {} port {} ' 'must not have an associated pad' .format(sig['instance'], sig['port'])) error += 1 # At this point, all direct pads should have been ticked off. for key, val in known_direct_pads.items(): if val == 1: log.warning('Direct pad {} has not been connected' .format(key)) error += 1 return error def check_implementation_targets(top: Dict, prefix: str) -> int: error = 0 known_names = {} for target in top['targets']: error += check_keys(target, target_required, target_optional, target_added, prefix + ' Targets') # check name uniqueness if target['name'] in known_names: log.warning('Target name {} is not unique'.format(target['name'])) error += 1 known_names[target['name']] = 1 error += check_keys(target['pinmux'], target_pinmux_required, target_pinmux_optional, target_pinmux_added, prefix + ' Target pinmux') error += check_keys(target['pinout'], target_pinout_required, target_pinout_optional, target_pinout_added, prefix + ' Target pinout') # Check special pad signals known_entry_names = {} for entry in target['pinmux']['special_signals']: error += check_keys(entry, special_sig_required, special_sig_optional, special_sig_added, prefix + ' Special signal') # check name uniqueness if entry['name'] in known_entry_names: log.warning('Special pad name {} is not unique'.format(entry['name'])) error += 1 known_entry_names[entry['name']] = 1 # The pad key needs to refer to a valid pad name. is_muxed = False for pad in top['pinout']['pads']: if entry['pad'] == pad['name']: is_muxed = pad['connection'] == 'muxed' break else: log.warning('Unknown pad {}'.format(entry['pad'])) error += 1 if not is_muxed: # If this is not a muxed pad, we need to make sure this refers to # DIO that is NOT a manual pad. for sig in top['pinmux']['signals']: if entry['pad'] == sig['pad']: break else: log.warning('Special pad {} cannot refer to a manual pad'.format(entry['pad'])) error += 1 # Check pads to remove and stub out for entry in target['pinout']['remove_pads']: # The pad key needs to refer to a valid pad name. for pad in top['pinout']['pads']: if entry == pad['name']: break else: log.warning('Unknown pad {}'.format(entry)) error += 1 # Check pads to add known_pad_names = {} for pad in top['pinout']['pads']: known_pad_names.update({pad['name']: 1}) for pad in target['pinout']['add_pads']: error += check_pad(top, pad, known_pad_names, ['manual'], prefix + ' Additional Pad') return error # check for inconsistent clock group definitions def check_clock_groups(top): # default empty assignment if "groups" not in top['clocks']: top['clocks']['groups'] = [] error = 0 for group in top['clocks']['groups']: error = check_keys(group, clock_groups_required, clock_groups_optional, clock_groups_added, "Clock Groups") # Check sw_cg values are valid if group['sw_cg'] not in ['yes', 'no', 'hint']: log.error("Incorrect attribute for sw_cg: {}".format( group['sw_cg'])) error += 1 # Check combination of src and sw are valid if group['src'] == 'yes' and group['sw_cg'] != 'no': log.error("Invalid combination of src and sw_cg: {} and {}".format( group['src'], group['sw_cg'])) error += 1 # Check combination of sw_cg and unique are valid unique = group['unique'] if 'unique' in group else 'no' if group['sw_cg'] == 'no' and unique != 'no': log.error( "Incorrect attribute combination. When sw_cg is no, unique must be no" ) error += 1 if error: break return error def check_clocks_resets(top, ipobjs, ip_idxs, xbarobjs, xbar_idxs): error = 0 # there should only be one each of pwrmgr/clkmgr/rstmgr pwrmgrs = [m for m in top['module'] if m['type'] == 'pwrmgr'] clkmgrs = [m for m in top['module'] if m['type'] == 'clkmgr'] rstmgrs = [m for m in top['module'] if m['type'] == 'rstmgr'] if len(pwrmgrs) == 1 * len(clkmgrs) == 1 * len(rstmgrs) != 1: log.error("Incorrect number of pwrmgr/clkmgr/rstmgr") error += 1 # check clock fields are all there ext_srcs = [] for src in top['clocks']['srcs']: check_keys(src, clock_srcs_required, clock_srcs_optional, {}, "Clock source") ext_srcs.append(src['name']) # check derived clock sources log.info("Collected clocks are {}".format(ext_srcs)) for src in top['clocks']['derived_srcs']: check_keys(src, derived_clock_srcs_required, {}, {}, "Derived clocks") try: ext_srcs.index(src['src']) except Exception: error += 1 log.error("{} is not a valid src for {}".format( src['src'], src['name'])) # all defined clock/reset nets reset_nets = [reset['name'] for reset in top['resets']['nodes']] clock_srcs = [ clock['name'] for clock in top['clocks']['srcs'] + top['clocks']['derived_srcs'] ] # Check clock/reset port connection for all IPs for ipcfg in top['module']: ipcfg_name = ipcfg['name'].lower() log.info("Checking clock/resets for %s" % ipcfg_name) error += validate_reset(ipcfg, ipobjs[ip_idxs[ipcfg_name]], reset_nets) error += validate_clock(ipcfg, ipobjs[ip_idxs[ipcfg_name]], clock_srcs) if error: log.error("module clock/reset checking failed") break # Check clock/reset port connection for all xbars for xbarcfg in top['xbar']: xbarcfg_name = xbarcfg['name'].lower() log.info("Checking clock/resets for xbar %s" % xbarcfg_name) error += validate_reset(xbarcfg, xbarobjs[xbar_idxs[xbarcfg_name]], reset_nets, "xbar") error += validate_clock(xbarcfg, xbarobjs[xbar_idxs[xbarcfg_name]], clock_srcs, "xbar") if error: log.error("xbar clock/reset checking failed") break return error # Checks the following # For each defined reset connection in top*.hjson, there exists a defined port at the destination # and defined reset net # There are the same number of defined connections as there are ports def validate_reset(top, inst, reset_nets, prefix=""): # Gather inst port list error = 0 # Handle either an IpBlock (generated by reggen) or an OrderedDict # (generated by topgen for a crossbar) if isinstance(inst, IpBlock): name = inst.name reset_signals = inst.reset_signals else: name = inst['name'] reset_signals = ([inst.get('reset_primary', 'rst_ni')] + inst.get('other_reset_list', [])) log.info("%s %s resets are %s" % (prefix, name, reset_signals)) if len(top['reset_connections']) != len(reset_signals): error += 1 log.error("%s %s mismatched number of reset ports and nets" % (prefix, name)) missing_port = [ port for port in top['reset_connections'].keys() if port not in reset_signals ] if missing_port: error += 1 log.error("%s %s Following reset ports do not exist:" % (prefix, name)) [log.error("%s" % port) for port in missing_port] missing_net = [ net for port, net in top['reset_connections'].items() if net not in reset_nets ] if missing_net: error += 1 log.error("%s %s Following reset nets do not exist:" % (prefix, name)) [log.error("%s" % net) for net in missing_net] return error # Checks the following # For each defined clock_src in top*.hjson, there exists a defined port at the destination # and defined clock source # There are the same number of defined connections as there are ports def validate_clock(top, inst, clock_srcs, prefix=""): # Gather inst port list error = 0 # Handle either an IpBlock (generated by reggen) or an OrderedDict # (generated by topgen for a crossbar) if isinstance(inst, IpBlock): name = inst.name clock_signals = inst.clock_signals else: name = inst['name'] clock_signals = ([inst.get('clock_primary', 'rst_ni')] + inst.get('other_clock_list', [])) if len(top['clock_srcs']) != len(clock_signals): error += 1 log.error("%s %s mismatched number of clock ports and nets" % (prefix, name)) missing_port = [ port for port in top['clock_srcs'].keys() if port not in clock_signals ] if missing_port: error += 1 log.error("%s %s Following clock ports do not exist:" % (prefix, name)) [log.error("%s" % port) for port in missing_port] missing_net = [ net for port, net in top['clock_srcs'].items() if net not in clock_srcs ] if missing_net: error += 1 log.error("%s %s Following clock nets do not exist:" % (prefix, name)) [log.error("%s" % net) for net in missing_net] return error def check_flash(top): error = 0 for mem in top['memory']: if mem['type'] == "eflash": error = check_keys(mem, eflash_required, eflash_optional, eflash_added, "Eflash") flash = Flash(mem) error += 1 if not flash.check_values() else 0 if error: log.error("Flash check failed") else: flash.populate(mem) return error def check_power_domains(top): error = 0 # check that the default domain is valid if top['power']['default'] not in top['power']['domains']: error += 1 return error # check that power domain definition is consistent with reset and module definition for reset in top['resets']['nodes']: if reset['gen']: if 'domains' not in reset: log.error("{} missing domain definition".format(reset['name'])) error += 1 return error else: for domain in reset['domains']: if domain not in top['power']['domains']: log.error("{} defined invalid domain {}".format( reset['name'], domain)) error += 1 return error # Check that each module, xbar, memory has a power domain defined. # If not, give it a default. # If there is one defined, check that it is a valid definition for end_point in top['module'] + top['memory'] + top['xbar']: if 'domain' not in end_point: end_point['domain'] = top['power']['default'] if end_point['domain'] not in top['power']['domains']: log.error("{} defined invalid domain {}" .format(end_point['name'], end_point['domain'])) error += 1 return error # arrived without incident, return return error def validate_top(top, ipobjs, xbarobjs): # return as it is for now error = check_keys(top, top_required, top_optional, top_added, "top") if error != 0: log.error("Top HJSON has top level errors. Aborting") return top, error component = top['name'] # MODULE check err, ip_idxs = check_target(top, ipobjs, Target(TargetType.MODULE)) error += err # XBAR check err, xbar_idxs = check_target(top, xbarobjs, Target(TargetType.XBAR)) error += err # MEMORY check error += check_flash(top) # Power domain check error += check_power_domains(top) # Clock / Reset check error += check_clocks_resets(top, ipobjs, ip_idxs, xbarobjs, xbar_idxs) # Clock group check error += check_clock_groups(top) # RV_PLIC check # Pinout, pinmux and target checks # Note that these checks must happen in this order, as # the pinmux and target configs depend on the pinout. error += check_pinout(top, component) error += check_pinmux(top, component) error += check_implementation_targets(top, component) return top, error
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from .lib import get_hjsonobj_xbars, search_ips # noqa: F401 # noqa: F401 These functions are used in topgen.py from .merge import amend_clocks, merge_top # noqa: F401 from .validate import validate_top, check_flash # noqa: F401
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 ${gencmd} <% import re import topgen.lib as lib from copy import deepcopy # Provide shortcuts for some commonly used variables pinmux = top['pinmux'] pinout = top['pinout'] num_mio_inputs = pinmux['io_counts']['muxed']['inouts'] + \ pinmux['io_counts']['muxed']['inputs'] num_mio_outputs = pinmux['io_counts']['muxed']['inouts'] + \ pinmux['io_counts']['muxed']['outputs'] num_mio_pads = pinmux['io_counts']['muxed']['pads'] num_dio_inputs = pinmux['io_counts']['dedicated']['inouts'] + \ pinmux['io_counts']['dedicated']['inputs'] num_dio_outputs = pinmux['io_counts']['dedicated']['inouts'] + \ pinmux['io_counts']['dedicated']['outputs'] num_dio_total = pinmux['io_counts']['dedicated']['inouts'] + \ pinmux['io_counts']['dedicated']['inputs'] + \ pinmux['io_counts']['dedicated']['outputs'] def get_dio_sig(pinmux: {}, pad: {}): '''Get DIO signal associated with this pad or return None''' for sig in pinmux["ios"]: if sig["connection"] == "direct" and pad["name"] == sig["pad"]: return sig else: return None # Modify the pad lists on the fly, based on target config maxwidth = 0 muxed_pads = [] dedicated_pads = [] k = 0 for pad in pinout["pads"]: if pad["connection"] == "muxed": if pad["name"] not in target["pinout"]["remove_pads"]: maxwidth = max(maxwidth, len(pad["name"])) muxed_pads.append(pad) else: k = pad["idx"] if pad["name"] not in target["pinout"]["remove_pads"]: maxwidth = max(maxwidth, len(pad["name"])) dedicated_pads.append(pad) for pad in target["pinout"]["add_pads"]: # Since these additional pads have not been elaborated in the merge phase, # we need to add their global index here. amended_pad = deepcopy(pad) amended_pad.update({"idx" : k}) dedicated_pads.append(pad) k += 1 num_im = sum([x["width"] if "width" in x else 1 for x in top["inter_signal"]["external"]]) max_sigwidth = max([x["width"] if "width" in x else 1 for x in top["pinmux"]["ios"]]) max_sigwidth = len("{}".format(max_sigwidth)) clks_attr = top['clocks'] cpu_clk = top['clocks']['hier_paths']['top'] + "clk_proc_main" cpu_rst = top["reset_paths"]["sys"] dm_rst = top["reset_paths"]["lc"] esc_clk = top['clocks']['hier_paths']['top'] + "clk_io_div4_timers" esc_rst = top["reset_paths"]["sys_io_div4"] unused_resets = lib.get_unused_resets(top) unused_im_defs, undriven_im_defs = lib.get_dangling_im_def(top["inter_signal"]["definitions"]) %>\ % if target["name"] != "asic": module chip_${top["name"]}_${target["name"]} #( // Path to a VMEM file containing the contents of the boot ROM, which will be // baked into the FPGA bitstream. parameter BootRomInitFile = "boot_rom_fpga_${target["name"]}.32.vmem", // Path to a VMEM file containing the contents of the emulated OTP, which will be // baked into the FPGA bitstream. parameter OtpCtrlMemInitFile = "otp_img_fpga_${target["name"]}.vmem", // TODO: Remove this 0 once infra is ready parameter bit RomCtrlSkipCheck = 1 ) ( % else: module chip_${top["name"]}_${target["name"]} #( // TODO: Remove this 0 once infra is ready parameter bit RomCtrlSkipCheck = 1 ) ( % endif <% %>\ // Dedicated Pads % for pad in dedicated_pads: <% sig = get_dio_sig(pinmux, pad) if sig is not None: comment = "// Dedicated Pad for {}".format(sig["name"]) else: comment = "// Manual Pad" %>\ inout ${pad["name"]}, ${comment} % endfor // Muxed Pads % for pad in muxed_pads: inout ${pad["name"]}${" " if loop.last else ","} // MIO Pad ${pad["idx"]} % endfor ); import top_${top["name"]}_pkg::*; import prim_pad_wrapper_pkg::*; % if target["pinmux"]["special_signals"]: //////////////////////////// // Special Signal Indices // //////////////////////////// % for entry in target["pinmux"]["special_signals"]: <% param_name = (lib.Name.from_snake_case(entry["name"]) + lib.Name(["pad", "idx"])).as_camel_case() %>\ parameter int ${param_name} = ${entry["idx"]}; % endfor % endif // DFT and Debug signal positions in the pinout. localparam pinmux_pkg::target_cfg_t PinmuxTargetCfg = '{ tck_idx: TckPadIdx, tms_idx: TmsPadIdx, trst_idx: TrstNPadIdx, tdi_idx: TdiPadIdx, tdo_idx: TdoPadIdx, tap_strap0_idx: Tap0PadIdx, tap_strap1_idx: Tap1PadIdx, dft_strap0_idx: Dft0PadIdx, dft_strap1_idx: Dft1PadIdx, // TODO: check whether there is a better way to pass these USB-specific params usb_dp_idx: DioUsbdevDp, usb_dn_idx: DioUsbdevDn, usb_dp_pullup_idx: DioUsbdevDpPullup, usb_dn_pullup_idx: DioUsbdevDnPullup, // Pad types for attribute WARL behavior dio_pad_type: { <% pad_attr = [] for sig in list(reversed(top["pinmux"]["ios"])): if sig["connection"] != "muxed": pad_attr.append((sig['name'], sig["attr"])) %>\ % for name, attr in pad_attr: ${attr}${" " if loop.last else ","} // DIO ${name} % endfor }, mio_pad_type: { <% pad_attr = [] for pad in list(reversed(pinout["pads"])): if pad["connection"] == "muxed": pad_attr.append(pad["type"]) %>\ % for attr in pad_attr: ${attr}${" " if loop.last else ","} // MIO Pad ${len(pad_attr) - loop.index - 1} % endfor } }; //////////////////////// // Signal definitions // //////////////////////// pad_attr_t [pinmux_reg_pkg::NMioPads-1:0] mio_attr; pad_attr_t [pinmux_reg_pkg::NDioPads-1:0] dio_attr; logic [pinmux_reg_pkg::NMioPads-1:0] mio_out; logic [pinmux_reg_pkg::NMioPads-1:0] mio_oe; logic [pinmux_reg_pkg::NMioPads-1:0] mio_in; logic [pinmux_reg_pkg::NMioPads-1:0] mio_in_raw; logic [pinmux_reg_pkg::NDioPads-1:0] dio_out; logic [pinmux_reg_pkg::NDioPads-1:0] dio_oe; logic [pinmux_reg_pkg::NDioPads-1:0] dio_in; logic unused_mio_in_raw; assign unused_mio_in_raw = ^mio_in_raw; // Manual pads % for pad in dedicated_pads: <% pad_prefix = pad["name"].lower() %>\ % if not get_dio_sig(pinmux, pad): logic manual_in_${pad_prefix}, manual_out_${pad_prefix}, manual_oe_${pad_prefix}; % endif % endfor % for pad in dedicated_pads: <% pad_prefix = pad["name"].lower() %>\ % if not get_dio_sig(pinmux, pad): pad_attr_t manual_attr_${pad_prefix}; % endif % endfor % if target["pinout"]["remove_pads"]: ///////////////////////// // Stubbed pad tie-off // ///////////////////////// // Only signals going to non-custom pads need to be tied off. logic [${len(pinout["pads"])-1}:0] unused_sig; % for pad in pinout["pads"]: % if pad["connection"] == 'muxed': % if pad["name"] in target["pinout"]["remove_pads"]: assign mio_in[${pad["idx"]}] = 1'b0; assign unused_sig[${loop.index}] = mio_out[${pad["idx"]}] ^ mio_oe[${pad["idx"]}]; % endif % else: % if pad["name"] in target["pinout"]["remove_pads"]: <% ## Only need to tie off if this is not a custom pad. sig = get_dio_sig(pinmux, pad) if sig is not None: sig_index = lib.get_io_enum_literal(sig, 'dio') %>\ % if sig is not None: assign dio_in[${lib.get_io_enum_literal(sig, 'dio')}] = 1'b0; assign unused_sig[${loop.index}] = dio_out[${sig_index}] ^ dio_oe[${sig_index}]; % endif % endif % endif % endfor %endif ////////////////////// // Padring Instance // ////////////////////// % if target["name"] == "asic": // AST signals needed in padring ast_pkg::ast_clks_t ast_base_clks; logic scan_rst_n; lc_ctrl_pkg::lc_tx_t scanmode; % endif padring #( // Padring specific counts may differ from pinmux config due // to custom, stubbed or added pads. .NDioPads(${len(dedicated_pads)}), .NMioPads(${len(muxed_pads)}), % if target["name"] == "asic": .PhysicalPads(1), .NIoBanks(int'(IoBankCount)), .DioScanRole ({ % for pad in list(reversed(dedicated_pads)): scan_role_pkg::${lib.Name.from_snake_case('dio_pad_' + pad["name"] + '_scan_role').as_camel_case()}${"" if loop.last else ","} % endfor }), .MioScanRole ({ % for pad in list(reversed(muxed_pads)): scan_role_pkg::${lib.Name.from_snake_case('mio_pad_' + pad["name"] + '_scan_role').as_camel_case()}${"" if loop.last else ","} % endfor }), .DioPadBank ({ % for pad in list(reversed(dedicated_pads)): ${lib.Name.from_snake_case('io_bank_' + pad["bank"]).as_camel_case()}${" " if loop.last else ","} // ${pad['name']} % endfor }), .MioPadBank ({ % for pad in list(reversed(muxed_pads)): ${lib.Name.from_snake_case('io_bank_' + pad["bank"]).as_camel_case()}${" " if loop.last else ","} // ${pad['name']} % endfor }), % endif \ \ .DioPadType ({ % for pad in list(reversed(dedicated_pads)): ${pad["type"]}${" " if loop.last else ","} // ${pad['name']} % endfor }), .MioPadType ({ % for pad in list(reversed(muxed_pads)): ${pad["type"]}${" " if loop.last else ","} // ${pad['name']} % endfor }) ) u_padring ( // This is only used for scan and DFT purposes % if target["name"] == "asic": .clk_scan_i ( ast_base_clks.clk_sys ), .scanmode_i ( scanmode ), % else: .clk_scan_i ( 1'b0 ), .scanmode_i ( lc_ctrl_pkg::Off ), % endif .dio_in_raw_o ( ), .mio_in_raw_o ( mio_in_raw ), // Chip IOs .dio_pad_io ({ % for pad in list(reversed(dedicated_pads)): ${pad["name"]}${"" if loop.last else ","} % endfor }), .mio_pad_io ({ % for pad in list(reversed(muxed_pads)): ${pad["name"]}${"" if loop.last else ","} % endfor }), // Core-facing % for port in ["in_o", "out_i", "oe_i", "attr_i"]: .dio_${port} ({ % for pad in list(reversed(dedicated_pads)): <% sig = get_dio_sig(pinmux, pad) %>\ % if sig is None: manual_${port[:-2]}_${pad["name"].lower()}${"" if loop.last else ","} % else: dio_${port[:-2]}[${lib.get_io_enum_literal(sig, 'dio')}]${"" if loop.last else ","} % endif % endfor }), % endfor % for port in ["in_o", "out_i", "oe_i", "attr_i"]: <% sig_name = 'mio_' + port[:-2] indices = list(reversed(list(pad['idx'] for pad in muxed_pads))) %>\ .mio_${port} (${lib.make_bit_concatenation(sig_name, indices, 6)})${"" if loop.last else ","} % endfor ); ################################################################### ## USB for CW305 ## ################################################################### % if target["name"] == "cw305": // Connect the DP pad assign dio_in[DioUsbdevDp] = manual_in_usb_p; assign manual_out_usb_p = dio_out[DioUsbdevDp]; assign manual_oe_usb_p = dio_oe[DioUsbdevDp]; assign manual_attr_usb_p = dio_attr[DioUsbdevDp]; // Connect the DN pad assign dio_in[DioUsbdevDn] = manual_in_usb_n; assign manual_out_usb_n = dio_out[DioUsbdevDn]; assign manual_oe_usb_n = dio_oe[DioUsbdevDn]; assign manual_attr_usb_n = dio_attr[DioUsbdevDn]; // Connect sense pad assign dio_in[DioUsbdevSense] = manual_in_io_usb_sense0; assign manual_out_io_usb_sense0 = dio_out[DioUsbdevSense]; assign manual_oe_io_usb_sense0 = dio_oe[DioUsbdevSense]; assign manual_attr_io_sense0 = dio_attr[DioUsbdevSense]; // Connect DN pullup assign dio_in[DioUsbdevDnPullup] = manual_in_io_usb_dnpullup0; assign manual_out_io_usb_dnpullup0 = dio_out[DioUsbdevDnPullup]; assign manual_oe_io_usb_dnpullup0 = dio_oe[DioUsbdevDnPullup]; assign manual_attr_io_dnpullup0 = dio_attr[DioUsbdevDnPullup]; // Connect DP pullup assign dio_in[DioUsbdevDpPullup] = manual_in_io_usb_dppullup0; assign manual_out_io_usb_dppullup0 = dio_out[DioUsbdevDpPullup]; assign manual_oe_io_usb_dppullup0 = dio_oe[DioUsbdevDpPullup]; assign manual_attr_io_dppullup0 = dio_attr[DioUsbdevDpPullup]; // Tie-off unused signals assign dio_in[DioUsbdevSe0] = 1'b0; assign dio_in[DioUsbdevTxModeSe] = 1'b0; assign dio_in[DioUsbdevSuspend] = 1'b0; logic unused_usb_sigs; assign unused_usb_sigs = ^{ // SE0 dio_out[DioUsbdevSe0], dio_oe[DioUsbdevSe0], dio_attr[DioUsbdevSe0], // TX Mode dio_out[DioUsbdevTxModeSe], dio_oe[DioUsbdevTxModeSe], dio_attr[DioUsbdevTxModeSe], // Suspend dio_out[DioUsbdevSuspend], dio_oe[DioUsbdevSuspend], dio_attr[DioUsbdevSuspend], // D is used as an input only dio_out[DioUsbdevD], dio_oe[DioUsbdevD], dio_attr[DioUsbdevD] }; % endif ################################################################### ## USB for Nexysvideo ## ################################################################### % if target["name"] == "nexysvideo": ///////////////////// // USB Overlay Mux // ///////////////////// // TODO: generalize this USB mux code and align with other tops. // Software can enable the pinflip feature inside usbdev. // The example hello_usbdev does this based on GPIO0 (a switch on the board) // // Here, we use the state of the DN pullup to effectively undo the // swapping such that the PCB always sees the unflipped D+/D-. We // could do the same inside the .xdc file but then two FPGA // bitstreams would be needed for testing. // // dio_in/out/oe map is: PADS <- _padring <- JTAG mux -> _umux -> USB mux -> _core // Split out for differential PHY testing // Outputs always drive and just copy the value // Let them go to the normal place too because it won't do any harm // and it simplifies the changes needed // The output enable for IO_USB_DNPULLUP0 is used to decide whether we need to undo the swapping. logic undo_swap; assign undo_swap = dio_oe[DioUsbdevDnPullup]; // GPIO[2] = Switch 2 on board is used to select using the UPHY // Keep GPIO[1] for selecting differential in sw logic use_uphy; assign use_uphy = mio_in[MioPadIoa2]; // DioUsbdevDn assign manual_attr_usb_n = '0; assign manual_attr_io_uphy_dn_tx = '0; assign manual_out_io_uphy_dn_tx = manual_out_usb_n; assign manual_out_usb_n = undo_swap ? dio_out[DioUsbdevDp] : dio_out[DioUsbdevDn]; assign manual_oe_io_uphy_dn_tx = manual_oe_usb_n; assign manual_oe_usb_n = undo_swap ? dio_oe[DioUsbdevDp] : dio_oe[DioUsbdevDn]; assign dio_in[DioUsbdevDn] = use_uphy ? (undo_swap ? manual_in_io_uphy_dp_rx : manual_in_io_uphy_dn_rx) : (undo_swap ? manual_in_usb_p : manual_in_usb_n); // DioUsbdevDp assign manual_attr_usb_p = '0; assign manual_attr_io_uphy_dp_tx = '0; assign manual_out_io_uphy_dp_tx = manual_out_usb_p; assign manual_out_usb_p = undo_swap ? dio_out[DioUsbdevDn] : dio_out[DioUsbdevDp]; assign manual_oe_io_uphy_dp_tx = manual_oe_usb_p; assign manual_oe_usb_p = undo_swap ? dio_oe[DioUsbdevDn] : dio_oe[DioUsbdevDp]; assign dio_in[DioUsbdevDp] = use_uphy ? (undo_swap ? manual_in_io_uphy_dn_rx : manual_in_io_uphy_dp_rx) : (undo_swap ? manual_in_usb_n : manual_in_usb_p); // DioUsbdevD // This is not connected at the moment logic unused_out_usb_d; assign unused_out_usb_d = dio_out[DioUsbdevD] ^ dio_oe[DioUsbdevD]; assign dio_in[DioUsbdevD] = use_uphy ? (undo_swap ? ~manual_in_io_uphy_d_rx : manual_in_io_uphy_d_rx) : // This is not connected at the moment (undo_swap ? 1'b1 : 1'b0); assign manual_out_io_uphy_d_rx = 1'b0; assign manual_oe_io_uphy_d_rx = 1'b0; // DioUsbdevDnPullup assign manual_attr_io_usb_dnpullup0 = '0; assign manual_out_io_usb_dnpullup0 = undo_swap ? dio_out[DioUsbdevDpPullup] : dio_out[DioUsbdevDnPullup]; assign manual_oe_io_usb_dnpullup0 = undo_swap ? dio_oe[DioUsbdevDpPullup] : dio_oe[DioUsbdevDnPullup]; assign dio_in[DioUsbdevDnPullup] = manual_in_io_usb_dnpullup0; // DioUsbdevDpPullup assign manual_attr_io_usb_dppullup0 = '0; assign manual_out_io_usb_dppullup0 = undo_swap ? dio_out[DioUsbdevDnPullup] : dio_out[DioUsbdevDpPullup]; assign manual_oe_io_usb_dppullup0 = undo_swap ? dio_oe[DioUsbdevDnPullup] : dio_oe[DioUsbdevDpPullup]; assign dio_in[DioUsbdevDpPullup] = manual_in_io_usb_dppullup0; // DioUsbdevSense assign manual_out_io_usb_sense0 = dio_out[DioUsbdevSense]; assign manual_oe_io_usb_sense0 = dio_oe[DioUsbdevSense]; assign dio_in[DioUsbdevSense] = use_uphy ? manual_in_io_uphy_sense : manual_in_io_usb_sense0; assign manual_out_io_uphy_sense = 1'b0; assign manual_oe_io_uphy_sense = 1'b0; // DioUsbdevRxEnable assign dio_in[DioUsbdevRxEnable] = 1'b0; // Additional outputs for uphy assign manual_oe_io_uphy_dppullup = 1'b1; assign manual_out_io_uphy_dppullup = manual_out_io_usb_dppullup0 & manual_oe_io_usb_dppullup0; logic unused_in_io_uphy_dppullup; assign unused_in_io_uphy_dppullup = manual_in_io_uphy_dppullup; assign manual_oe_io_uphy_oe_n = 1'b1; assign manual_out_io_uphy_oe_n = ~manual_oe_usb_p; logic unused_in_io_uphy_oe_n; assign unused_in_io_uphy_oe_n = manual_in_io_uphy_oe_n; % endif ################################################################### ## ASIC ## ################################################################### % if target["name"] == "asic": ////////////////////////////////// // Manual Pad / Signal Tie-offs // ////////////////////////////////// assign manual_out_por_n = 1'b0; assign manual_oe_por_n = 1'b0; assign manual_out_cc1 = 1'b0; assign manual_oe_cc1 = 1'b0; assign manual_out_cc2 = 1'b0; assign manual_oe_cc2 = 1'b0; assign manual_out_flash_test_mode0 = 1'b0; assign manual_oe_flash_test_mode0 = 1'b0; assign manual_out_flash_test_mode1 = 1'b0; assign manual_oe_flash_test_mode1 = 1'b0; assign manual_out_flash_test_volt = 1'b0; assign manual_oe_flash_test_volt = 1'b0; assign manual_out_otp_ext_volt = 1'b0; assign manual_oe_otp_ext_volt = 1'b0; // These pad attributes currently tied off permanently (these are all input-only pads). assign manual_attr_por_n = '0; assign manual_attr_cc1 = '0; assign manual_attr_cc2 = '0; assign manual_attr_flash_test_mode0 = '0; assign manual_attr_flash_test_mode1 = '0; assign manual_attr_flash_test_volt = '0; assign manual_attr_otp_ext_volt = '0; logic unused_manual_sigs; assign unused_manual_sigs = ^{ manual_in_cc2, manual_in_cc1, manual_in_flash_test_volt, manual_in_flash_test_mode0, manual_in_flash_test_mode1, manual_in_otp_ext_volt }; /////////////////////////////// // Differential USB Receiver // /////////////////////////////// // TODO: generalize this USB mux code and align with other tops. // Connect the DP pad assign dio_in[DioUsbdevDp] = manual_in_usb_p; assign manual_out_usb_p = dio_out[DioUsbdevDp]; assign manual_oe_usb_p = dio_oe[DioUsbdevDp]; assign manual_attr_usb_p = dio_attr[DioUsbdevDp]; // Connect the DN pad assign dio_in[DioUsbdevDn] = manual_in_usb_n; assign manual_out_usb_n = dio_out[DioUsbdevDn]; assign manual_oe_usb_n = dio_oe[DioUsbdevDn]; assign manual_attr_usb_n = dio_attr[DioUsbdevDn]; // Pullups logic usb_pullup_p_en, usb_pullup_n_en; assign usb_pullup_p_en = dio_out[DioUsbdevDpPullup] & dio_oe[DioUsbdevDpPullup]; assign usb_pullup_n_en = dio_out[DioUsbdevDnPullup] & dio_oe[DioUsbdevDnPullup]; logic usb_rx_enable; assign usb_rx_enable = dio_out[DioUsbdevRxEnable] & dio_oe[DioUsbdevRxEnable]; logic [ast_pkg::UsbCalibWidth-1:0] usb_io_pu_cal; // pwrmgr interface pwrmgr_pkg::pwr_ast_req_t base_ast_pwr; pwrmgr_pkg::pwr_ast_rsp_t ast_base_pwr; prim_usb_diff_rx #( .CalibW(ast_pkg::UsbCalibWidth) ) u_prim_usb_diff_rx ( .input_pi ( USB_P ), .input_ni ( USB_N ), .input_en_i ( usb_rx_enable ), .core_pok_i ( ast_base_pwr.main_pok ), .pullup_p_en_i ( usb_pullup_p_en ), .pullup_n_en_i ( usb_pullup_n_en ), .calibration_i ( usb_io_pu_cal ), .input_o ( dio_in[DioUsbdevD] ) ); // Tie-off unused signals assign dio_in[DioUsbdevSense] = 1'b0; assign dio_in[DioUsbdevSe0] = 1'b0; assign dio_in[DioUsbdevDpPullup] = 1'b0; assign dio_in[DioUsbdevDnPullup] = 1'b0; assign dio_in[DioUsbdevTxModeSe] = 1'b0; assign dio_in[DioUsbdevSuspend] = 1'b0; assign dio_in[DioUsbdevRxEnable] = 1'b0; logic unused_usb_sigs; assign unused_usb_sigs = ^{ // Sense dio_out[DioUsbdevSense], dio_oe[DioUsbdevSense], dio_attr[DioUsbdevSense], // SE0 dio_out[DioUsbdevSe0], dio_oe[DioUsbdevSe0], dio_attr[DioUsbdevSe0], // TX Mode dio_out[DioUsbdevTxModeSe], dio_oe[DioUsbdevTxModeSe], dio_attr[DioUsbdevTxModeSe], // Suspend dio_out[DioUsbdevSuspend], dio_oe[DioUsbdevSuspend], dio_attr[DioUsbdevSuspend], // Rx enable dio_attr[DioUsbdevRxEnable], // D is used as an input only dio_out[DioUsbdevD], dio_oe[DioUsbdevD], dio_attr[DioUsbdevD], // Pullup/down dio_attr[DioUsbdevDpPullup], dio_attr[DioUsbdevDnPullup] }; ////////////////////// // AST // ////////////////////// // TLUL interface tlul_pkg::tl_h2d_t base_ast_bus; tlul_pkg::tl_d2h_t ast_base_bus; // assorted ast status ast_pkg::ast_status_t ast_status; // ast clocks and resets logic aon_pok; // synchronization clocks / rests clkmgr_pkg::clkmgr_ast_out_t clks_ast; rstmgr_pkg::rstmgr_ast_out_t rsts_ast; // otp power sequence otp_ctrl_pkg::otp_ast_req_t otp_ctrl_otp_ast_pwr_seq; otp_ctrl_pkg::otp_ast_rsp_t otp_ctrl_otp_ast_pwr_seq_h; logic usb_ref_pulse; logic usb_ref_val; // adc ast_pkg::adc_ast_req_t adc_req; ast_pkg::adc_ast_rsp_t adc_rsp; // entropy source interface // The entropy source pacakge definition should eventually be moved to es entropy_src_pkg::entropy_src_rng_req_t es_rng_req; entropy_src_pkg::entropy_src_rng_rsp_t es_rng_rsp; logic es_rng_fips; // entropy distribution network edn_pkg::edn_req_t ast_edn_edn_req; edn_pkg::edn_rsp_t ast_edn_edn_rsp; // alerts interface ast_pkg::ast_alert_rsp_t ast_alert_rsp; ast_pkg::ast_alert_req_t ast_alert_req; // Flash connections lc_ctrl_pkg::lc_tx_t flash_bist_enable; logic flash_power_down_h; logic flash_power_ready_h; // Life cycle clock bypass req/ack lc_ctrl_pkg::lc_tx_t ast_clk_byp_req; lc_ctrl_pkg::lc_tx_t ast_clk_byp_ack; // DFT connections logic scan_en; lc_ctrl_pkg::lc_tx_t dft_en; pinmux_pkg::dft_strap_test_req_t dft_strap_test; // Debug connections logic [ast_pkg::Ast2PadOutWidth-1:0] ast2pinmux; logic [ast_pkg::Pad2AstInWidth-1:0] pad2ast; assign pad2ast = { mio_in_raw[MioPadIoc3], mio_in_raw[MioPadIob8], mio_in_raw[MioPadIob7], mio_in_raw[MioPadIob2], mio_in_raw[MioPadIob1], mio_in_raw[MioPadIob0] }; // Jitter enable logic jen; // reset domain connections import rstmgr_pkg::PowerDomains; import rstmgr_pkg::DomainAonSel; import rstmgr_pkg::Domain0Sel; // external clock comes in at a fixed position logic ext_clk; assign ext_clk = mio_in_raw[MioPadIoc6]; // Memory configuration connections ast_pkg::spm_rm_t ast_ram_1p_cfg; ast_pkg::spm_rm_t ast_rf_cfg; ast_pkg::spm_rm_t ast_rom_cfg; ast_pkg::dpm_rm_t ast_ram_2p_fcfg; ast_pkg::dpm_rm_t ast_ram_2p_lcfg; prim_ram_1p_pkg::ram_1p_cfg_t ram_1p_cfg; prim_ram_2p_pkg::ram_2p_cfg_t ram_2p_cfg; prim_rom_pkg::rom_cfg_t rom_cfg; // conversion from ast structure to memory centric structures assign ram_1p_cfg = '{ ram_cfg: '{ cfg_en: ast_ram_1p_cfg.marg_en, cfg: ast_ram_1p_cfg.marg }, rf_cfg: '{ cfg_en: ast_rf_cfg.marg_en, cfg: ast_rf_cfg.marg } }; assign ram_2p_cfg = '{ a_ram_fcfg: '{ cfg_en: ast_ram_2p_fcfg.marg_en_a, cfg: ast_ram_2p_fcfg.marg_a }, a_ram_lcfg: '{ cfg_en: ast_ram_2p_lcfg.marg_en_a, cfg: ast_ram_2p_lcfg.marg_a }, b_ram_fcfg: '{ cfg_en: ast_ram_2p_fcfg.marg_en_b, cfg: ast_ram_2p_fcfg.marg_b }, b_ram_lcfg: '{ cfg_en: ast_ram_2p_lcfg.marg_en_b, cfg: ast_ram_2p_lcfg.marg_b } }; assign rom_cfg = '{ cfg_en: ast_rom_cfg.marg_en, cfg: ast_rom_cfg.marg }; // AST does not use all clocks / resets forwarded to it logic unused_slow_clk_en; logic unused_usb_clk_aon; logic unused_usb_clk_io_div4; assign unused_slow_clk_en = base_ast_pwr.slow_clk_en; assign unused_usb_clk_aon = clks_ast.clk_ast_usbdev_aon_peri; assign unused_usb_clk_io_div4 = clks_ast.clk_ast_usbdev_io_div4_peri; logic unused_usb_usb_rst; logic [PowerDomains-1:0] unused_usb_sys_io_div4_rst; logic [PowerDomains-1:0] unused_usb_sys_aon_rst; logic unused_ast_sys_io_div4_rst; logic unused_sensor_ctrl_sys_io_div4_rst; logic unused_adc_ctrl_sys_io_div4_rst; logic unused_entropy_sys_rst; logic unused_edn_sys_rst; assign unused_usb_usb_rst = rsts_ast.rst_ast_usbdev_usb_n[DomainAonSel]; assign unused_usb_sys_io_div4_rst = rsts_ast.rst_ast_usbdev_sys_io_div4_n; assign unused_usb_sys_aon_rst = rsts_ast.rst_ast_usbdev_sys_aon_n; assign unused_ast_sys_io_div4_rst = rsts_ast.rst_ast_ast_sys_io_div4_n[Domain0Sel]; assign unused_sensor_ctrl_sys_io_div4_rst = rsts_ast.rst_ast_sensor_ctrl_aon_sys_io_div4_n[Domain0Sel]; assign unused_adc_ctrl_sys_io_div4_rst = rsts_ast.rst_ast_adc_ctrl_aon_sys_io_div4_n[Domain0Sel]; assign unused_entropy_sys_rst = rsts_ast.rst_ast_entropy_src_sys_n[DomainAonSel]; assign unused_edn_sys_rst = rsts_ast.rst_ast_edn0_sys_n[DomainAonSel]; ast_pkg::ast_dif_t flash_alert; ast_pkg::ast_dif_t otp_alert; logic ast_init_done; ast #( .EntropyStreams(ast_pkg::EntropyStreams), .AdcChannels(ast_pkg::AdcChannels), .AdcDataWidth(ast_pkg::AdcDataWidth), .UsbCalibWidth(ast_pkg::UsbCalibWidth), .Ast2PadOutWidth(ast_pkg::Ast2PadOutWidth), .Pad2AstInWidth(ast_pkg::Pad2AstInWidth) ) u_ast ( // tlul .tl_i ( base_ast_bus ), .tl_o ( ast_base_bus ), // init done indication .ast_init_done_o ( ast_init_done ), // buffered clocks & resets // Reset domain connection is manual at the moment .clk_ast_adc_i ( clks_ast.clk_ast_adc_ctrl_aon_io_div4_peri ), .rst_ast_adc_ni ( rsts_ast.rst_ast_adc_ctrl_aon_sys_io_div4_n[DomainAonSel] ), .clk_ast_alert_i ( clks_ast.clk_ast_sensor_ctrl_aon_io_div4_secure ), .rst_ast_alert_ni ( rsts_ast.rst_ast_sensor_ctrl_aon_sys_io_div4_n[DomainAonSel] ), .clk_ast_es_i ( clks_ast.clk_ast_edn0_main_secure ), .rst_ast_es_ni ( rsts_ast.rst_ast_edn0_sys_n[Domain0Sel] ), .clk_ast_rng_i ( clks_ast.clk_ast_entropy_src_main_secure ), .rst_ast_rng_ni ( rsts_ast.rst_ast_entropy_src_sys_n[Domain0Sel] ), .clk_ast_tlul_i ( clks_ast.clk_ast_ast_io_div4_secure ), .rst_ast_tlul_ni ( rsts_ast.rst_ast_ast_sys_io_div4_n[DomainAonSel] ), .clk_ast_usb_i ( clks_ast.clk_ast_usbdev_usb_peri ), .rst_ast_usb_ni ( rsts_ast.rst_ast_usbdev_usb_n[Domain0Sel] ), .clk_ast_ext_i ( ext_clk ), .por_ni ( manual_in_por_n ), // pok test for FPGA .vcc_supp_i ( 1'b1 ), .vcaon_supp_i ( 1'b1 ), .vcmain_supp_i ( 1'b1 ), .vioa_supp_i ( 1'b1 ), .viob_supp_i ( 1'b1 ), // pok .vcaon_pok_o ( aon_pok ), .vcmain_pok_o ( ast_base_pwr.main_pok ), .vioa_pok_o ( ast_status.io_pok[0] ), .viob_pok_o ( ast_status.io_pok[1] ), // main regulator .main_env_iso_en_i ( base_ast_pwr.pwr_clamp_env ), .main_pd_ni ( base_ast_pwr.main_pd_n ), // pdm control (flash)/otp .flash_power_down_h_o ( flash_power_down_h ), .flash_power_ready_h_o ( flash_power_ready_h ), .otp_power_seq_i ( otp_ctrl_otp_ast_pwr_seq ), .otp_power_seq_h_o ( otp_ctrl_otp_ast_pwr_seq_h ), // system source clock .clk_src_sys_en_i ( base_ast_pwr.core_clk_en ), // need to add function in clkmgr .clk_src_sys_jen_i ( jen ), .clk_src_sys_o ( ast_base_clks.clk_sys ), .clk_src_sys_val_o ( ast_base_pwr.core_clk_val ), // aon source clock .clk_src_aon_o ( ast_base_clks.clk_aon ), .clk_src_aon_val_o ( ast_base_pwr.slow_clk_val ), // io source clock .clk_src_io_en_i ( base_ast_pwr.io_clk_en ), .clk_src_io_o ( ast_base_clks.clk_io ), .clk_src_io_val_o ( ast_base_pwr.io_clk_val ), // usb source clock .usb_ref_pulse_i ( usb_ref_pulse ), .usb_ref_val_i ( usb_ref_val ), .clk_src_usb_en_i ( base_ast_pwr.usb_clk_en ), .clk_src_usb_o ( ast_base_clks.clk_usb ), .clk_src_usb_val_o ( ast_base_pwr.usb_clk_val ), // USB IO Pull-up Calibration Setting .usb_io_pu_cal_o ( usb_io_pu_cal ), // adc .adc_a0_ai ( CC1 ), .adc_a1_ai ( CC2 ), .adc_pd_i ( adc_req.pd ), .adc_chnsel_i ( adc_req.channel_sel ), .adc_d_o ( adc_rsp.data ), .adc_d_val_o ( adc_rsp.data_valid ), // rng .rng_en_i ( es_rng_req.rng_enable ), .rng_fips_i ( es_rng_fips ), .rng_val_o ( es_rng_rsp.rng_valid ), .rng_b_o ( es_rng_rsp.rng_b ), // entropy .entropy_rsp_i ( ast_edn_edn_rsp ), .entropy_req_o ( ast_edn_edn_req ), // alerts .fla_alert_in_i ( flash_alert ), .otp_alert_in_i ( otp_alert ), .alert_rsp_i ( ast_alert_rsp ), .alert_req_o ( ast_alert_req ), // dft .dft_strap_test_i ( dft_strap_test ), .lc_dft_en_i ( dft_en ), // pinmux related .padmux2ast_i ( pad2ast ), .ast2padmux_o ( ast2pinmux ), // Direct short to PAD .pad2ast_t0_ai ( IOA4 ), .pad2ast_t1_ai ( IOA5 ), .ast2pad_t0_ao ( IOA2 ), .ast2pad_t1_ao ( IOA3 ), .lc_clk_byp_req_i ( ast_clk_byp_req ), .lc_clk_byp_ack_o ( ast_clk_byp_ack ), .flash_bist_en_o ( flash_bist_enable ), // Memory configuration connections .dpram_rmf_o ( ast_ram_2p_fcfg ), .dpram_rml_o ( ast_ram_2p_lcfg ), .spram_rm_o ( ast_ram_1p_cfg ), .sprgf_rm_o ( ast_rf_cfg ), .sprom_rm_o ( ast_rom_cfg ), // scan .dft_scan_md_o ( scanmode ), .scan_shift_en_o ( scan_en ), .scan_reset_no ( scan_rst_n ) ); ////////////////////// // Top-level design // ////////////////////// top_${top["name"]} #( .AesMasking(1'b1), .AesSBoxImpl(aes_pkg::SBoxImplDom), .SecAesStartTriggerDelay(0), .SecAesAllowForcingMasks(1'b0), .KmacEnMasking(1), // DOM AND + Masking scheme .KmacReuseShare(0), .SramCtrlRetAonInstrExec(0), .SramCtrlMainInstrExec(1), .PinmuxAonTargetCfg(PinmuxTargetCfg), .RomCtrlSkipCheck(RomCtrlSkipCheck) ) top_${top["name"]} ( .rst_ni ( aon_pok ), // ast connections .clk_main_i ( ast_base_clks.clk_sys ), .clk_io_i ( ast_base_clks.clk_io ), .clk_usb_i ( ast_base_clks.clk_usb ), .clk_aon_i ( ast_base_clks.clk_aon ), .clks_ast_o ( clks_ast ), .clk_main_jitter_en_o ( jen ), .rsts_ast_o ( rsts_ast ), .pwrmgr_ast_req_o ( base_ast_pwr ), .pwrmgr_ast_rsp_i ( ast_base_pwr ), .sensor_ctrl_ast_alert_req_i ( ast_alert_req ), .sensor_ctrl_ast_alert_rsp_o ( ast_alert_rsp ), .sensor_ctrl_ast_status_i ( ast_status ), .usbdev_usb_ref_val_o ( usb_ref_pulse ), .usbdev_usb_ref_pulse_o ( usb_ref_val ), .ast_tl_req_o ( base_ast_bus ), .ast_tl_rsp_i ( ast_base_bus ), .adc_req_o ( adc_req ), .adc_rsp_i ( adc_rsp ), .ast_edn_req_i ( ast_edn_edn_req ), .ast_edn_rsp_o ( ast_edn_edn_rsp ), .otp_ctrl_otp_ast_pwr_seq_o ( otp_ctrl_otp_ast_pwr_seq ), .otp_ctrl_otp_ast_pwr_seq_h_i ( otp_ctrl_otp_ast_pwr_seq_h ), .otp_alert_o ( otp_alert ), .flash_bist_enable_i ( flash_bist_enable ), .flash_power_down_h_i ( flash_power_down_h ), .flash_power_ready_h_i ( flash_power_ready_h ), .flash_alert_o ( flash_alert ), .es_rng_req_o ( es_rng_req ), .es_rng_rsp_i ( es_rng_rsp ), .es_rng_fips_o ( es_rng_fips ), .ast_clk_byp_req_o ( ast_clk_byp_req ), .ast_clk_byp_ack_i ( ast_clk_byp_ack ), .ast2pinmux_i ( ast2pinmux ), .ast_init_done_i ( ast_init_done ), // Flash test mode voltages .flash_test_mode_a_io ( {FLASH_TEST_MODE1, FLASH_TEST_MODE0} ), .flash_test_voltage_h_io ( FLASH_TEST_VOLT ), // OTP external voltage .otp_ext_voltage_h_io ( OTP_EXT_VOLT ), // Multiplexed I/O .mio_in_i ( mio_in ), .mio_out_o ( mio_out ), .mio_oe_o ( mio_oe ), // Dedicated I/O .dio_in_i ( dio_in ), .dio_out_o ( dio_out ), .dio_oe_o ( dio_oe ), // Pad attributes .mio_attr_o ( mio_attr ), .dio_attr_o ( dio_attr ), // Memory attributes .ram_1p_cfg_i ( ram_1p_cfg ), .ram_2p_cfg_i ( ram_2p_cfg ), .rom_cfg_i ( rom_cfg ), // DFT signals .ast_lc_dft_en_o ( dft_en ), .dft_strap_test_o ( dft_strap_test ), .dft_hold_tap_sel_i ( '0 ), .scan_rst_ni ( scan_rst_n ), .scan_en_i ( scan_en ), .scanmode_i ( scanmode ) ); % endif ################################################################### ## FPGA shared ## ################################################################### % if target["name"] in ["cw305", "nexysvideo"]: ////////////////// // PLL for FPGA // ////////////////// assign manual_out_io_clk = 1'b0; assign manual_oe_io_clk = 1'b0; assign manual_out_por_n = 1'b0; assign manual_oe_por_n = 1'b0; assign manual_out_io_jsrst_n = 1'b0; assign manual_oe_io_jsrst_n = 1'b0; logic clk_main, clk_usb_48mhz, clk_aon, rst_n; clkgen_xil7series # ( .AddClkBuf(0) ) clkgen ( .clk_i(manual_in_io_clk), .rst_ni(manual_in_por_n), .jtag_srst_ni(manual_in_io_jsrst_n), .clk_main_o(clk_main), .clk_48MHz_o(clk_usb_48mhz), .clk_aon_o(clk_aon), .rst_no(rst_n) ); ////////////////////// // Top-level design // ////////////////////// pwrmgr_pkg::pwr_ast_rsp_t ast_base_pwr; ast_pkg::ast_alert_req_t ast_base_alerts; ast_pkg::ast_status_t ast_base_status; assign ast_base_pwr.slow_clk_val = 1'b1; assign ast_base_pwr.core_clk_val = 1'b1; assign ast_base_pwr.io_clk_val = 1'b1; assign ast_base_pwr.usb_clk_val = 1'b1; assign ast_base_pwr.main_pok = 1'b1; ast_pkg::ast_dif_t silent_alert = '{ p: 1'b0, n: 1'b1 }; assign ast_base_alerts.alerts = {ast_pkg::NumAlerts{silent_alert}}; assign ast_base_status.io_pok = {ast_pkg::NumIoRails{1'b1}}; // the rst_ni pin only goes to AST // the rest of the logic generates reset based on the 'pok' signal. // for verilator purposes, make these two the same. lc_ctrl_pkg::lc_tx_t lc_clk_bypass; % if target["name"] == "cw305": // This is used for outputting the capture trigger logic [pinmux_reg_pkg::NMioPads-1:0] mio_out_pre; % endif // TODO: align this with ASIC version to minimize the duplication. // Also need to add AST simulation and FPGA emulation models for things like entropy source - // otherwise Verilator / FPGA will hang. top_${top["name"]} #( % if target["name"] == "cw305": .AesMasking(1'b1), .AesSBoxImpl(aes_pkg::SBoxImplDom), .SecAesStartTriggerDelay(40), .SecAesAllowForcingMasks(1'b1), .SecAesSkipPRNGReseeding(1'b1), .IbexICache(0), .BootRomInitFile(BootRomInitFile), % else: .AesMasking(1'b0), .AesSBoxImpl(aes_pkg::SBoxImplLut), .SecAesStartTriggerDelay(0), .SecAesAllowForcingMasks(1'b0), .SecAesSkipPRNGReseeding(1'b0), .EntropySrcStub(1'b1), .CsrngSBoxImpl(aes_pkg::SBoxImplLut), .OtbnRegFile(otbn_pkg::RegFileFPGA), .OtbnStub(1'b1), .OtpCtrlMemInitFile(OtpCtrlMemInitFile), .RomCtrlBootRomInitFile(BootRomInitFile), % endif .IbexRegFile(ibex_pkg::RegFileFPGA), .IbexPipeLine(1), .SecureIbex(0), .SramCtrlRetAonInstrExec(0), .SramCtrlMainInstrExec(1), .PinmuxAonTargetCfg(PinmuxTargetCfg) ) top_${top["name"]} ( .rst_ni ( rst_n ), .clk_main_i ( clk_main ), .clk_io_i ( clk_main ), .clk_usb_i ( clk_usb_48mhz ), .clk_aon_i ( clk_aon ), .clks_ast_o ( ), .clk_main_jitter_en_o ( ), .rsts_ast_o ( ), .pwrmgr_ast_req_o ( ), .pwrmgr_ast_rsp_i ( ast_base_pwr ), .sensor_ctrl_ast_alert_req_i ( ast_base_alerts ), .sensor_ctrl_ast_alert_rsp_o ( ), .sensor_ctrl_ast_status_i ( ast_base_status ), .usbdev_usb_ref_val_o ( ), .usbdev_usb_ref_pulse_o ( ), .ast_edn_req_i ( '0 ), .ast_edn_rsp_o ( ), .flash_bist_enable_i ( lc_ctrl_pkg::Off ), .flash_power_down_h_i ( 1'b0 ), .flash_power_ready_h_i ( 1'b1 ), .ast_clk_byp_req_o ( lc_clk_bypass ), .ast_clk_byp_ack_i ( lc_clk_bypass ), % if target["name"] != "cw305": .ast_tl_req_o ( ), .ast_tl_rsp_i ( '0 ), .otp_ctrl_otp_ast_pwr_seq_o ( ), .otp_ctrl_otp_ast_pwr_seq_h_i ( '0 ), .otp_alert_o ( ), .es_rng_req_o ( ), .es_rng_rsp_i ( '0 ), .es_rng_fips_o ( ), .ast2pinmux_i ( '0 ), % endif // Multiplexed I/O .mio_in_i ( mio_in ), % if target["name"] == "cw305": .mio_out_o ( mio_out_pre ), % else: .mio_out_o ( mio_out ), % endif .mio_oe_o ( mio_oe ), // Dedicated I/O .dio_in_i ( dio_in ), .dio_out_o ( dio_out ), .dio_oe_o ( dio_oe ), // Pad attributes .mio_attr_o ( mio_attr ), .dio_attr_o ( dio_attr ), // Memory attributes .ram_1p_cfg_i ( '0 ), .ram_2p_cfg_i ( '0 ), .rom_cfg_i ( '0 ), // DFT signals .dft_hold_tap_sel_i ( '0 ), .scan_rst_ni ( 1'b1 ), .scan_en_i ( 1'b0 ), .scanmode_i ( lc_ctrl_pkg::Off ) ); % endif ################################################################### ## CW305 capture trigger ## ################################################################### % if target["name"] == "cw305": ////////////////////////////////////// // Generate precise capture trigger // ////////////////////////////////////// // TODO: make this a "manual" IO specific to the CW305 target // such that we can decouple this from the MIO signals. localparam int MioIdxTrigger = 15; // To obtain a more precise capture trigger for side-channel analysis, we only forward the // software-controlled capture trigger when the AES module is actually busy (performing // either encryption/decryption or clearing internal registers). // GPIO15 is used as capture trigger (mapped to IOB9 at the moment in pinmux.c). always_comb begin : p_trigger mio_out = mio_out_pre; mio_out[MioIdxTrigger] = mio_out_pre[MioIdxTrigger] & ~top_englishbreakfast.clkmgr_aon_idle[clkmgr_pkg::Aes]; end ////////////////////// // ChipWhisperer IO // ////////////////////// logic unused_inputs; assign unused_inputs = manual_in_tio_clkout ^ manual_in_io_utx_debug; // Clock ouput to capture board. assign manual_out_tio_clkout = manual_in_io_clk; assign manual_oe_tio_clkout = 1'b1; // UART Tx for debugging. The UART itself is connected to the capture board. assign manual_out_io_utx_debug = top_${top["name"]}.cio_uart0_tx_d2p; assign manual_oe_io_utx_debug = 1'b1; % endif endmodule : chip_${top["name"]}_${target["name"]}
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // Generated by topgen.py parameter string LIST_OF_ALERTS[] = { % for alert in top["alert"]: % if loop.last: "${alert["name"]}" % else: "${alert["name"]}", % endif % endfor }; parameter uint NUM_ALERTS = ${len(top["alert"])};
# This disables clang-format on all files in the sw/autogen directory. # This is needed so that git-clang-format and similar scripts work. DisableFormat: true SortIncludes: false
# OpenTitan topgen templates This directory contains templates used by topgen to assembly a chip toplevel.
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // tb__alert_handler_connect.sv is auto-generated by `topgen.py` tool <% index = 0 module_name = "" %>\ % for alert in top["alert"]: % if alert["module_name"] == module_name: <% index = index + 1 %>\ % else: <% module_name = alert["module_name"] index = 0 %>\ % endif assign alert_if[${loop.index}].alert_tx = `CHIP_HIER.u_${module_name}.alert_tx_o[${index}]; % endfor
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // tb__xbar_connect generated by `topgen.py` tool <% from collections import OrderedDict import topgen.lib as lib top_hier = 'tb.dut.top_' + top["name"] + '.' clk_hier = top_hier + top["clocks"]["hier_paths"]["top"] clk_src = OrderedDict() for xbar in top["xbar"]: for clk, src in xbar["clock_srcs"].items(): clk_src[clk] = src clk_freq = OrderedDict() for clock in top["clocks"]["srcs"] + top["clocks"]["derived_srcs"]: if clock["name"] in clk_src.values(): clk_freq[clock["name"]] = clock["freq"] hosts = OrderedDict() devices = OrderedDict() for xbar in top["xbar"]: for node in xbar["nodes"]: if node["type"] == "host" and not node["xbar"]: hosts[node["name"]] = "clk_" + clk_src[node["clock"]] elif node["type"] == "device" and not node["xbar"]: devices[node["name"]] = "clk_" + clk_src[node["clock"]] def escape_if_name(qual_if_name): return qual_if_name.replace('.', '__') %>\ <%text> `define DRIVE_CHIP_TL_HOST_IF(tl_name, inst_name, sig_name) \ force ``tl_name``_tl_if.d2h = dut.top_earlgrey.u_``inst_name``.``sig_name``_i; \ force dut.top_earlgrey.u_``inst_name``.``sig_name``_o = ``tl_name``_tl_if.h2d; \ force dut.top_earlgrey.u_``inst_name``.clk_i = 0; \ uvm_config_db#(virtual tl_if)::set(null, $sformatf("*%0s*", `"tl_name`"), "vif", \ ``tl_name``_tl_if); `define DRIVE_CHIP_TL_DEVICE_IF(tl_name, inst_name, sig_name) \ force ``tl_name``_tl_if.h2d = dut.top_earlgrey.u_``inst_name``.``sig_name``_i; \ force dut.top_earlgrey.u_``inst_name``.``sig_name``_o = ``tl_name``_tl_if.d2h; \ force dut.top_earlgrey.u_``inst_name``.clk_i = 0; \ uvm_config_db#(virtual tl_if)::set(null, $sformatf("*%0s*", `"tl_name`"), "vif", \ ``tl_name``_tl_if); `define DRIVE_CHIP_TL_EXT_DEVICE_IF(tl_name, port_name) \ force ``tl_name``_tl_if.h2d = dut.top_earlgrey.``port_name``_req_o; \ force dut.top_earlgrey.``port_name``_rsp_i = ``tl_name``_tl_if.d2h; \ uvm_config_db#(virtual tl_if)::set(null, $sformatf("*%0s*", `"tl_name`"), "vif", \ ``tl_name``_tl_if); </%text>\ % for c in clk_freq.keys(): wire clk_${c}; clk_rst_if clk_rst_if_${c}(.clk(clk_${c}), .rst_n(rst_n)); % endfor % for i, clk in hosts.items(): tl_if ${escape_if_name(i)}_tl_if(${clk}, rst_n); % endfor % for i, clk in devices.items(): tl_if ${escape_if_name(i)}_tl_if(${clk}, rst_n); % endfor initial begin bit xbar_mode; void'($value$plusargs("xbar_mode=%0b", xbar_mode)); if (xbar_mode) begin // only enable assertions in xbar as many pins are unconnected $assertoff(0, tb); % for xbar in top["xbar"]: $asserton(0, tb.dut.top_${top["name"]}.u_xbar_${xbar["name"]}); % endfor % for c in clk_freq.keys(): clk_rst_if_${c}.set_active(.drive_rst_n_val(0)); clk_rst_if_${c}.set_freq_khz(${clk_freq[c]} / 1000); % endfor // bypass clkmgr, force clocks directly % for xbar in top["xbar"]: % for clk, src in xbar["clock_srcs"].items(): force ${top_hier}u_xbar_${xbar["name"]}.${clk} = clk_${src}; % endfor % endfor // bypass rstmgr, force resets directly % for xbar in top["xbar"]: % for rst in xbar["reset_connections"]: force ${top_hier}u_xbar_${xbar["name"]}.${rst} = rst_n; % endfor % endfor % for xbar in top["xbar"]: % for node in xbar["nodes"]: <% clk = 'clk_' + clk_src[node["clock"]] esc_name = node['name'].replace('.', '__') inst_sig_list = lib.find_otherside_modules(top, xbar["name"], 'tl_' + esc_name) inst_name = inst_sig_list[0][1] sig_name = inst_sig_list[0][2] %>\ % if node["type"] == "host" and not node["xbar"]: `DRIVE_CHIP_TL_HOST_IF(${esc_name}, ${inst_name}, ${sig_name}) % elif node["type"] == "device" and not node["xbar"] and node["stub"]: `DRIVE_CHIP_TL_EXT_DEVICE_IF(${esc_name}, ${inst_name}_${sig_name}) % elif node["type"] == "device" and not node["xbar"]: `DRIVE_CHIP_TL_DEVICE_IF(${esc_name}, ${inst_name}, ${sig_name}) % endif % endfor % endfor end end `undef DRIVE_CHIP_TL_HOST_IF `undef DRIVE_CHIP_TL_DEVICE_IF `undef DRIVE_CHIP_TL_EXT_DEVICE_IF
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "${helper.header_path}" /** * PLIC Interrupt Source to Peripheral Map * * This array is a mapping from `${helper.plic_interrupts.name.as_c_type()}` to * `${helper.plic_sources.name.as_c_type()}`. */ ${helper.plic_mapping.render_definition()} /** * Alert Handler Alert Source to Peripheral Map * * This array is a mapping from `${helper.alert_alerts.name.as_c_type()}` to * `${helper.alert_sources.name.as_c_type()}`. */ ${helper.alert_mapping.render_definition()}
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #ifndef _TOP_${top["name"].upper()}_H_ #define _TOP_${top["name"].upper()}_H_ /** * @file * @brief Top-specific Definitions * * This file contains preprocessor and type definitions for use within the * device C/C++ codebase. * * These definitions are for information that depends on the top-specific chip * configuration, which includes: * - Device Memory Information (for Peripherals and Memory) * - PLIC Interrupt ID Names and Source Mappings * - Alert ID Names and Source Mappings * - Pinmux Pin/Select Names * - Power Manager Wakeups */ #ifdef __cplusplus extern "C" { #endif % for (inst_name, if_name), region in helper.devices(): <% if_desc = inst_name if if_name is None else '{} device on {}'.format(if_name, inst_name) hex_base_addr = "0x{:X}u".format(region.base_addr) hex_size_bytes = "0x{:X}u".format(region.size_bytes) base_addr_name = region.base_addr_name().as_c_define() size_bytes_name = region.size_bytes_name().as_c_define() %>\ /** * Peripheral base address for ${if_desc} in top ${top["name"]}. * * This should be used with #mmio_region_from_addr to access the memory-mapped * registers associated with the peripheral (usually via a DIF). */ #define ${base_addr_name} ${hex_base_addr} /** * Peripheral size for ${if_desc} in top ${top["name"]}. * * This is the size (in bytes) of the peripheral's reserved memory area. All * memory-mapped registers associated with this peripheral should have an * address between #${base_addr_name} and * `${base_addr_name} + ${size_bytes_name}`. */ #define ${size_bytes_name} ${hex_size_bytes} % endfor % for name, region in helper.memories(): <% hex_base_addr = "0x{:X}u".format(region.base_addr) hex_size_bytes = "0x{:X}u".format(region.size_bytes) base_addr_name = region.base_addr_name().as_c_define() size_bytes_name = region.size_bytes_name().as_c_define() %>\ /** * Memory base address for ${name} in top ${top["name"]}. */ #define ${base_addr_name} ${hex_base_addr} /** * Memory size for ${name} in top ${top["name"]}. */ #define ${size_bytes_name} ${hex_size_bytes} % endfor /** * PLIC Interrupt Source Peripheral. * * Enumeration used to determine which peripheral asserted the corresponding * interrupt. */ ${helper.plic_sources.render()} /** * PLIC Interrupt Source. * * Enumeration of all PLIC interrupt sources. The interrupt sources belonging to * the same peripheral are guaranteed to be consecutive. */ ${helper.plic_interrupts.render()} /** * PLIC Interrupt Source to Peripheral Map * * This array is a mapping from `${helper.plic_interrupts.name.as_c_type()}` to * `${helper.plic_sources.name.as_c_type()}`. */ ${helper.plic_mapping.render_declaration()} /** * PLIC Interrupt Target. * * Enumeration used to determine which set of IE, CC, threshold registers to * access for a given interrupt target. */ ${helper.plic_targets.render()} /** * Alert Handler Source Peripheral. * * Enumeration used to determine which peripheral asserted the corresponding * alert. */ ${helper.alert_sources.render()} /** * Alert Handler Alert Source. * * Enumeration of all Alert Handler Alert Sources. The alert sources belonging to * the same peripheral are guaranteed to be consecutive. */ ${helper.alert_alerts.render()} /** * Alert Handler Alert Source to Peripheral Map * * This array is a mapping from `${helper.alert_alerts.name.as_c_type()}` to * `${helper.alert_sources.name.as_c_type()}`. */ ${helper.alert_mapping.render_declaration()} #define PINMUX_MIO_PERIPH_INSEL_IDX_OFFSET 2 // PERIPH_INSEL ranges from 0 to NUM_MIO_PADS + 2 -1} // 0 and 1 are tied to value 0 and 1 #define NUM_MIO_PADS ${top["pinmux"]["io_counts"]["muxed"]["pads"]} #define NUM_DIO_PADS ${top["pinmux"]["io_counts"]["dedicated"]["inouts"] + \ top["pinmux"]["io_counts"]["dedicated"]["inputs"] + \ top["pinmux"]["io_counts"]["dedicated"]["outputs"] } #define PINMUX_PERIPH_OUTSEL_IDX_OFFSET 3 /** * Pinmux Peripheral Input. */ ${helper.pinmux_peripheral_in.render()} /** * Pinmux MIO Input Selector. */ ${helper.pinmux_insel.render()} /** * Pinmux MIO Output. */ ${helper.pinmux_mio_out.render()} /** * Pinmux Peripheral Output Selector. */ ${helper.pinmux_outsel.render()} /** * Power Manager Wakeup Signals */ ${helper.pwrmgr_wakeups.render()} /** * Reset Manager Software Controlled Resets */ ${helper.rstmgr_sw_rsts.render()} /** * Power Manager Reset Request Signals */ ${helper.pwrmgr_reset_requests.render()} /** * Clock Manager Software-Controlled ("Gated") Clocks. * * The Software has full control over these clocks. */ ${helper.clkmgr_gateable_clocks.render()} /** * Clock Manager Software-Hinted Clocks. * * The Software has partial control over these clocks. It can ask them to stop, * but the clock manager is in control of whether the clock actually is stopped. */ ${helper.clkmgr_hintable_clocks.render()} // Header Extern Guard #ifdef __cplusplus } // extern "C" #endif #endif // _TOP_${top["name"].upper()}_H_
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 ${gencmd} <% import re import topgen.lib as lib num_mio_inputs = top['pinmux']['io_counts']['muxed']['inouts'] + \ top['pinmux']['io_counts']['muxed']['inputs'] num_mio_outputs = top['pinmux']['io_counts']['muxed']['inouts'] + \ top['pinmux']['io_counts']['muxed']['outputs'] num_mio_pads = top['pinmux']['io_counts']['muxed']['pads'] num_dio_inputs = top['pinmux']['io_counts']['dedicated']['inouts'] + \ top['pinmux']['io_counts']['dedicated']['inputs'] num_dio_outputs = top['pinmux']['io_counts']['dedicated']['inouts'] + \ top['pinmux']['io_counts']['dedicated']['outputs'] num_dio_total = top['pinmux']['io_counts']['dedicated']['inouts'] + \ top['pinmux']['io_counts']['dedicated']['inputs'] + \ top['pinmux']['io_counts']['dedicated']['outputs'] num_im = sum([x["width"] if "width" in x else 1 for x in top["inter_signal"]["external"]]) max_sigwidth = max([x["width"] if "width" in x else 1 for x in top["pinmux"]["ios"]]) max_sigwidth = len("{}".format(max_sigwidth)) clks_attr = top['clocks'] cpu_clk = top['clocks']['hier_paths']['top'] + "clk_proc_main" cpu_rst = top["reset_paths"]["sys"] dm_rst = top["reset_paths"]["lc"] esc_clk = top['clocks']['hier_paths']['top'] + "clk_io_div4_timers" esc_rst = top["reset_paths"]["sys_io_div4"] unused_resets = lib.get_unused_resets(top) unused_im_defs, undriven_im_defs = lib.get_dangling_im_def(top["inter_signal"]["definitions"]) has_toplevel_rom = False for m in top['memory']: if m['type'] == 'rom': has_toplevel_rom = True %>\ module top_${top["name"]} #( // Auto-inferred parameters % for m in top["module"]: % if not lib.is_inst(m): <% continue %> % endif % for p_exp in filter(lambda p: p.get("expose") == "true", m["param_list"]): parameter ${p_exp["type"]} ${p_exp["name_top"]} = ${p_exp["default"]}, % endfor % endfor // Manually defined parameters % if has_toplevel_rom: parameter BootRomInitFile = "", % endif parameter ibex_pkg::regfile_e IbexRegFile = ibex_pkg::RegFileFF, parameter bit IbexICache = 1, parameter bit IbexPipeLine = 0, parameter bit SecureIbex = 1 ) ( // Reset, clocks defined as part of intermodule input rst_ni, % if num_mio_pads != 0: // Multiplexed I/O input ${lib.bitarray(num_mio_pads, max_sigwidth)} mio_in_i, output logic ${lib.bitarray(num_mio_pads, max_sigwidth)} mio_out_o, output logic ${lib.bitarray(num_mio_pads, max_sigwidth)} mio_oe_o, % endif % if num_dio_total != 0: // Dedicated I/O input ${lib.bitarray(num_dio_total, max_sigwidth)} dio_in_i, output logic ${lib.bitarray(num_dio_total, max_sigwidth)} dio_out_o, output logic ${lib.bitarray(num_dio_total, max_sigwidth)} dio_oe_o, % endif % if "pinmux" in top: // pad attributes to padring output prim_pad_wrapper_pkg::pad_attr_t [pinmux_reg_pkg::NMioPads-1:0] mio_attr_o, output prim_pad_wrapper_pkg::pad_attr_t [pinmux_reg_pkg::NDioPads-1:0] dio_attr_o, % endif % if num_im != 0: // Inter-module Signal External type % for sig in top["inter_signal"]["external"]: ${"input " if sig["direction"] == "in" else "output"} ${lib.im_defname(sig)} ${lib.bitarray(sig["width"],1)} ${sig["signame"]}, % endfor // Flash specific voltages inout [1:0] flash_test_mode_a_io, inout flash_test_voltage_h_io, // OTP specific voltages inout otp_ext_voltage_h_io, % endif input scan_rst_ni, // reset used for test mode input scan_en_i, input lc_ctrl_pkg::lc_tx_t scanmode_i // lc_ctrl_pkg::On for Scan ); // JTAG IDCODE for development versions of this code. // Manufacturers of OpenTitan chips must replace this code with one of their // own IDs. // Field structure as defined in the IEEE 1149.1 (JTAG) specification, // section 12.1.1. localparam logic [31:0] JTAG_IDCODE = { 4'h0, // Version 16'h4F54, // Part Number: "OT" 11'h426, // Manufacturer Identity: Google 1'b1 // (fixed) }; import tlul_pkg::*; import top_pkg::*; import tl_main_pkg::*; import top_${top["name"]}_pkg::*; // Compile-time random constants import top_${top["name"]}_rnd_cnst_pkg::*; // Signals logic [${num_mio_inputs - 1}:0] mio_p2d; logic [${num_mio_outputs - 1}:0] mio_d2p; logic [${num_mio_outputs - 1}:0] mio_en_d2p; logic [${num_dio_total - 1}:0] dio_p2d; logic [${num_dio_total - 1}:0] dio_d2p; logic [${num_dio_total - 1}:0] dio_en_d2p; % for m in top["module"]: % if not lib.is_inst(m): <% continue %> % endif <% block = name_to_block[m['type']] inouts, inputs, outputs = block.xputs %>\ // ${m["name"]} % for p_in in inputs + inouts: logic ${lib.bitarray(p_in.bits.width(), max_sigwidth)} cio_${m["name"]}_${p_in.name}_p2d; % endfor % for p_out in outputs + inouts: logic ${lib.bitarray(p_out.bits.width(), max_sigwidth)} cio_${m["name"]}_${p_out.name}_d2p; logic ${lib.bitarray(p_out.bits.width(), max_sigwidth)} cio_${m["name"]}_${p_out.name}_en_d2p; % endfor % endfor <% # Interrupt source 0 is tied to 0 to conform RISC-V PLIC spec. # So, total number of interrupts are the number of entries in the list + 1 interrupt_num = sum([x["width"] if "width" in x else 1 for x in top["interrupt"]]) + 1 %>\ logic [${interrupt_num-1}:0] intr_vector; // Interrupt source list % for m in top["module"]: <% block = name_to_block[m['type']] %>\ % if not lib.is_inst(m): <% continue %> % endif % for intr in block.interrupts: % if intr.bits.width() != 1: logic [${intr.bits.width()-1}:0] intr_${m["name"]}_${intr.name}; % else: logic intr_${m["name"]}_${intr.name}; % endif % endfor % endfor <% add_spaces = " " * len(str((interrupt_num-1).bit_length()-1)) %> logic [0:0]${add_spaces}irq_plic; logic [0:0]${add_spaces}msip; logic [${(interrupt_num-1).bit_length()-1}:0] irq_id[1]; logic [${(interrupt_num-1).bit_length()-1}:0] unused_irq_id[1]; // this avoids lint errors assign unused_irq_id = irq_id; // Alert list prim_alert_pkg::alert_tx_t [alert_pkg::NAlerts-1:0] alert_tx; prim_alert_pkg::alert_rx_t [alert_pkg::NAlerts-1:0] alert_rx; % if not top["alert"]: for (genvar k = 0; k < alert_pkg::NAlerts; k++) begin : gen_alert_tie_off // tie off if no alerts present in the system assign alert_tx[k].alert_p = 1'b0; assign alert_tx[k].alert_n = 1'b1; end % endif ## Inter-module Definitions % if len(top["inter_signal"]["definitions"]) >= 1: // define inter-module signals % endif % for sig in top["inter_signal"]["definitions"]: ${lib.im_defname(sig)} ${lib.bitarray(sig["width"],1)} ${sig["signame"]}; % endfor ## Mixed connection to port ## Index greater than 0 means a port is assigned to an inter-module array ## whereas an index of 0 means a port is directly driven by a module // define mixed connection to port % for port in top['inter_signal']['external']: % if port['conn_type'] and port['index'] > 0: % if port['direction'] == 'in': assign ${port['netname']}[${port['index']}] = ${port['signame']}; % else: assign ${port['signame']} = ${port['netname']}[${port['index']}]; % endif % elif port['conn_type']: % if port['direction'] == 'in': assign ${port['netname']} = ${port['signame']}; % else: assign ${port['signame']} = ${port['netname']}; % endif % endif % endfor ## Partial inter-module definition tie-off // define partial inter-module tie-off % for sig in unused_im_defs: % for idx in range(sig['end_idx'], sig['width']): ${lib.im_defname(sig)} unused_${sig["signame"]}${idx}; % endfor % endfor // assign partial inter-module tie-off % for sig in unused_im_defs: % for idx in range(sig['end_idx'], sig['width']): assign unused_${sig["signame"]}${idx} = ${sig["signame"]}[${idx}]; % endfor % endfor % for sig in undriven_im_defs: % for idx in range(sig['end_idx'], sig['width']): assign ${sig["signame"]}[${idx}] = ${sig["default"]}; % endfor % endfor ## Inter-module signal collection // Unused reset signals % for k, v in unused_resets.items(): logic unused_d${v.lower()}_rst_${k}; % endfor % for k, v in unused_resets.items(): assign unused_d${v.lower()}_rst_${k} = ${lib.get_reset_path(k, v, top['resets'])}; % endfor // Non-debug module reset == reset for everything except for the debug module logic ndmreset_req; // debug request from rv_dm to core logic debug_req; // processor core rv_core_ibex #( .PMPEnable (1), .PMPGranularity (0), // 2^(PMPGranularity+2) == 4 byte granularity .PMPNumRegions (16), .MHPMCounterNum (10), .MHPMCounterWidth (32), .RV32E (0), .RV32M (ibex_pkg::RV32MSingleCycle), .RV32B (ibex_pkg::RV32BNone), .RegFile (IbexRegFile), .BranchTargetALU (1), .WritebackStage (1), .ICache (IbexICache), .ICacheECC (1), .BranchPredictor (0), .DbgTriggerEn (1), .SecureIbex (SecureIbex), .DmHaltAddr (ADDR_SPACE_DEBUG_MEM + dm::HaltAddress[31:0]), .DmExceptionAddr (ADDR_SPACE_DEBUG_MEM + dm::ExceptionAddress[31:0]), .PipeLine (IbexPipeLine) ) u_rv_core_ibex ( // clock and reset .clk_i (${cpu_clk}), .rst_ni (${cpu_rst}[rstmgr_pkg::Domain0Sel]), .clk_esc_i (${esc_clk}), .rst_esc_ni (${esc_rst}[rstmgr_pkg::Domain0Sel]), .ram_cfg_i (ast_ram_1p_cfg), // static pinning .hart_id_i (32'b0), .boot_addr_i (ADDR_SPACE_ROM_CTRL__ROM), // TL-UL buses .tl_i_o (main_tl_corei_req), .tl_i_i (main_tl_corei_rsp), .tl_d_o (main_tl_cored_req), .tl_d_i (main_tl_cored_rsp), // interrupts .irq_software_i (msip), .irq_timer_i (intr_rv_timer_timer_expired_0_0), .irq_external_i (irq_plic), // escalation input from alert handler (NMI) .esc_tx_i (alert_handler_esc_tx[0]), .esc_rx_o (alert_handler_esc_rx[0]), // debug interface .debug_req_i (debug_req), // crash dump interface .crash_dump_o (rv_core_ibex_crash_dump), // CPU control signals .lc_cpu_en_i (lc_ctrl_lc_cpu_en), .pwrmgr_cpu_en_i (pwrmgr_aon_fetch_en), .core_sleep_o (pwrmgr_aon_pwr_cpu.core_sleeping), // dft bypass .scan_rst_ni, .scanmode_i ); // Debug Module (RISC-V Debug Spec 0.13) // rv_dm #( .NrHarts (1), .IdcodeValue (JTAG_IDCODE) ) u_dm_top ( .clk_i (${cpu_clk}), .rst_ni (${dm_rst}[rstmgr_pkg::Domain0Sel]), .hw_debug_en_i (lc_ctrl_lc_hw_debug_en), .scanmode_i, .scan_rst_ni, .ndmreset_o (ndmreset_req), .dmactive_o (), .debug_req_o (debug_req), .unavailable_i (1'b0), // bus device with debug memory (for execution-based debug) .tl_d_i (main_tl_debug_mem_req), .tl_d_o (main_tl_debug_mem_rsp), // bus host (for system bus accesses, SBA) .tl_h_o (main_tl_dm_sba_req), .tl_h_i (main_tl_dm_sba_rsp), //JTAG .jtag_req_i (pinmux_aon_rv_jtag_req), .jtag_rsp_o (pinmux_aon_rv_jtag_rsp) ); assign rstmgr_aon_cpu.ndmreset_req = ndmreset_req; assign rstmgr_aon_cpu.rst_cpu_n = ${top["reset_paths"]["sys"]}[rstmgr_pkg::Domain0Sel]; ## Memory Instantiation % for m in top["memory"]: <% resets = m['reset_connections'] clocks = m['clock_connections'] %>\ % if m["type"] == "ram_1p_scr": <% data_width = int(top["datawidth"]) full_data_width = data_width + int(m["integ_width"]) dw_byte = data_width // 8 addr_width = ((int(m["size"], 0) // dw_byte) -1).bit_length() sram_depth = (int(m["size"], 0) // dw_byte) max_char = len(str(max(data_width, addr_width))) %>\ // sram device logic ${lib.bitarray(1, max_char)} ${m["name"]}_req; logic ${lib.bitarray(1, max_char)} ${m["name"]}_gnt; logic ${lib.bitarray(1, max_char)} ${m["name"]}_we; logic ${lib.bitarray(1, max_char)} ${m["name"]}_intg_err; logic ${lib.bitarray(addr_width, max_char)} ${m["name"]}_addr; logic ${lib.bitarray(full_data_width, max_char)} ${m["name"]}_wdata; logic ${lib.bitarray(full_data_width, max_char)} ${m["name"]}_wmask; logic ${lib.bitarray(full_data_width, max_char)} ${m["name"]}_rdata; logic ${lib.bitarray(1, max_char)} ${m["name"]}_rvalid; logic ${lib.bitarray(2, max_char)} ${m["name"]}_rerror; tlul_adapter_sram #( .SramAw(${addr_width}), .SramDw(${data_width}), .Outstanding(2), .CmdIntgCheck(1), .EnableRspIntgGen(1), .EnableDataIntgGen(0), .EnableDataIntgPt(1) ) u_tl_adapter_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .tl_i (${m["name"]}_tl_req), .tl_o (${m["name"]}_tl_rsp), .en_ifetch_i (${m["inter_signal_list"][3]["top_signame"]}), .req_o (${m["name"]}_req), .req_type_o (), .gnt_i (${m["name"]}_gnt), .we_o (${m["name"]}_we), .addr_o (${m["name"]}_addr), .wdata_o (${m["name"]}_wdata), .wmask_o (${m["name"]}_wmask), .intg_error_o(${m["name"]}_intg_err), .rdata_i (${m["name"]}_rdata), .rvalid_i (${m["name"]}_rvalid), .rerror_i (${m["name"]}_rerror) ); <% mem_name = m["name"].split("_") mem_name = lib.Name(mem_name[1:]) %>\ prim_ram_1p_scr #( .Width(${full_data_width}), .Depth(${sram_depth}), .EnableParity(0), .LfsrWidth(${data_width}), .StatePerm(RndCnstSramCtrl${mem_name.as_camel_case()}SramLfsrPerm), .DataBitsPerMask(1), // TODO: Temporary change to ensure byte updates can still be done .DiffWidth(8) ) u_ram1p_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .key_valid_i (${m["inter_signal_list"][1]["top_signame"]}_req.valid), .key_i (${m["inter_signal_list"][1]["top_signame"]}_req.key), .nonce_i (${m["inter_signal_list"][1]["top_signame"]}_req.nonce), .init_req_i (${m["inter_signal_list"][2]["top_signame"]}_req.req), .init_seed_i (${m["inter_signal_list"][2]["top_signame"]}_req.seed), .init_ack_o (${m["inter_signal_list"][2]["top_signame"]}_rsp.ack), .req_i (${m["name"]}_req), .intg_error_i(${m["name"]}_intg_err), .gnt_o (${m["name"]}_gnt), .write_i (${m["name"]}_we), .addr_i (${m["name"]}_addr), .wdata_i (${m["name"]}_wdata), .wmask_i (${m["name"]}_wmask), .rdata_o (${m["name"]}_rdata), .rvalid_o (${m["name"]}_rvalid), .rerror_o (${m["name"]}_rerror), .raddr_o (${m["inter_signal_list"][1]["top_signame"]}_rsp.raddr), .intg_error_o(${m["inter_signal_list"][4]["top_signame"]}), .cfg_i (ram_1p_cfg_i) ); assign ${m["inter_signal_list"][1]["top_signame"]}_rsp.rerror = ${m["name"]}_rerror; % elif m["type"] == "rom": <% data_width = int(top["datawidth"]) full_data_width = data_width + int(m['integ_width']) dw_byte = data_width // 8 addr_width = ((int(m["size"], 0) // dw_byte) -1).bit_length() rom_depth = (int(m["size"], 0) // dw_byte) max_char = len(str(max(data_width, addr_width))) %>\ // ROM device logic ${lib.bitarray(1, max_char)} ${m["name"]}_req; logic ${lib.bitarray(addr_width, max_char)} ${m["name"]}_addr; logic ${lib.bitarray(full_data_width, max_char)} ${m["name"]}_rdata; logic ${lib.bitarray(1, max_char)} ${m["name"]}_rvalid; tlul_adapter_sram #( .SramAw(${addr_width}), .SramDw(${data_width}), .Outstanding(2), .ErrOnWrite(1), .CmdIntgCheck(1), .EnableRspIntgGen(1), .EnableDataIntgGen(1) // TODO: Needs to be updated for intgerity passthrough ) u_tl_adapter_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .tl_i (${m["name"]}_tl_req), .tl_o (${m["name"]}_tl_rsp), .en_ifetch_i (tlul_pkg::InstrEn), .req_o (${m["name"]}_req), .req_type_o (), .gnt_i (1'b1), // Always grant as only one requester exists .we_o (), .addr_o (${m["name"]}_addr), .wdata_o (), .wmask_o (), .intg_error_o(), // Connect to ROM checker and ROM scramble later .rdata_i (${m["name"]}_rdata[${data_width-1}:0]), .rvalid_i (${m["name"]}_rvalid), .rerror_i (2'b00) ); prim_rom_adv #( .Width(${full_data_width}), .Depth(${rom_depth}), .MemInitFile(BootRomInitFile) ) u_rom_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .req_i (${m["name"]}_req), .addr_i (${m["name"]}_addr), .rdata_o (${m["name"]}_rdata), .rvalid_o (${m["name"]}_rvalid), .cfg_i (rom_cfg_i) ); % elif m["type"] == "eflash": // host to flash communication logic flash_host_req; tlul_pkg::tl_type_e flash_host_req_type; logic flash_host_req_rdy; logic flash_host_req_done; logic flash_host_rderr; logic [flash_ctrl_pkg::BusWidth-1:0] flash_host_rdata; logic [flash_ctrl_pkg::BusAddrW-1:0] flash_host_addr; logic flash_host_intg_err; tlul_adapter_sram #( .SramAw(flash_ctrl_pkg::BusAddrW), .SramDw(flash_ctrl_pkg::BusWidth), .Outstanding(2), .ByteAccess(0), .ErrOnWrite(1), .CmdIntgCheck(1), .EnableRspIntgGen(1), .EnableDataIntgGen(1) ) u_tl_adapter_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .tl_i (${m["name"]}_tl_req), .tl_o (${m["name"]}_tl_rsp), .en_ifetch_i (tlul_pkg::InstrEn), // tie this to secure boot somehow .req_o (flash_host_req), .req_type_o (flash_host_req_type), .gnt_i (flash_host_req_rdy), .we_o (), .addr_o (flash_host_addr), .wdata_o (), .wmask_o (), .intg_error_o(flash_host_intg_err), .rdata_i (flash_host_rdata), .rvalid_i (flash_host_req_done), .rerror_i ({flash_host_rderr,1'b0}) ); flash_phy u_flash_${m["name"]} ( % for key in clocks: .${key} (${clocks[key]}), % endfor % for key, value in resets.items(): .${key} (${value}), % endfor .host_req_i (flash_host_req), .host_intg_err_i (flash_host_intg_err), .host_req_type_i (flash_host_req_type), .host_addr_i (flash_host_addr), .host_req_rdy_o (flash_host_req_rdy), .host_req_done_o (flash_host_req_done), .host_rderr_o (flash_host_rderr), .host_rdata_o (flash_host_rdata), .flash_ctrl_i (${m["inter_signal_list"][0]["top_signame"]}_req), .flash_ctrl_o (${m["inter_signal_list"][0]["top_signame"]}_rsp), .lc_nvm_debug_en_i (${m["inter_signal_list"][2]["top_signame"]}), .flash_bist_enable_i, .flash_power_down_h_i, .flash_power_ready_h_i, .flash_test_mode_a_io, .flash_test_voltage_h_io, .flash_alert_o, .scanmode_i, .scan_en_i, .scan_rst_ni ); % else: // flash memory is embedded within controller % endif % endfor ## Peripheral Instantiation <% alert_idx = 0 %> % for m in top["module"]: <% if not lib.is_inst(m): continue block = name_to_block[m['type']] inouts, inputs, outputs = block.xputs port_list = inputs + outputs + inouts max_sigwidth = max(len(x.name) for x in port_list) if port_list else 0 max_intrwidth = (max(len(x.name) for x in block.interrupts) if block.interrupts else 0) %>\ % if m["param_list"] or block.alerts: ${m["type"]} #( % if block.alerts: <% w = len(block.alerts) slice = str(alert_idx+w-1) + ":" + str(alert_idx) %>\ .AlertAsyncOn(alert_handler_reg_pkg::AsyncOn[${slice}])${"," if m["param_list"] else ""} % endif % for i in m["param_list"]: .${i["name"]}(${i["name_top" if i.get("expose") == "true" or i.get("randtype", "none") != "none" else "default"]})${"," if not loop.last else ""} % endfor ) u_${m["name"]} ( % else: ${m["type"]} u_${m["name"]} ( % endif % for p_in in inputs + inouts: % if loop.first: // Input % endif .${lib.ljust("cio_"+p_in.name+"_i",max_sigwidth+9)} (cio_${m["name"]}_${p_in.name}_p2d), % endfor % for p_out in outputs + inouts: % if loop.first: // Output % endif .${lib.ljust("cio_"+p_out.name+"_o", max_sigwidth+9)} (cio_${m["name"]}_${p_out.name}_d2p), .${lib.ljust("cio_"+p_out.name+"_en_o",max_sigwidth+9)} (cio_${m["name"]}_${p_out.name}_en_d2p), % endfor % for intr in block.interrupts: % if loop.first: // Interrupt % endif .${lib.ljust("intr_"+intr.name+"_o",max_intrwidth+7)} (intr_${m["name"]}_${intr.name}), % endfor % if block.alerts: % for alert in block.alerts: // [${alert_idx}]: ${alert.name}<% alert_idx += 1 %> % endfor .alert_tx_o ( alert_tx[${slice}] ), .alert_rx_i ( alert_rx[${slice}] ), % endif ## TODO: Inter-module Connection % if m.get('inter_signal_list'): // Inter-module signals % for sig in m['inter_signal_list']: ## TODO: handle below condition in lib.py % if sig['type'] == "req_rsp": .${lib.im_portname(sig,"req")}(${lib.im_netname(sig, "req")}), .${lib.im_portname(sig,"rsp")}(${lib.im_netname(sig, "rsp")}), % elif sig['type'] == "uni": ## TODO: Broadcast type ## TODO: default for logic type .${lib.im_portname(sig)}(${lib.im_netname(sig)}), % endif % endfor % endif % if m["type"] == "rv_plic": .intr_src_i (intr_vector), .irq_o (irq_plic), .irq_id_o (irq_id), .msip_o (msip), % endif % if m["type"] == "pinmux": .periph_to_mio_i (mio_d2p ), .periph_to_mio_oe_i (mio_en_d2p ), .mio_to_periph_o (mio_p2d ), .mio_attr_o, .mio_out_o, .mio_oe_o, .mio_in_i, .periph_to_dio_i (dio_d2p ), .periph_to_dio_oe_i (dio_en_d2p ), .dio_to_periph_o (dio_p2d ), .dio_attr_o, .dio_out_o, .dio_oe_o, .dio_in_i, % endif % if m["type"] == "alert_handler": // alert signals .alert_rx_o ( alert_rx ), .alert_tx_i ( alert_tx ), % endif % if m["type"] == "otp_ctrl": .otp_ext_voltage_h_io, % endif % if block.scan: .scanmode_i, % endif % if block.scan_reset: .scan_rst_ni, % endif % if block.scan_en: .scan_en_i, % endif // Clock and reset connections % for k, v in m["clock_connections"].items(): .${k} (${v}), % endfor % for k, v in m["reset_connections"].items(): .${k} (${v})${"," if not loop.last else ""} % endfor ); % endfor // interrupt assignments <% base = interrupt_num %>\ assign intr_vector = { % for intr in top["interrupt"][::-1]: <% base -= intr["width"] %>\ intr_${intr["name"]}, // IDs [${base} +: ${intr['width']}] % endfor 1'b 0 // ID [0 +: 1] is a special case and tied to zero. }; // TL-UL Crossbar % for xbar in top["xbar"]: <% name_len = max([len(x["name"]) for x in xbar["nodes"]]); %>\ xbar_${xbar["name"]} u_xbar_${xbar["name"]} ( % for k, v in xbar["clock_connections"].items(): .${k} (${v}), % endfor % for k, v in xbar["reset_connections"].items(): .${k} (${v}), % endfor ## Inter-module signal % for sig in xbar["inter_signal_list"]: <% assert sig['type'] == "req_rsp" %>\ // port: ${sig['name']} .${lib.im_portname(sig,"req")}(${lib.im_netname(sig, "req")}), .${lib.im_portname(sig,"rsp")}(${lib.im_netname(sig, "rsp")}), % endfor .scanmode_i ); % endfor % if "pinmux" in top: // Pinmux connections // All muxed inputs % for sig in top["pinmux"]["ios"]: % if sig["connection"] == "muxed" and sig["type"] in ["inout", "input"]: <% literal = lib.get_io_enum_literal(sig, 'mio_in') %>\ assign cio_${sig["name"]}_p2d${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""} = mio_p2d[${literal}]; % endif % endfor // All muxed outputs % for sig in top["pinmux"]["ios"]: % if sig["connection"] == "muxed" and sig["type"] in ["inout", "output"]: <% literal = lib.get_io_enum_literal(sig, 'mio_out') %>\ assign mio_d2p[${literal}] = cio_${sig["name"]}_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % endif % endfor // All muxed output enables % for sig in top["pinmux"]["ios"]: % if sig["connection"] == "muxed" and sig["type"] in ["inout", "output"]: <% literal = lib.get_io_enum_literal(sig, 'mio_out') %>\ assign mio_en_d2p[${literal}] = cio_${sig["name"]}_en_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % endif % endfor // All dedicated inputs <% idx = 0 %>\ logic [${num_dio_total-1}:0] unused_dio_p2d; assign unused_dio_p2d = dio_p2d; % for sig in top["pinmux"]["ios"]: <% literal = lib.get_io_enum_literal(sig, 'dio') %>\ % if sig["connection"] != "muxed" and sig["type"] in ["inout"]: assign cio_${sig["name"]}_p2d${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""} = dio_p2d[${literal}]; % elif sig["connection"] != "muxed" and sig["type"] in ["input"]: assign cio_${sig["name"]}_p2d${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""} = dio_p2d[${literal}]; % endif % endfor // All dedicated outputs % for sig in top["pinmux"]["ios"]: <% literal = lib.get_io_enum_literal(sig, 'dio') %>\ % if sig["connection"] != "muxed" and sig["type"] in ["inout"]: assign dio_d2p[${literal}] = cio_${sig["name"]}_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % elif sig["connection"] != "muxed" and sig["type"] in ["input"]: assign dio_d2p[${literal}] = 1'b0; % elif sig["connection"] != "muxed" and sig["type"] in ["output"]: assign dio_d2p[${literal}] = cio_${sig["name"]}_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % endif % endfor // All dedicated output enables % for sig in top["pinmux"]["ios"]: <% literal = lib.get_io_enum_literal(sig, 'dio') %>\ % if sig["connection"] != "muxed" and sig["type"] in ["inout"]: assign dio_en_d2p[${literal}] = cio_${sig["name"]}_en_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % elif sig["connection"] != "muxed" and sig["type"] in ["input"]: assign dio_en_d2p[${literal}] = 1'b0; % elif sig["connection"] != "muxed" and sig["type"] in ["output"]: assign dio_en_d2p[${literal}] = cio_${sig["name"]}_en_d2p${"[" + str(sig["idx"]) +"]" if sig["idx"] !=-1 else ""}; % endif % endfor % endif // make sure scanmode_i is never X (including during reset) `ASSERT_KNOWN(scanmodeKnown, scanmode_i, clk_main_i, 0) endmodule
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #ifndef _TOP_${top["name"].upper()}_MEMORY_H_ #define _TOP_${top["name"].upper()}_MEMORY_H_ /** * @file * @brief Assembler-only Top-Specific Definitions. * * This file contains preprocessor definitions for use within assembly code. * * These are not shared with C/C++ code because these are only allowed to be * preprocessor definitions, no data or type declarations are allowed. The * assembler is also stricter about literals (not allowing suffixes for * signed/unsigned which are sensible to use for unsigned values in C/C++). */ // Include guard for assembler #ifdef __ASSEMBLER__ /** * Memory base address for rom in top earlgrey. */ #define TOP_EARLGREY_ROM_BASE_ADDR 0x00008000 /** * Memory size for rom in top earlgrey. */ #define TOP_EARLGREY_ROM_SIZE_BYTES 0x4000 % for m in top["memory"]: /** * Memory base address for ${m["name"]} in top ${top["name"]}. */ #define TOP_${top["name"].upper()}_${m["name"].upper()}_BASE_ADDR ${m["base_addr"]} /** * Memory size for ${m["name"]} in top ${top["name"]}. */ #define TOP_${top["name"].upper()}_${m["name"].upper()}_SIZE_BYTES ${m["size"]} % endfor % for (inst_name, if_name), region in helper.devices(): <% if_desc = inst_name if if_name is None else '{} device on {}'.format(if_name, inst_name) hex_base_addr = "0x{:X}".format(region.base_addr) base_addr_name = region.base_addr_name().as_c_define() %>\ /** * Peripheral base address for ${if_desc} in top ${top["name"]}. * * This should be used with #mmio_region_from_addr to access the memory-mapped * registers associated with the peripheral (usually via a DIF). */ #define ${base_addr_name} ${hex_base_addr} % endfor #endif // __ASSEMBLER__ #endif // _TOP_${top["name"].upper()}_MEMORY_H_
/* Copyright lowRISC contributors. */ /* Licensed under the Apache License, Version 2.0, see LICENSE for details. */ /* SPDX-License-Identifier: Apache-2.0 */ <%! def memory_to_flags(memory): memory_type = memory["type"] memory_access = memory.get("swaccess", "rw") assert memory_access in ["ro", "rw"] flags_str = "" if memory_access == "ro": flags_str += "r" else: flags_str += "rw" if memory_type in ["rom", "eflash"]: flags_str += "x" return flags_str %>\ /** * Partial linker script for chip memory configuration. */ MEMORY { rom(rx) : ORIGIN = 0x00008000, LENGTH = 0x4000 % for m in top["memory"]: ${m["name"]}(${memory_to_flags(m)}) : ORIGIN = ${m["base_addr"]}, LENGTH = ${m["size"]} % endfor }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 ${gencmd} <% import topgen.lib as lib %>\ package top_${top["name"]}_pkg; % for (inst_name, if_name), region in helper.devices(): <% if_desc = inst_name if if_name is None else '{} device on {}'.format(if_name, inst_name) hex_base_addr = "32'h{:X}".format(region.base_addr) hex_size_bytes = "32'h{:X}".format(region.size_bytes) %>\ /** * Peripheral base address for ${if_desc} in top ${top["name"]}. */ parameter int unsigned ${region.base_addr_name().as_c_define()} = ${hex_base_addr}; /** * Peripheral size in bytes for ${if_desc} in top ${top["name"]}. */ parameter int unsigned ${region.size_bytes_name().as_c_define()} = ${hex_size_bytes}; % endfor % for name, region in helper.memories(): <% hex_base_addr = "32'h{:x}".format(region.base_addr) hex_size_bytes = "32'h{:x}".format(region.size_bytes) %>\ /** * Memory base address for ${name} in top ${top["name"]}. */ parameter int unsigned ${region.base_addr_name().as_c_define()} = ${hex_base_addr}; /** * Memory size for ${name} in top ${top["name"]}. */ parameter int unsigned ${region.size_bytes_name().as_c_define()} = ${hex_size_bytes}; % endfor // Enumeration of IO power domains. // Only used in ASIC target. typedef enum logic [${len(top["pinout"]["banks"]).bit_length()-1}:0] { % for bank in top["pinout"]["banks"]: ${lib.Name(['io', 'bank', bank]).as_camel_case()} = ${loop.index}, % endfor IoBankCount = ${len(top["pinout"]["banks"])} } pwr_dom_e; // Enumeration for MIO signals on the top-level. typedef enum int unsigned { % for sig in top["pinmux"]["ios"]: % if sig['type'] in ['inout', 'input'] and sig['connection'] == 'muxed': ${lib.get_io_enum_literal(sig, 'mio_in')} = ${sig['glob_idx']}, % endif % endfor <% total = top["pinmux"]['io_counts']['muxed']['inouts'] + \ top["pinmux"]['io_counts']['muxed']['inputs'] %>\ ${lib.Name.from_snake_case("mio_in_count").as_camel_case()} = ${total} } mio_in_e; typedef enum { % for sig in top["pinmux"]["ios"]: % if sig['type'] in ['inout', 'output'] and sig['connection'] == 'muxed': ${lib.get_io_enum_literal(sig, 'mio_out')} = ${sig['glob_idx']}, % endif % endfor <% total = top["pinmux"]['io_counts']['muxed']['inouts'] + \ top["pinmux"]['io_counts']['muxed']['outputs'] %>\ ${lib.Name.from_snake_case("mio_out_count").as_camel_case()} = ${total} } mio_out_e; // Enumeration for DIO signals, used on both the top and chip-levels. typedef enum int unsigned { % for sig in top["pinmux"]["ios"]: % if sig['connection'] != 'muxed': ${lib.get_io_enum_literal(sig, 'dio')} = ${sig['glob_idx']}, % endif % endfor <% total = top["pinmux"]['io_counts']['dedicated']['inouts'] + \ top["pinmux"]['io_counts']['dedicated']['inputs'] + \ top["pinmux"]['io_counts']['dedicated']['outputs'] %>\ ${lib.Name.from_snake_case("dio_count").as_camel_case()} = ${total} } dio_e; // Raw MIO/DIO input array indices on chip-level. // TODO: Does not account for target specific stubbed/added pads. // Need to make a target-specific package for those. typedef enum int unsigned { % for pad in top["pinout"]["pads"]: % if pad["connection"] == "muxed": ${lib.Name.from_snake_case("mio_pad_" + pad["name"]).as_camel_case()} = ${pad["idx"]}, % endif % endfor ${lib.Name.from_snake_case("mio_pad_count").as_camel_case()} } mio_pad_e; typedef enum int unsigned { % for pad in top["pinout"]["pads"]: % if pad["connection"] != "muxed": ${lib.Name.from_snake_case("dio_pad_" + pad["name"]).as_camel_case()} = ${pad["idx"]}, % endif % endfor ${lib.Name.from_snake_case("dio_pad_count").as_camel_case()} } dio_pad_e; // TODO: Enumeration for PLIC Interrupt source peripheral. // TODO: Enumeration for PLIC Interrupt Ids. endpackage
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 ${gencmd} <% def make_blocked_sv_literal(hexstr, randwidth): """This chops the random hexstring into manageable blocks of 64 chars such that the lines do not get too long. """ # Make all-caps and drop '0x' preamble hexstr = str(hexstr[2:]).upper() # Block width in hex chars blockwidth = 64 remainder = randwidth % (4*blockwidth) numbits = remainder if remainder else 4*blockwidth idx = 0 hexblocks = [] while randwidth > 0: hexstr = hexstr[idx:] randwidth -= numbits idx = (numbits + 3) // 4 hexblocks.append(str(numbits) + "'h" + hexstr[0:idx]) numbits = 4*blockwidth return hexblocks %> package top_${top["name"]}_rnd_cnst_pkg; % for m in top["module"]: % for p in filter(lambda p: p.get("randtype") in ["data", "perm"], m["param_list"]): % if loop.first: //////////////////////////////////////////// // ${m['name']} //////////////////////////////////////////// % endif // ${p['desc']} parameter ${p["type"]} ${p["name_top"]} = { % for block in make_blocked_sv_literal(p["default"], p["randwidth"]): ${block}${"" if loop.last else ","} % endfor }; % endfor % endfor endpackage : top_${top["name"]}_rnd_cnst_pkg
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // xbar_env_pkg__params generated by `topgen.py` tool <% from collections import OrderedDict def is_device_a_xbar(dev_name): for xbar in top["xbar"]: if xbar["name"] == dev_name: return 1 return 0 # recursively find all non-xbar devices under this xbar def get_xbar_edge_nodes(xbar_name): edge_devices = [] for xbar in top["xbar"]: if xbar["name"] == xbar_name: for host, devices in xbar["connections"].items(): for dev_name in devices: if is_device_a_xbar(dev_name): edge_devices.extend(get_xbar_edge_nodes()) else: edge_devices.append(dev_name) return edge_devices # find device xbar and assign all its device nodes to it: "peri" -> "uart, gpio, ..." xbar_device_dict = OrderedDict() for xbar in top["xbar"]: for n in xbar["nodes"]: if n["type"] == "device" and n["xbar"]: xbar_device_dict[n["name"]] = get_xbar_edge_nodes(n["name"]) # create the mapping: host with the corresponding devices map host_dev_map = OrderedDict() for host, devices in top["xbar"][0]["connections"].items(): dev_list = [] for dev in devices: if dev not in xbar_device_dict.keys(): dev_list.append(dev) else: dev_list.extend(xbar_device_dict[dev]) host_dev_map[host] = dev_list %>\ // List of Xbar device memory map tl_device_t xbar_devices[$] = '{ % for xbar in top["xbar"]: % for device in xbar["nodes"]: % if device["type"] == "device" and not device["xbar"]: '{"${device["name"].replace('.', '__')}", '{ % for addr in device["addr_range"]: <% start_addr = int(addr["base_addr"], 0) end_addr = start_addr + int(addr["size_byte"], 0) - 1 %>\ '{32'h${"%08x" % start_addr}, 32'h${"%08x" % end_addr}}${"," if not loop.last else ""} % endfor }}${"," if not loop.last or xbar != top["xbar"][-1] else "};"} % endif % endfor % endfor // List of Xbar hosts tl_host_t xbar_hosts[$] = '{ % for host in host_dev_map.keys(): '{"${host}", ${loop.index}, '{ <% host_devices = host_dev_map[host]; %>\ % for device in host_devices: % if loop.last: "${device}"}} % else: "${device}", % endif % endfor % if loop.last: }; % else: , % endif % endfor
From 9d8c19415867127950c8397e9e58706a712592b2 Mon Sep 17 00:00:00 2001 From: Manuel Eggimann <[email protected]> Date: Wed, 5 May 2021 21:41:26 +0200 Subject: [PATCH] Add reg_interface support This commit is a manual rebase of the original patches on top of the upstream master --- bus_interfaces.py | 20 +++++-- fpv_csr.sv.tpl | 5 ++ reg_top.sv.tpl | 135 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 143 insertions(+), 17 deletions(-) diff --git a/bus_interfaces.py b/bus_interfaces.py index 40182fb87..37c5818e1 100644 --- a/bus_interfaces.py +++ b/bus_interfaces.py @@ -3,19 +3,28 @@ # SPDX-License-Identifier: Apache-2.0 '''Code representing a list of bus interfaces for a block''' - +from enum import Enum from typing import Dict, List, Optional, Tuple from .inter_signal import InterSignal from .lib import check_list, check_keys, check_str, check_optional_str +class BusProtocol(Enum): + TLUL = "tlul" + REG_IFACE = "reg_iface" + + @classmethod + def has_value(cls, v): + return v in cls._value2member_map_ + class BusInterfaces: def __init__(self, has_unnamed_host: bool, named_hosts: List[str], has_unnamed_device: bool, - named_devices: List[str]): + named_devices: List[str], + interface_list: List[Dict]): assert has_unnamed_device or named_devices assert len(named_hosts) == len(set(named_hosts)) assert len(named_devices) == len(set(named_devices)) @@ -24,11 +33,13 @@ class BusInterfaces: self.named_hosts = named_hosts self.has_unnamed_device = has_unnamed_device self.named_devices = named_devices + self.interface_list = interface_list @staticmethod def from_raw(raw: object, where: str) -> 'BusInterfaces': has_unnamed_host = False named_hosts = [] + interface_list = [] has_unnamed_device = False named_devices = [] @@ -41,7 +52,7 @@ class BusInterfaces: protocol = check_str(ed['protocol'], 'protocol field of ' + entry_what) - if protocol != 'tlul': + if not BusProtocol.has_value(protocol): raise ValueError('Unknown protocol {!r} at {}' .format(protocol, entry_what)) @@ -80,12 +91,13 @@ class BusInterfaces: 'with name {!r} at {}' .format(name, where)) named_devices.append(name) + interface_list.append({'name': name, 'protocol': BusProtocol(protocol), 'is_host': direction=='host'}) if not (has_unnamed_device or named_devices): raise ValueError('No device interface at ' + where) return BusInterfaces(has_unnamed_host, named_hosts, - has_unnamed_device, named_devices) + has_unnamed_device, named_devices, interface_list) def has_host(self) -> bool: return bool(self.has_unnamed_host or self.named_hosts) diff --git a/fpv_csr.sv.tpl b/fpv_csr.sv.tpl index 5308da8a6..01f20c738 100644 --- a/fpv_csr.sv.tpl +++ b/fpv_csr.sv.tpl @@ -12,6 +12,7 @@ from topgen import lib lblock = block.name.lower() + use_reg_iface = any([interface['protocol'] == BusProtocol.REG_IFACE and not interace['is_host'] for interface in block.bus_interfaces.interface_list]) # This template shouldn't be instantiated if the device interface # doesn't actually have any registers. @@ -20,7 +21,11 @@ %>\ <%def name="construct_classes(block)">\ +% if use_reg_iface: +`include "common_cells/assertions.svh" +% else: `include "prim_assert.sv" +% endif `ifdef UVM import uvm_pkg::*; `endif diff --git a/reg_top.sv.tpl b/reg_top.sv.tpl index 8b4e8d3be..4cd9036a2 100644 --- a/reg_top.sv.tpl +++ b/reg_top.sv.tpl @@ -9,6 +9,8 @@ from reggen.lib import get_basename from reggen.register import Register from reggen.multi_register import MultiRegister + from reggen.ip_block import IpBlock + from reggen.bus_interfaces import BusProtocol num_wins = len(rb.windows) num_wins_width = ((num_wins+1).bit_length()) - 1 @@ -36,24 +38,56 @@ rb.windows[0].offset != 0 or rb.windows[0].size_in_bytes != (1 << addr_width))) + # Check if the interface protocol is reg_interface + use_reg_iface = any([interface['protocol'] == BusProtocol.REG_IFACE and not interface['is_host'] for interface in block.bus_interfaces.interface_list]) + reg_intf_req = "reg_req_t" + reg_intf_rsp = "reg_rsp_t" common_data_intg_gen = 0 if rb.has_data_intg_passthru else 1 adapt_data_intg_gen = 1 if rb.has_data_intg_passthru else 0 assert common_data_intg_gen != adapt_data_intg_gen %> + +% if use_reg_iface: +`include "common_cells/assertions.svh" +% else: `include "prim_assert.sv" +% endif -module ${mod_name} ( +module ${mod_name} \ +% if use_reg_iface: +#( + parameter type reg_req_t = logic, + parameter type reg_rsp_t = logic, + parameter int AW = ${addr_width} +) \ +% else: + % if needs_aw: +#( + parameter int AW = ${addr_width} +) \ + % endif +% endif +( input clk_i, input rst_ni, - +% if use_reg_iface: + input ${reg_intf_req} reg_req_i, + output ${reg_intf_rsp} reg_rsp_o, +% else: input tlul_pkg::tl_h2d_t tl_i, output tlul_pkg::tl_d2h_t tl_o, +% endif % if num_wins != 0: // Output port for window +% if use_reg_iface: + output ${reg_intf_req} [${num_wins}-1:0] reg_req_win_o, + input ${reg_intf_rsp} [${num_wins}-1:0] reg_rsp_win_i, +% else: output tlul_pkg::tl_h2d_t tl_win_o [${num_wins}], input tlul_pkg::tl_d2h_t tl_win_i [${num_wins}], +% endif % endif // To HW @@ -64,8 +98,10 @@ module ${mod_name} ( input ${lblock}_reg_pkg::${hw2reg_t} hw2reg, // Read % endif +% if not use_reg_iface: // Integrity check errors output logic intg_err_o, +% endif // Config input devmode_i // If 1, explicit error return for unmapped register access @@ -73,9 +109,6 @@ module ${mod_name} ( import ${lblock}_reg_pkg::* ; -% if needs_aw: - localparam int AW = ${addr_width}; -% endif % if rb.all_regs: localparam int DW = ${block.regwidth}; localparam int DBW = DW/8; // Byte Width @@ -93,10 +126,17 @@ module ${mod_name} ( logic [DW-1:0] reg_rdata_next; +% if use_reg_iface: + // Below register interface can be changed + reg_req_t reg_intf_req; + reg_rsp_t reg_intf_rsp; +% else: tlul_pkg::tl_h2d_t tl_reg_h2d; tlul_pkg::tl_d2h_t tl_reg_d2h; % endif +% endif +% if not use_reg_iface: // incoming payload check logic intg_err; tlul_cmd_intg_chk u_chk ( @@ -126,23 +166,63 @@ module ${mod_name} ( .tl_i(tl_o_pre), .tl_o ); +% endif % if num_dsp == 1: ## Either no windows (and just registers) or no registers and only ## one window. % if num_wins == 0: + % if use_reg_iface: + assign reg_intf_req = reg_req_i; + assign reg_rsp_o = reg_intf_rsp; + % else: assign tl_reg_h2d = tl_i; assign tl_o_pre = tl_reg_d2h; + % endif % else: + % if use_reg_iface: + assign reg_req_win_o = reg_req_i; + assign reg_rsp_o = reg_rsp_win_i + % else: assign tl_win_o[0] = tl_i; assign tl_o_pre = tl_win_i[0]; + % endif % endif % else: + logic [${num_wins_width-1}:0] reg_steer; + + % if use_reg_iface: + ${reg_intf_req} [${num_dsp}-1:0] reg_intf_demux_req; + ${reg_intf_rsp} [${num_dsp}-1:0] reg_intf_demux_rsp; + + // demux connection + assign reg_intf_req = reg_intf_demux_req[${num_wins}]; + assign reg_intf_demux_rsp[${num_wins}] = reg_intf_rsp; + + % for i,t in enumerate(block.wins): + assign reg_req_win_o[${i}] = reg_intf_demux_req[${i}]; + assign reg_intf_demux_rsp[${i}] = reg_rsp_win_i[${i}]; + % endfor + + // Create Socket_1n + reg_demux #( + .NoPorts (${num_dsp}), + .req_t (${reg_intf_req}), + .rsp_t (${reg_intf_rsp}) + ) i_reg_demux ( + .clk_i, + .rst_ni, + .in_req_i (reg_req_i), + .in_rsp_o (reg_rsp_o), + .out_req_o (reg_intf_demux_req), + .out_rsp_i (reg_intf_demux_rsp), + .in_select_i (reg_steer) + ); + + % else: tlul_pkg::tl_h2d_t tl_socket_h2d [${num_dsp}]; tlul_pkg::tl_d2h_t tl_socket_d2h [${num_dsp}]; - logic [${num_wins_width}:0] reg_steer; - // socket_1n connection % if rb.all_regs: assign tl_reg_h2d = tl_socket_h2d[${num_wins}]; @@ -186,6 +266,7 @@ module ${mod_name} ( .tl_d_i (tl_socket_d2h), .dev_select_i (reg_steer) ); + % endif // Create steering logic always_comb begin @@ -196,13 +277,21 @@ module ${mod_name} ( <% base_addr = w.offset limit_addr = w.offset + w.size_in_bytes - - hi_check = 'tl_i.a_address[AW-1:0] < {}'.format(limit_addr) + if use_reg_iface: + hi_check = 'reg_req_i.addr[AW-1:0] < {}'.format(limit_addr) + else: + hi_check = 'tl_i.a_address[AW-1:0] < {}'.format(limit_addr) addr_checks = [] if base_addr > 0: - addr_checks.append('tl_i.a_address[AW-1:0] >= {}'.format(base_addr)) + if use_reg_iface: + addr_checks.append('reg_req_i.addr[AW-1:0] >= {}'.format(base_addr)) + else: + addr_checks.append('tl_i.a_address[AW-1:0] >= {}'.format(base_addr)) if limit_addr < 2**addr_width: - addr_checks.append('tl_i.a_address[AW-1:0] < {}'.format(limit_addr)) + if use_reg_iface: + addr_checks.append('reg_req_i.addr[AW-1:0] < {}'.format(limit_addr)) + else: + addr_checks.append('tl_i.a_address[AW-1:0] < {}'.format(limit_addr)) addr_test = ' && '.join(addr_checks) %>\ @@ -214,13 +303,26 @@ module ${mod_name} ( end % endif % endfor + % if not use_reg_iface: if (intg_err) begin reg_steer = ${num_dsp-1}; end + % endif end % endif % if rb.all_regs: + +% if use_reg_iface: + assign reg_we = reg_intf_req.valid & reg_intf_req.write; + assign reg_re = reg_intf_req.valid & ~reg_intf_req.write; + assign reg_addr = reg_intf_req.addr; + assign reg_wdata = reg_intf_req.wdata; + assign reg_be = reg_intf_req.wstrb; + assign reg_intf_rsp.rdata = reg_rdata; + assign reg_intf_rsp.error = reg_error; + assign reg_intf_rsp.ready = 1'b1; +% else: tlul_adapter_reg #( .RegAw(AW), .RegDw(DW), @@ -240,9 +342,15 @@ module ${mod_name} ( .rdata_i (reg_rdata), .error_i (reg_error) ); +% endif assign reg_rdata = reg_rdata_next ; +% if use_reg_iface: + assign reg_error = (devmode_i & addrmiss) | wr_err; +% else: assign reg_error = (devmode_i & addrmiss) | wr_err | intg_err; +% endif + // Define SW related signals // Format: <reg>_<field>_{wd|we|qs} @@ -405,16 +513,17 @@ ${rdata_gen(f, r.name.lower() + "_" + f.name.lower())}\ % if rb.all_regs: // Assertions for Register Interface +% if not use_reg_iface: `ASSERT_PULSE(wePulse, reg_we) `ASSERT_PULSE(rePulse, reg_re) `ASSERT(reAfterRv, $rose(reg_re || reg_we) |=> tl_o.d_valid) - `ASSERT(en2addrHit, (reg_we || reg_re) |-> $onehot0(addr_hit)) - // this is formulated as an assumption such that the FPV testbenches do disprove this // property by mistake //`ASSUME(reqParity, tl_reg_h2d.a_valid |-> tl_reg_h2d.a_user.chk_en == tlul_pkg::CheckDis) +% endif + `ASSERT(en2addrHit, (reg_we || reg_re) |-> $onehot0(addr_hit)) % endif endmodule -- 2.16.5
gitdir: ../../.git/modules/corev_apu/riscv-dbg
language: cpp # run on new infrastructure dist: xenial sudo: false cache: apt: true directories: $RISCV $VERILATOR_ROOT timeout: 1000 # required packages to install addons: apt: sources: - ubuntu-toolchain-r-test packages: - gcc-7 - g++-7 - gperf - autoconf - automake - autotools-dev - libmpc-dev - libmpfr-dev - libgmp-dev - gawk - build-essential - bison - flex - texinfo - python-pexpect - libusb-1.0-0-dev - default-jdk - zlib1g-dev - valgrind env: global: - RISCV="/home/travis/riscv_install" - VERILATOR_ROOT="/home/travis/verilator-4.018" before_install: - export CXX=g++-7 CC=gcc-7 # setup dependent paths - export PATH=$RISCV/bin:$VERILATOR_ROOT/bin:$PATH - export LIBRARY_PATH=$RISCV/lib - export LD_LIBRARY_PATH=$RISCV/lib - export C_INCLUDE_PATH=$RISCV/include:$VERILATOR_ROOT/share/verilator/include - export CPLUS_INCLUDE_PATH=$RISCV/include:$VERILATOR_ROOT/share/verilator/include - export PKG_CONFIG_PATH=$VERILATOR_ROOT/share/pkgconfig # number of parallel jobs to use for make commands and simulation - export NUM_JOBS=4 - ci/make-tmp.sh - git submodule update --init --recursive stages: - download - compile1 - compile2 - test jobs: include: - stage: download name: download pulp gcc script: - ci/download-pulp-gcc.sh - stage: compile2 name: build verilator script: - ci/install-verilator.sh - stage: compile2 name: build openocd script: - ci/get-openocd.sh - stage: test name: run openocd debug module tests script: - ci/veri-run-openocd-compliance.sh # extra time during long builds install: travis_wait
package: name: riscv-dbg sources: files: - src/dm_pkg.sv - debug_rom/debug_rom.sv - debug_rom/debug_rom_one_scratch.sv - src/dm_csrs.sv - src/dm_mem.sv - src/dm_top.sv - src/dm_obi_top.sv - src/dmi_cdc.sv - src/dmi_jtag.sv - src/dmi_jtag_tap.sv - src/dm_sba.sv
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [Unreleased] ### Added ### Changed ### Fixed ## [0.4.1] - 2021-05-04 ### Added ### Changed ### Fixed - Remove superfluous helper variable in dm_csrs.sv - Synchronized Bender.yml entries - Various Lint warnings ## [0.4.0] - 2020-11-06 ### Added - Added parameter ReadByteEnable that may be disabled to revert SBA _be_ behavior to 0 on reads - Optional wrapper `dm_obi_top.sv` that wraps `dm_top` providing an OBI compliant interface - `tb` that runs dm in conjunction with ri5cy and OpenOCD - `.travis-ci.yml` running `tb` with verilator ### Changed - Made second scratch register optional (default is two) from [@zarubaf](https://github.com/zarubaf) - Use latest version of CV32E40P in testbench (#82) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - Move assertions into separate module (#82) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) ### Fixed - Fix for SBA _be_ when reading to match the request size from (#70) [@jm4rtin](https://github.com/jm4rtin) - Off-by-one error in data and progbuf end address from [@pbing](https://github.com/pbing) - Haltsum1-3 calculation - A DMI read of SBAddress0 andSBAddress0 will (wrongly) trigger SBBUSYERROR when the system bus master is busy (#93) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - When the two scratch mode is being used, a0 was loaded instead of saved into scratch1 (#90) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - dmireset can be accidentally triggered (#89) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - enumeration lint issue in ProgBuf (#84) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - Fix faulty assertion because of bad `hartinfo_i` in testbench (#82) [@Silabs-ArjanB](https://github.com/Silabs-ArjanB) - Return `CmdErrBusy` if accessing data or progbuf while command was executing (#79) [@noytzach](https://github.com/noytzach) ## [0.3.0] - 2020-01-23 ### Added - Documentation in `doc/` from [@imphil](https://github.com/imphil) ### Changed - Various linting issues and cleanups from [@msfschaffner](https://github.com/msfschaffner) ### Fixed - Corruption on debug exception entry [@tomroberts-lowrisc](https://github.com/tomroberts-lowrisc) - truncation of `selected_hart` ## [0.2.0] - 2019-08-16 ## Added - Add Bender.yml ### Fixed - Fix haltsum1, haltsum2 and haltsum3 - Fix minor linter issues ## [0.1.0] - 2019-05-18 ### Added - Parametrize buswidth to support 32-bit and 64-bit cores - Support arbitrary base addresses in debug ROM - Add misc helper functions to facilitate code generation - Add README - Fork from Ariane ### Changed - Allow generic number of data registers - Make JTAG IDCODE parametrizable ### Removed - Remove ariane specific packages ### Fixed - Fix resumeack and resumereq behaviour to be cleared and set according to debug specification - Add missing JTAG test logic reset handling - Fix resume logic in multihart situations - Fix missing else(s) in system bus access - Fix bad transitions into program buffer - Fix error handling when using unsupported abstract commands - Prevent harts from being in multiple states - Fix various style issues
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016-2017 SiFive, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[![Build Status](https://travis-ci.com/pulp-platform/riscv-dbg.svg?branch=master)](https://travis-ci.com/pulp-platform/riscv-dbg) # RISC-V Debug Support for PULP Cores This module is an implementation of a debug unit compliant with the [RISC-V debug specification](https://github.com/riscv/riscv-debug-spec) v0.13.1. It is used in the [Ariane](https://github.com/pulp-platform/ariane) and [RI5CY](https://github.com/pulp-platform/riscv) cores. ## Implementation We use an execution-based technique, also described in the specification, where the core is running in a "park loop". Depending on the request made to the debug unit via JTAG over the Debug Transport Module (DTM), the code that is being executed is changed dynamically. This approach simplifies the implementation side of the core, but means that the core is in fact always busy looping while debugging. ## Features The following features are currently supported * Parametrizable buswidth for `XLEN=32` `XLEN=64` cores * Accessing registers over abstract command * Program buffer * System bus access (only `XLEN`) * DTM with JTAG interface These are not implemented (yet) * Trigger module * Quick access using abstract commands * Accessing memory using abstract commands * Authentication ## Tests We use OpenOCD's [RISC-V compliance tests](https://github.com/riscv/riscv-openocd/blob/riscv/src/target/riscv/riscv-013.c), our custom testbench in `tb/` and [riscv-tests/debug](https://github.com/riscv/riscv-tests/tree/master/debug).
riscv-dbg: files: [ src/dm_pkg.sv, debug_rom/debug_rom.sv, debug_rom/debug_rom_one_scratch.sv, src/dm_csrs.sv, src/dm_mem.sv, src/dm_top.sv, src/dm_obi_top.sv, src/dmi_cdc.sv, src/dmi_jtag.sv, src/dmi_jtag_tap.sv, src/dm_sba.sv, ]
#!/bin/bash set -o pipefail set -e ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) VERSION="v1.0.16" # mkdir -p $RISCV wget https://github.com/pulp-platform/pulp-riscv-gnu-toolchain/releases/download/$VERSION/$VERSION-pulp-riscv-gcc-ubuntu-16.tar.bz2 echo "unpacking pulp gcc and installing to $RISCV" tar -xvf $VERSION-pulp-riscv-gcc-ubuntu-16.tar.bz2 -C "$RISCV" --strip 1
#!/usr/bin/env bash set -e VERSION="af3a034b57279d2a400d87e7508c9a92254ec165" mkdir -p $RISCV/ cd $RISCV check_version() { $1 --version | awk "NR==1 {if (\$NF>$2) {exit 0} exit 1}" || ( echo $3 requires at least version $2 of $1. Aborting. exit 1 ) } if [ -z ${NUM_JOBS} ]; then NUM_JOBS=1 fi if ! [ -e $RISCV/bin/openocd ]; then if ! [ -e $RISCV/riscv-openocd ]; then git clone https://github.com/riscv/riscv-openocd.git fi check_version automake 1.14 "OpenOCD build" check_version autoconf 2.64 "OpenOCD build" cd riscv-openocd git checkout $VERSION git submodule update --init --recursive echo "Compiling OpenOCD" ./bootstrap ./configure --prefix=$RISCV --disable-werror --disable-wextra --enable-remote-bitbang make -j${NUM_JOBS} make install echo "Compilation Finished" fi
#!/bin/bash set -e ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) cd $ROOT/tmp if [ -z ${NUM_JOBS} ]; then NUM_JOBS=1 fi if [ ! -e "$VERILATOR_ROOT/bin/verilator" ]; then echo "Installing Verilator" rm -f verilator*.tgz wget https://www.veripool.org/ftp/verilator-4.018.tgz tar xzf verilator*.tgz rm -f verilator*.tgz cd verilator-4.018 mkdir -p $VERILATOR_ROOT # copy scripts autoconf && ./configure --prefix="$VERILATOR_ROOT" && make -j${NUM_JOBS} make install # not obvious to me why these symlinks are missing ln -s $VERILATOR_ROOT/share/verilator/include $VERILATOR_ROOT/include ln -s $VERILATOR_ROOT/share/verilator/bin/verilator_includer \ $VERILATOR_ROOT/bin/verilator_includer make test else echo "Using Verilator from cached directory." fi
#!/bin/bash set -e cd "$(dirname "${BASH_SOURCE[0]}")/.." [ -d tmp ] || rm -rf tmp mkdir -p tmp
#!/usr/bin/env python3 import sys, getopt from junit_xml import * def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print ('openocd-to-junit.py -i <inputfile> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('openocd-to-junit.py -i <inputfile> -o <outputfile>') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg test_strings = defaultdict(list) test_timestamps = {} current_testname = '' test_cases = [] current_test_case = None ocd_stdout = '' with open(inputfile, 'r') as infile: for line in infile: if 'Info' in line and 'riscv013_test_compliance()' in line: print(line.split(' ')) current_testname = ' '.join(line.split(' ')[7:]) test_strings[current_testname].append(line) test_timestamps[current_testname] = line.split(' ')[3] ocd_stdout += line for k,v in test_strings.items(): current_test_case = TestCase(k, stdout=''.join(v), timestamp=test_timestamps[k]) error_msg = "" for line in v: if 'FAILED' in line: error_msg += line; if error_msg: current_test_case.add_error_info(error_msg) test_cases.append(current_test_case) ts = TestSuite("openocd-compliance", test_cases, stdout=ocd_stdout) # pretty printing is on by default but can be disabled using prettyprint=False with open(outputfile, 'w') as outfile: TestSuite.to_file(outfile, [ts]) if __name__ == "__main__": main(sys.argv[1:])
#!/usr/bin/env bash set -e ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) if [ -z "${RISCV}" ] then echo "RISCV is empty" exit 1 fi function cleanup { echo "cleaning up processes and tmp files" sleep 2 echo "vsim pid is:${vsim_pid} pgid:${vsim_pgid}" if ps -p "${vsim_pid}" > /dev/null then echo "vsim pid exists, killing it" kill -- -"${vsim_pgid}" fi rm "${vsim_out}" } trap cleanup EXIT vsim_out=$(mktemp) openocd_out=openocd.log make -C "${ROOT}"/tb/dm vsim-run &> "${vsim_out}"& # record vsim pid/pgid to kill it if it survives this script vsim_pid=$! vsim_pgid=$(ps -o pgid= ${vsim_pid} | grep -o [0-9]*) # block until we get "Listening on port" so that we are safe to connect openocd coproc grep -m 1 "Listening on port" tail -f -n0 "${vsim_out}" --pid "$COPROC_PID" >&"${COPROC[1]}" echo "Starting openocd" "${RISCV}"/bin/openocd -f "${ROOT}"/tb/dm/dm_compliance_test.cfg |& tee "${openocd_out}" if grep -q "ALL TESTS PASSED" "${openocd_out}"; then exit 0 fi exit 1
#!/usr/bin/env bash set -e ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) if [ -z "${RISCV}" ] then echo "RISCV is empty" exit 1 fi veri_out=$(mktemp) openocd_out=openocd.log make -C "${ROOT}"/tb veri-run |& tee "${veri_out}"& # record veri pid/pgid to kill it if it survives this script veri_pid=$! veri_pgid=$(ps -o pgid= ${veri_pid} | grep -o [0-9]*) # block until we get "Listening on port" so that we are safe to connect openocd coproc grep -m 1 "Listening on port" tail -f -n0 "${veri_out}" --pid "$COPROC_PID" >&"${COPROC[1]}" echo "Starting openocd" "${RISCV}"/bin/openocd -f "${ROOT}"/tb/dm_compliance_test.cfg |& tee "${openocd_out}" if grep -q "ALL TESTS PASSED" "${openocd_out}"; then exit 0 fi exit 1
*.bin *.elf debug_rom.img
// Auto-generated code const int reset_vec_size = 38; uint32_t reset_vec[reset_vec_size] = { 0x00c0006f, 0x07c0006f, 0x04c0006f, 0x0ff0000f, 0x7b241073, 0x7b351073, 0x00000517, 0x00c55513, 0x00c51513, 0xf1402473, 0x10852023, 0x00a40433, 0x40044403, 0x00147413, 0x02041c63, 0xf1402473, 0x00a40433, 0x40044403, 0x00247413, 0xfa041ce3, 0xfd5ff06f, 0x00000517, 0x00c55513, 0x00c51513, 0x10052623, 0x7b302573, 0x7b202473, 0x00100073, 0x10052223, 0x7b302573, 0x7b202473, 0xa85ff06f, 0xf1402473, 0x10852423, 0x7b302573, 0x7b202473, 0x7b200073, 0x00000000 };
// See LICENSE.SiFive for license details. #include "encoding.h" // The debugger can assume as second scratch register. // # define SND_SCRATCH 1 // These are implementation-specific addresses in the Debug Module #define HALTED 0x100 #define GOING 0x104 #define RESUMING 0x108 #define EXCEPTION 0x10C // Region of memory where each hart has 1 // byte to read. #define FLAGS 0x400 #define FLAG_GO 0 #define FLAG_RESUME 1 .option norvc .global entry .global exception // Entry location on ebreak, Halt, or Breakpoint // It is the same for all harts. They branch when // their GO or RESUME bit is set. entry: jal zero, _entry resume: jal zero, _resume exception: jal zero, _exception _entry: // This fence is required because the execution may have written something // into the Abstract Data or Program Buffer registers. fence csrw CSR_DSCRATCH0, s0 // Save s0 to allow signaling MHARTID #ifdef SND_SCRATCH csrw CSR_DSCRATCH1, a0 // Save a0 to allow loading arbitrary DM base auipc a0, 0 // Get PC srli a0, a0, 12 // And throw away lower 12 bits to get the DM base slli a0, a0, 12 #endif // We continue to let the hart know that we are halted in order that // a DM which was reset is still made aware that a hart is halted. // We keep checking both whether there is something the debugger wants // us to do, or whether we should resume. entry_loop: csrr s0, CSR_MHARTID #ifdef SND_SCRATCH sw s0, HALTED(a0) add s0, s0, a0 #else sw s0, HALTED(zero) #endif lbu s0, FLAGS(s0) // 1 byte flag per hart. Only one hart advances here. andi s0, s0, (1 << FLAG_GO) bnez s0, going csrr s0, CSR_MHARTID #ifdef SND_SCRATCH add s0, s0, a0 #endif lbu s0, FLAGS(s0) // multiple harts can resume here andi s0, s0, (1 << FLAG_RESUME) bnez s0, resume jal zero, entry_loop _exception: // We can only get here due to an exception while in debug mode. Hence, // we do not need to save a0 to a scratch register as it has already // been saved on debug entry. #ifdef SND_SCRATCH auipc a0, 0 // Get POC srli a0, a0, 12 // And throw away lower 12 bits to get the DM base slli a0, a0, 12 sw zero, EXCEPTION(a0) // Let debug module know you got an exception. // It is safe to always restore the scratch registers here as they must // have been saved on debug entry. Restoring them here avoids issues // with registers being overwritten by exceptions occuring during // program buffer execution. csrr a0, CSR_DSCRATCH1 // Restore a0 here #else sw zero, EXCEPTION(zero) // Let debug module know you got an exception. #endif csrr s0, CSR_DSCRATCH0 // Restore s0 here ebreak going: #ifdef SND_SCRATCH sw zero, GOING(a0) // When debug module sees this write, the GO flag is reset. csrr a0, CSR_DSCRATCH1 // Restore a0 here #else sw zero, GOING(zero) // When debug module sees this write, the GO flag is reset. #endif csrr s0, CSR_DSCRATCH0 // Restore s0 here jal zero, whereto _resume: csrr s0, CSR_MHARTID #ifdef SND_SCRATCH sw s0, RESUMING(a0) // When Debug Module sees this write, the RESUME flag is reset. csrr a0, CSR_DSCRATCH1 // Restore a0 here #else sw s0, RESUMING(zero) // When Debug Module sees this write, the RESUME flag is reset. #endif csrr s0, CSR_DSCRATCH0 // Restore s0 here dret // END OF ACTUAL "ROM" CONTENTS. BELOW IS JUST FOR LINKER SCRIPT. .section .whereto whereto: nop // Variable "ROM" This is : jal x0 abstract, jal x0 program_buffer, // or jal x0 resume, as desired. // Debug Module state machine tracks what is 'desired'. // We don't need/want to use jalr here because all of the // Variable ROM contents are set by // Debug Module before setting the OK_GO byte.
/* Copyright 2018 ETH Zurich and University of Bologna. * Copyright and related rights are licensed under the Solderpad Hardware * License, Version 0.51 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law * or agreed to in writing, software, hardware and materials distributed under * this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * File: $filename.v * * Description: Auto-generated bootrom */ // Auto-generated code module debug_rom ( input logic clk_i, input logic req_i, input logic [63:0] addr_i, output logic [63:0] rdata_o ); localparam int unsigned RomSize = 19; logic [RomSize-1:0][63:0] mem; assign mem = { 64'h00000000_7b200073, 64'h7b202473_7b302573, 64'h10852423_f1402473, 64'ha85ff06f_7b202473, 64'h7b302573_10052223, 64'h00100073_7b202473, 64'h7b302573_10052623, 64'h00c51513_00c55513, 64'h00000517_fd5ff06f, 64'hfa041ce3_00247413, 64'h40044403_00a40433, 64'hf1402473_02041c63, 64'h00147413_40044403, 64'h00a40433_10852023, 64'hf1402473_00c51513, 64'h00c55513_00000517, 64'h7b351073_7b241073, 64'h0ff0000f_04c0006f, 64'h07c0006f_00c0006f }; logic [$clog2(RomSize)-1:0] addr_q; always_ff @(posedge clk_i) begin if (req_i) begin addr_q <= addr_i[$clog2(RomSize)-1+3:3]; end end // this prevents spurious Xes from propagating into // the speculative fetch stage of the core always_comb begin : p_outmux rdata_o = '0; if (addr_q < $clog2(RomSize)'(RomSize)) begin rdata_o = mem[addr_q]; end end endmodule
// Auto-generated code const int reset_vec_size = 26; uint32_t reset_vec[reset_vec_size] = { 0x00c0006f, 0x0500006f, 0x0340006f, 0x0ff0000f, 0x7b241073, 0xf1402473, 0x10802023, 0x40044403, 0x00147413, 0x02041263, 0xf1402473, 0x40044403, 0x00247413, 0xfc0418e3, 0xfddff06f, 0x10002623, 0x7b202473, 0x00100073, 0x10002223, 0x7b202473, 0xab1ff06f, 0xf1402473, 0x10802423, 0x7b202473, 0x7b200073, 0x00000000 };
/* Copyright 2018 ETH Zurich and University of Bologna. * Copyright and related rights are licensed under the Solderpad Hardware * License, Version 0.51 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law * or agreed to in writing, software, hardware and materials distributed under * this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * File: $filename.v * * Description: Auto-generated bootrom */ // Auto-generated code module debug_rom_one_scratch ( input logic clk_i, input logic req_i, input logic [63:0] addr_i, output logic [63:0] rdata_o ); localparam int unsigned RomSize = 13; logic [RomSize-1:0][63:0] mem; assign mem = { 64'h00000000_7b200073, 64'h7b202473_10802423, 64'hf1402473_ab1ff06f, 64'h7b202473_10002223, 64'h00100073_7b202473, 64'h10002623_fddff06f, 64'hfc0418e3_00247413, 64'h40044403_f1402473, 64'h02041263_00147413, 64'h40044403_10802023, 64'hf1402473_7b241073, 64'h0ff0000f_0340006f, 64'h0500006f_00c0006f }; logic [$clog2(RomSize)-1:0] addr_q; always_ff @(posedge clk_i) begin if (req_i) begin addr_q <= addr_i[$clog2(RomSize)-1+3:3]; end end // this prevents spurious Xes from propagating into // the speculative fetch stage of the core always_comb begin : p_outmux rdata_o = '0; if (addr_q < $clog2(RomSize)'(RomSize)) begin rdata_o = mem[addr_q]; end end endmodule
// See LICENSE for license details. #ifndef RISCV_CSR_ENCODING_H #define RISCV_CSR_ENCODING_H #define MSTATUS_UIE 0x00000001 #define MSTATUS_SIE 0x00000002 #define MSTATUS_HIE 0x00000004 #define MSTATUS_MIE 0x00000008 #define MSTATUS_UPIE 0x00000010 #define MSTATUS_SPIE 0x00000020 #define MSTATUS_HPIE 0x00000040 #define MSTATUS_MPIE 0x00000080 #define MSTATUS_SPP 0x00000100 #define MSTATUS_HPP 0x00000600 #define MSTATUS_MPP 0x00001800 #define MSTATUS_FS 0x00006000 #define MSTATUS_XS 0x00018000 #define MSTATUS_MPRV 0x00020000 #define MSTATUS_SUM 0x00040000 #define MSTATUS_MXR 0x00080000 #define MSTATUS_TVM 0x00100000 #define MSTATUS_TW 0x00200000 #define MSTATUS_TSR 0x00400000 #define MSTATUS32_SD 0x80000000 #define MSTATUS_UXL 0x0000000300000000 #define MSTATUS_SXL 0x0000000C00000000 #define MSTATUS64_SD 0x8000000000000000 #define SSTATUS_UIE 0x00000001 #define SSTATUS_SIE 0x00000002 #define SSTATUS_UPIE 0x00000010 #define SSTATUS_SPIE 0x00000020 #define SSTATUS_SPP 0x00000100 #define SSTATUS_FS 0x00006000 #define SSTATUS_XS 0x00018000 #define SSTATUS_SUM 0x00040000 #define SSTATUS_MXR 0x00080000 #define SSTATUS32_SD 0x80000000 #define SSTATUS_UXL 0x0000000300000000 #define SSTATUS64_SD 0x8000000000000000 #define DCSR_XDEBUGVER (3U<<30) #define DCSR_NDRESET (1<<29) #define DCSR_FULLRESET (1<<28) #define DCSR_EBREAKM (1<<15) #define DCSR_EBREAKH (1<<14) #define DCSR_EBREAKS (1<<13) #define DCSR_EBREAKU (1<<12) #define DCSR_STOPCYCLE (1<<10) #define DCSR_STOPTIME (1<<9) #define DCSR_CAUSE (7<<6) #define DCSR_DEBUGINT (1<<5) #define DCSR_HALT (1<<3) #define DCSR_STEP (1<<2) #define DCSR_PRV (3<<0) #define DCSR_CAUSE_NONE 0 #define DCSR_CAUSE_SWBP 1 #define DCSR_CAUSE_HWBP 2 #define DCSR_CAUSE_DEBUGINT 3 #define DCSR_CAUSE_STEP 4 #define DCSR_CAUSE_HALT 5 #define MCONTROL_TYPE(xlen) (0xfULL<<((xlen)-4)) #define MCONTROL_DMODE(xlen) (1ULL<<((xlen)-5)) #define MCONTROL_MASKMAX(xlen) (0x3fULL<<((xlen)-11)) #define MCONTROL_SELECT (1<<19) #define MCONTROL_TIMING (1<<18) #define MCONTROL_ACTION (0x3f<<12) #define MCONTROL_CHAIN (1<<11) #define MCONTROL_MATCH (0xf<<7) #define MCONTROL_M (1<<6) #define MCONTROL_H (1<<5) #define MCONTROL_S (1<<4) #define MCONTROL_U (1<<3) #define MCONTROL_EXECUTE (1<<2) #define MCONTROL_STORE (1<<1) #define MCONTROL_LOAD (1<<0) #define MCONTROL_TYPE_NONE 0 #define MCONTROL_TYPE_MATCH 2 #define MCONTROL_ACTION_DEBUG_EXCEPTION 0 #define MCONTROL_ACTION_DEBUG_MODE 1 #define MCONTROL_ACTION_TRACE_START 2 #define MCONTROL_ACTION_TRACE_STOP 3 #define MCONTROL_ACTION_TRACE_EMIT 4 #define MCONTROL_MATCH_EQUAL 0 #define MCONTROL_MATCH_NAPOT 1 #define MCONTROL_MATCH_GE 2 #define MCONTROL_MATCH_LT 3 #define MCONTROL_MATCH_MASK_LOW 4 #define MCONTROL_MATCH_MASK_HIGH 5 #define MIP_SSIP (1 << IRQ_S_SOFT) #define MIP_HSIP (1 << IRQ_H_SOFT) #define MIP_MSIP (1 << IRQ_M_SOFT) #define MIP_STIP (1 << IRQ_S_TIMER) #define MIP_HTIP (1 << IRQ_H_TIMER) #define MIP_MTIP (1 << IRQ_M_TIMER) #define MIP_SEIP (1 << IRQ_S_EXT) #define MIP_HEIP (1 << IRQ_H_EXT) #define MIP_MEIP (1 << IRQ_M_EXT) #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP #define PRV_U 0 #define PRV_S 1 #define PRV_H 2 #define PRV_M 3 #define SATP32_MODE 0x80000000 #define SATP32_ASID 0x7FC00000 #define SATP32_PPN 0x003FFFFF #define SATP64_MODE 0xF000000000000000 #define SATP64_ASID 0x0FFFF00000000000 #define SATP64_PPN 0x00000FFFFFFFFFFF #define SATP_MODE_OFF 0 #define SATP_MODE_SV32 1 #define SATP_MODE_SV39 8 #define SATP_MODE_SV48 9 #define SATP_MODE_SV57 10 #define SATP_MODE_SV64 11 #define PMP_R 0x01 #define PMP_W 0x02 #define PMP_X 0x04 #define PMP_A 0x18 #define PMP_L 0x80 #define PMP_SHIFT 2 #define PMP_TOR 0x08 #define PMP_NA4 0x10 #define PMP_NAPOT 0x18 #define IRQ_S_SOFT 1 #define IRQ_H_SOFT 2 #define IRQ_M_SOFT 3 #define IRQ_S_TIMER 5 #define IRQ_H_TIMER 6 #define IRQ_M_TIMER 7 #define IRQ_S_EXT 9 #define IRQ_H_EXT 10 #define IRQ_M_EXT 11 #define IRQ_COP 12 #define IRQ_HOST 13 #define DEFAULT_RSTVEC 0x00001000 #define CLINT_BASE 0x02000000 #define CLINT_SIZE 0x000c0000 #define EXT_IO_BASE 0x40000000 #define DRAM_BASE 0x80000000 // page table entry (PTE) fields #define PTE_V 0x001 // Valid #define PTE_R 0x002 // Read #define PTE_W 0x004 // Write #define PTE_X 0x008 // Execute #define PTE_U 0x010 // User #define PTE_G 0x020 // Global #define PTE_A 0x040 // Accessed #define PTE_D 0x080 // Dirty #define PTE_SOFT 0x300 // Reserved for Software #define PTE_PPN_SHIFT 10 #define PTE_TABLE(PTE) (((PTE) & (PTE_V | PTE_R | PTE_W | PTE_X)) == PTE_V) #ifdef __riscv #if __riscv_xlen == 64 # define MSTATUS_SD MSTATUS64_SD # define SSTATUS_SD SSTATUS64_SD # define RISCV_PGLEVEL_BITS 9 # define SATP_MODE SATP64_MODE #else # define MSTATUS_SD MSTATUS32_SD # define SSTATUS_SD SSTATUS32_SD # define RISCV_PGLEVEL_BITS 10 # define SATP_MODE SATP32_MODE #endif #define RISCV_PGSHIFT 12 #define RISCV_PGSIZE (1 << RISCV_PGSHIFT) #ifndef __ASSEMBLER__ #ifdef __GNUC__ #define read_csr(reg) ({ unsigned long __tmp; \ asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ __tmp; }) #define write_csr(reg, val) ({ \ asm volatile ("csrw " #reg ", %0" :: "rK"(val)); }) #define swap_csr(reg, val) ({ unsigned long __tmp; \ asm volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "rK"(val)); \ __tmp; }) #define set_csr(reg, bit) ({ unsigned long __tmp; \ asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ __tmp; }) #define clear_csr(reg, bit) ({ unsigned long __tmp; \ asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ __tmp; }) #define rdtime() read_csr(time) #define rdcycle() read_csr(cycle) #define rdinstret() read_csr(instret) #endif #endif #endif #endif /* Automatically generated by parse-opcodes. */ #ifndef RISCV_ENCODING_H #define RISCV_ENCODING_H #define MATCH_BEQ 0x63 #define MASK_BEQ 0x707f #define MATCH_BNE 0x1063 #define MASK_BNE 0x707f #define MATCH_BLT 0x4063 #define MASK_BLT 0x707f #define MATCH_BGE 0x5063 #define MASK_BGE 0x707f #define MATCH_BLTU 0x6063 #define MASK_BLTU 0x707f #define MATCH_BGEU 0x7063 #define MASK_BGEU 0x707f #define MATCH_JALR 0x67 #define MASK_JALR 0x707f #define MATCH_JAL 0x6f #define MASK_JAL 0x7f #define MATCH_LUI 0x37 #define MASK_LUI 0x7f #define MATCH_AUIPC 0x17 #define MASK_AUIPC 0x7f #define MATCH_ADDI 0x13 #define MASK_ADDI 0x707f #define MATCH_SLLI 0x1013 #define MASK_SLLI 0xfc00707f #define MATCH_SLTI 0x2013 #define MASK_SLTI 0x707f #define MATCH_SLTIU 0x3013 #define MASK_SLTIU 0x707f #define MATCH_XORI 0x4013 #define MASK_XORI 0x707f #define MATCH_SRLI 0x5013 #define MASK_SRLI 0xfc00707f #define MATCH_SRAI 0x40005013 #define MASK_SRAI 0xfc00707f #define MATCH_ORI 0x6013 #define MASK_ORI 0x707f #define MATCH_ANDI 0x7013 #define MASK_ANDI 0x707f #define MATCH_ADD 0x33 #define MASK_ADD 0xfe00707f #define MATCH_SUB 0x40000033 #define MASK_SUB 0xfe00707f #define MATCH_SLL 0x1033 #define MASK_SLL 0xfe00707f #define MATCH_SLT 0x2033 #define MASK_SLT 0xfe00707f #define MATCH_SLTU 0x3033 #define MASK_SLTU 0xfe00707f #define MATCH_XOR 0x4033 #define MASK_XOR 0xfe00707f #define MATCH_SRL 0x5033 #define MASK_SRL 0xfe00707f #define MATCH_SRA 0x40005033 #define MASK_SRA 0xfe00707f #define MATCH_OR 0x6033 #define MASK_OR 0xfe00707f #define MATCH_AND 0x7033 #define MASK_AND 0xfe00707f #define MATCH_ADDIW 0x1b #define MASK_ADDIW 0x707f #define MATCH_SLLIW 0x101b #define MASK_SLLIW 0xfe00707f #define MATCH_SRLIW 0x501b #define MASK_SRLIW 0xfe00707f #define MATCH_SRAIW 0x4000501b #define MASK_SRAIW 0xfe00707f #define MATCH_ADDW 0x3b #define MASK_ADDW 0xfe00707f #define MATCH_SUBW 0x4000003b #define MASK_SUBW 0xfe00707f #define MATCH_SLLW 0x103b #define MASK_SLLW 0xfe00707f #define MATCH_SRLW 0x503b #define MASK_SRLW 0xfe00707f #define MATCH_SRAW 0x4000503b #define MASK_SRAW 0xfe00707f #define MATCH_LB 0x3 #define MASK_LB 0x707f #define MATCH_LH 0x1003 #define MASK_LH 0x707f #define MATCH_LW 0x2003 #define MASK_LW 0x707f #define MATCH_LD 0x3003 #define MASK_LD 0x707f #define MATCH_LBU 0x4003 #define MASK_LBU 0x707f #define MATCH_LHU 0x5003 #define MASK_LHU 0x707f #define MATCH_LWU 0x6003 #define MASK_LWU 0x707f #define MATCH_SB 0x23 #define MASK_SB 0x707f #define MATCH_SH 0x1023 #define MASK_SH 0x707f #define MATCH_SW 0x2023 #define MASK_SW 0x707f #define MATCH_SD 0x3023 #define MASK_SD 0x707f #define MATCH_FENCE 0xf #define MASK_FENCE 0x707f #define MATCH_FENCE_I 0x100f #define MASK_FENCE_I 0x707f #define MATCH_MUL 0x2000033 #define MASK_MUL 0xfe00707f #define MATCH_MULH 0x2001033 #define MASK_MULH 0xfe00707f #define MATCH_MULHSU 0x2002033 #define MASK_MULHSU 0xfe00707f #define MATCH_MULHU 0x2003033 #define MASK_MULHU 0xfe00707f #define MATCH_DIV 0x2004033 #define MASK_DIV 0xfe00707f #define MATCH_DIVU 0x2005033 #define MASK_DIVU 0xfe00707f #define MATCH_REM 0x2006033 #define MASK_REM 0xfe00707f #define MATCH_REMU 0x2007033 #define MASK_REMU 0xfe00707f #define MATCH_MULW 0x200003b #define MASK_MULW 0xfe00707f #define MATCH_DIVW 0x200403b #define MASK_DIVW 0xfe00707f #define MATCH_DIVUW 0x200503b #define MASK_DIVUW 0xfe00707f #define MATCH_REMW 0x200603b #define MASK_REMW 0xfe00707f #define MATCH_REMUW 0x200703b #define MASK_REMUW 0xfe00707f #define MATCH_AMOADD_W 0x202f #define MASK_AMOADD_W 0xf800707f #define MATCH_AMOXOR_W 0x2000202f #define MASK_AMOXOR_W 0xf800707f #define MATCH_AMOOR_W 0x4000202f #define MASK_AMOOR_W 0xf800707f #define MATCH_AMOAND_W 0x6000202f #define MASK_AMOAND_W 0xf800707f #define MATCH_AMOMIN_W 0x8000202f #define MASK_AMOMIN_W 0xf800707f #define MATCH_AMOMAX_W 0xa000202f #define MASK_AMOMAX_W 0xf800707f #define MATCH_AMOMINU_W 0xc000202f #define MASK_AMOMINU_W 0xf800707f #define MATCH_AMOMAXU_W 0xe000202f #define MASK_AMOMAXU_W 0xf800707f #define MATCH_AMOSWAP_W 0x800202f #define MASK_AMOSWAP_W 0xf800707f #define MATCH_LR_W 0x1000202f #define MASK_LR_W 0xf9f0707f #define MATCH_SC_W 0x1800202f #define MASK_SC_W 0xf800707f #define MATCH_AMOADD_D 0x302f #define MASK_AMOADD_D 0xf800707f #define MATCH_AMOXOR_D 0x2000302f #define MASK_AMOXOR_D 0xf800707f #define MATCH_AMOOR_D 0x4000302f #define MASK_AMOOR_D 0xf800707f #define MATCH_AMOAND_D 0x6000302f #define MASK_AMOAND_D 0xf800707f #define MATCH_AMOMIN_D 0x8000302f #define MASK_AMOMIN_D 0xf800707f #define MATCH_AMOMAX_D 0xa000302f #define MASK_AMOMAX_D 0xf800707f #define MATCH_AMOMINU_D 0xc000302f #define MASK_AMOMINU_D 0xf800707f #define MATCH_AMOMAXU_D 0xe000302f #define MASK_AMOMAXU_D 0xf800707f #define MATCH_AMOSWAP_D 0x800302f #define MASK_AMOSWAP_D 0xf800707f #define MATCH_LR_D 0x1000302f #define MASK_LR_D 0xf9f0707f #define MATCH_SC_D 0x1800302f #define MASK_SC_D 0xf800707f #define MATCH_ECALL 0x73 #define MASK_ECALL 0xffffffff #define MATCH_EBREAK 0x100073 #define MASK_EBREAK 0xffffffff #define MATCH_URET 0x200073 #define MASK_URET 0xffffffff #define MATCH_SRET 0x10200073 #define MASK_SRET 0xffffffff #define MATCH_MRET 0x30200073 #define MASK_MRET 0xffffffff #define MATCH_DRET 0x7b200073 #define MASK_DRET 0xffffffff #define MATCH_SFENCE_VMA 0x12000073 #define MASK_SFENCE_VMA 0xfe007fff #define MATCH_WFI 0x10500073 #define MASK_WFI 0xffffffff #define MATCH_CSRRW 0x1073 #define MASK_CSRRW 0x707f #define MATCH_CSRRS 0x2073 #define MASK_CSRRS 0x707f #define MATCH_CSRRC 0x3073 #define MASK_CSRRC 0x707f #define MATCH_CSRRWI 0x5073 #define MASK_CSRRWI 0x707f #define MATCH_CSRRSI 0x6073 #define MASK_CSRRSI 0x707f #define MATCH_CSRRCI 0x7073 #define MASK_CSRRCI 0x707f #define MATCH_FADD_S 0x53 #define MASK_FADD_S 0xfe00007f #define MATCH_FSUB_S 0x8000053 #define MASK_FSUB_S 0xfe00007f #define MATCH_FMUL_S 0x10000053 #define MASK_FMUL_S 0xfe00007f #define MATCH_FDIV_S 0x18000053 #define MASK_FDIV_S 0xfe00007f #define MATCH_FSGNJ_S 0x20000053 #define MASK_FSGNJ_S 0xfe00707f #define MATCH_FSGNJN_S 0x20001053 #define MASK_FSGNJN_S 0xfe00707f #define MATCH_FSGNJX_S 0x20002053 #define MASK_FSGNJX_S 0xfe00707f #define MATCH_FMIN_S 0x28000053 #define MASK_FMIN_S 0xfe00707f #define MATCH_FMAX_S 0x28001053 #define MASK_FMAX_S 0xfe00707f #define MATCH_FSQRT_S 0x58000053 #define MASK_FSQRT_S 0xfff0007f #define MATCH_FADD_D 0x2000053 #define MASK_FADD_D 0xfe00007f #define MATCH_FSUB_D 0xa000053 #define MASK_FSUB_D 0xfe00007f #define MATCH_FMUL_D 0x12000053 #define MASK_FMUL_D 0xfe00007f #define MATCH_FDIV_D 0x1a000053 #define MASK_FDIV_D 0xfe00007f #define MATCH_FSGNJ_D 0x22000053 #define MASK_FSGNJ_D 0xfe00707f #define MATCH_FSGNJN_D 0x22001053 #define MASK_FSGNJN_D 0xfe00707f #define MATCH_FSGNJX_D 0x22002053 #define MASK_FSGNJX_D 0xfe00707f #define MATCH_FMIN_D 0x2a000053 #define MASK_FMIN_D 0xfe00707f #define MATCH_FMAX_D 0x2a001053 #define MASK_FMAX_D 0xfe00707f #define MATCH_FCVT_S_D 0x40100053 #define MASK_FCVT_S_D 0xfff0007f #define MATCH_FCVT_D_S 0x42000053 #define MASK_FCVT_D_S 0xfff0007f #define MATCH_FSQRT_D 0x5a000053 #define MASK_FSQRT_D 0xfff0007f #define MATCH_FADD_Q 0x6000053 #define MASK_FADD_Q 0xfe00007f #define MATCH_FSUB_Q 0xe000053 #define MASK_FSUB_Q 0xfe00007f #define MATCH_FMUL_Q 0x16000053 #define MASK_FMUL_Q 0xfe00007f #define MATCH_FDIV_Q 0x1e000053 #define MASK_FDIV_Q 0xfe00007f #define MATCH_FSGNJ_Q 0x26000053 #define MASK_FSGNJ_Q 0xfe00707f #define MATCH_FSGNJN_Q 0x26001053 #define MASK_FSGNJN_Q 0xfe00707f #define MATCH_FSGNJX_Q 0x26002053 #define MASK_FSGNJX_Q 0xfe00707f #define MATCH_FMIN_Q 0x2e000053 #define MASK_FMIN_Q 0xfe00707f #define MATCH_FMAX_Q 0x2e001053 #define MASK_FMAX_Q 0xfe00707f #define MATCH_FCVT_S_Q 0x40300053 #define MASK_FCVT_S_Q 0xfff0007f #define MATCH_FCVT_Q_S 0x46000053 #define MASK_FCVT_Q_S 0xfff0007f #define MATCH_FCVT_D_Q 0x42300053 #define MASK_FCVT_D_Q 0xfff0007f #define MATCH_FCVT_Q_D 0x46100053 #define MASK_FCVT_Q_D 0xfff0007f #define MATCH_FSQRT_Q 0x5e000053 #define MASK_FSQRT_Q 0xfff0007f #define MATCH_FLE_S 0xa0000053 #define MASK_FLE_S 0xfe00707f #define MATCH_FLT_S 0xa0001053 #define MASK_FLT_S 0xfe00707f #define MATCH_FEQ_S 0xa0002053 #define MASK_FEQ_S 0xfe00707f #define MATCH_FLE_D 0xa2000053 #define MASK_FLE_D 0xfe00707f #define MATCH_FLT_D 0xa2001053 #define MASK_FLT_D 0xfe00707f #define MATCH_FEQ_D 0xa2002053 #define MASK_FEQ_D 0xfe00707f #define MATCH_FLE_Q 0xa6000053 #define MASK_FLE_Q 0xfe00707f #define MATCH_FLT_Q 0xa6001053 #define MASK_FLT_Q 0xfe00707f #define MATCH_FEQ_Q 0xa6002053 #define MASK_FEQ_Q 0xfe00707f #define MATCH_FCVT_W_S 0xc0000053 #define MASK_FCVT_W_S 0xfff0007f #define MATCH_FCVT_WU_S 0xc0100053 #define MASK_FCVT_WU_S 0xfff0007f #define MATCH_FCVT_L_S 0xc0200053 #define MASK_FCVT_L_S 0xfff0007f #define MATCH_FCVT_LU_S 0xc0300053 #define MASK_FCVT_LU_S 0xfff0007f #define MATCH_FMV_X_W 0xe0000053 #define MASK_FMV_X_W 0xfff0707f #define MATCH_FCLASS_S 0xe0001053 #define MASK_FCLASS_S 0xfff0707f #define MATCH_FCVT_W_D 0xc2000053 #define MASK_FCVT_W_D 0xfff0007f #define MATCH_FCVT_WU_D 0xc2100053 #define MASK_FCVT_WU_D 0xfff0007f #define MATCH_FCVT_L_D 0xc2200053 #define MASK_FCVT_L_D 0xfff0007f #define MATCH_FCVT_LU_D 0xc2300053 #define MASK_FCVT_LU_D 0xfff0007f #define MATCH_FMV_X_D 0xe2000053 #define MASK_FMV_X_D 0xfff0707f #define MATCH_FCLASS_D 0xe2001053 #define MASK_FCLASS_D 0xfff0707f #define MATCH_FCVT_W_Q 0xc6000053 #define MASK_FCVT_W_Q 0xfff0007f #define MATCH_FCVT_WU_Q 0xc6100053 #define MASK_FCVT_WU_Q 0xfff0007f #define MATCH_FCVT_L_Q 0xc6200053 #define MASK_FCVT_L_Q 0xfff0007f #define MATCH_FCVT_LU_Q 0xc6300053 #define MASK_FCVT_LU_Q 0xfff0007f #define MATCH_FMV_X_Q 0xe6000053 #define MASK_FMV_X_Q 0xfff0707f #define MATCH_FCLASS_Q 0xe6001053 #define MASK_FCLASS_Q 0xfff0707f #define MATCH_FCVT_S_W 0xd0000053 #define MASK_FCVT_S_W 0xfff0007f #define MATCH_FCVT_S_WU 0xd0100053 #define MASK_FCVT_S_WU 0xfff0007f #define MATCH_FCVT_S_L 0xd0200053 #define MASK_FCVT_S_L 0xfff0007f #define MATCH_FCVT_S_LU 0xd0300053 #define MASK_FCVT_S_LU 0xfff0007f #define MATCH_FMV_W_X 0xf0000053 #define MASK_FMV_W_X 0xfff0707f #define MATCH_FCVT_D_W 0xd2000053 #define MASK_FCVT_D_W 0xfff0007f #define MATCH_FCVT_D_WU 0xd2100053 #define MASK_FCVT_D_WU 0xfff0007f #define MATCH_FCVT_D_L 0xd2200053 #define MASK_FCVT_D_L 0xfff0007f #define MATCH_FCVT_D_LU 0xd2300053 #define MASK_FCVT_D_LU 0xfff0007f #define MATCH_FMV_D_X 0xf2000053 #define MASK_FMV_D_X 0xfff0707f #define MATCH_FCVT_Q_W 0xd6000053 #define MASK_FCVT_Q_W 0xfff0007f #define MATCH_FCVT_Q_WU 0xd6100053 #define MASK_FCVT_Q_WU 0xfff0007f #define MATCH_FCVT_Q_L 0xd6200053 #define MASK_FCVT_Q_L 0xfff0007f #define MATCH_FCVT_Q_LU 0xd6300053 #define MASK_FCVT_Q_LU 0xfff0007f #define MATCH_FMV_Q_X 0xf6000053 #define MASK_FMV_Q_X 0xfff0707f #define MATCH_FLW 0x2007 #define MASK_FLW 0x707f #define MATCH_FLD 0x3007 #define MASK_FLD 0x707f #define MATCH_FLQ 0x4007 #define MASK_FLQ 0x707f #define MATCH_FSW 0x2027 #define MASK_FSW 0x707f #define MATCH_FSD 0x3027 #define MASK_FSD 0x707f #define MATCH_FSQ 0x4027 #define MASK_FSQ 0x707f #define MATCH_FMADD_S 0x43 #define MASK_FMADD_S 0x600007f #define MATCH_FMSUB_S 0x47 #define MASK_FMSUB_S 0x600007f #define MATCH_FNMSUB_S 0x4b #define MASK_FNMSUB_S 0x600007f #define MATCH_FNMADD_S 0x4f #define MASK_FNMADD_S 0x600007f #define MATCH_FMADD_D 0x2000043 #define MASK_FMADD_D 0x600007f #define MATCH_FMSUB_D 0x2000047 #define MASK_FMSUB_D 0x600007f #define MATCH_FNMSUB_D 0x200004b #define MASK_FNMSUB_D 0x600007f #define MATCH_FNMADD_D 0x200004f #define MASK_FNMADD_D 0x600007f #define MATCH_FMADD_Q 0x6000043 #define MASK_FMADD_Q 0x600007f #define MATCH_FMSUB_Q 0x6000047 #define MASK_FMSUB_Q 0x600007f #define MATCH_FNMSUB_Q 0x600004b #define MASK_FNMSUB_Q 0x600007f #define MATCH_FNMADD_Q 0x600004f #define MASK_FNMADD_Q 0x600007f #define MATCH_C_NOP 0x1 #define MASK_C_NOP 0xffff #define MATCH_C_ADDI16SP 0x6101 #define MASK_C_ADDI16SP 0xef83 #define MATCH_C_JR 0x8002 #define MASK_C_JR 0xf07f #define MATCH_C_JALR 0x9002 #define MASK_C_JALR 0xf07f #define MATCH_C_EBREAK 0x9002 #define MASK_C_EBREAK 0xffff #define MATCH_C_LD 0x6000 #define MASK_C_LD 0xe003 #define MATCH_C_SD 0xe000 #define MASK_C_SD 0xe003 #define MATCH_C_ADDIW 0x2001 #define MASK_C_ADDIW 0xe003 #define MATCH_C_LDSP 0x6002 #define MASK_C_LDSP 0xe003 #define MATCH_C_SDSP 0xe002 #define MASK_C_SDSP 0xe003 #define MATCH_C_ADDI4SPN 0x0 #define MASK_C_ADDI4SPN 0xe003 #define MATCH_C_FLD 0x2000 #define MASK_C_FLD 0xe003 #define MATCH_C_LW 0x4000 #define MASK_C_LW 0xe003 #define MATCH_C_FLW 0x6000 #define MASK_C_FLW 0xe003 #define MATCH_C_FSD 0xa000 #define MASK_C_FSD 0xe003 #define MATCH_C_SW 0xc000 #define MASK_C_SW 0xe003 #define MATCH_C_FSW 0xe000 #define MASK_C_FSW 0xe003 #define MATCH_C_ADDI 0x1 #define MASK_C_ADDI 0xe003 #define MATCH_C_JAL 0x2001 #define MASK_C_JAL 0xe003 #define MATCH_C_LI 0x4001 #define MASK_C_LI 0xe003 #define MATCH_C_LUI 0x6001 #define MASK_C_LUI 0xe003 #define MATCH_C_SRLI 0x8001 #define MASK_C_SRLI 0xec03 #define MATCH_C_SRAI 0x8401 #define MASK_C_SRAI 0xec03 #define MATCH_C_ANDI 0x8801 #define MASK_C_ANDI 0xec03 #define MATCH_C_SUB 0x8c01 #define MASK_C_SUB 0xfc63 #define MATCH_C_XOR 0x8c21 #define MASK_C_XOR 0xfc63 #define MATCH_C_OR 0x8c41 #define MASK_C_OR 0xfc63 #define MATCH_C_AND 0x8c61 #define MASK_C_AND 0xfc63 #define MATCH_C_SUBW 0x9c01 #define MASK_C_SUBW 0xfc63 #define MATCH_C_ADDW 0x9c21 #define MASK_C_ADDW 0xfc63 #define MATCH_C_J 0xa001 #define MASK_C_J 0xe003 #define MATCH_C_BEQZ 0xc001 #define MASK_C_BEQZ 0xe003 #define MATCH_C_BNEZ 0xe001 #define MASK_C_BNEZ 0xe003 #define MATCH_C_SLLI 0x2 #define MASK_C_SLLI 0xe003 #define MATCH_C_FLDSP 0x2002 #define MASK_C_FLDSP 0xe003 #define MATCH_C_LWSP 0x4002 #define MASK_C_LWSP 0xe003 #define MATCH_C_FLWSP 0x6002 #define MASK_C_FLWSP 0xe003 #define MATCH_C_MV 0x8002 #define MASK_C_MV 0xf003 #define MATCH_C_ADD 0x9002 #define MASK_C_ADD 0xf003 #define MATCH_C_FSDSP 0xa002 #define MASK_C_FSDSP 0xe003 #define MATCH_C_SWSP 0xc002 #define MASK_C_SWSP 0xe003 #define MATCH_C_FSWSP 0xe002 #define MASK_C_FSWSP 0xe003 #define MATCH_CUSTOM0 0xb #define MASK_CUSTOM0 0x707f #define MATCH_CUSTOM0_RS1 0x200b #define MASK_CUSTOM0_RS1 0x707f #define MATCH_CUSTOM0_RS1_RS2 0x300b #define MASK_CUSTOM0_RS1_RS2 0x707f #define MATCH_CUSTOM0_RD 0x400b #define MASK_CUSTOM0_RD 0x707f #define MATCH_CUSTOM0_RD_RS1 0x600b #define MASK_CUSTOM0_RD_RS1 0x707f #define MATCH_CUSTOM0_RD_RS1_RS2 0x700b #define MASK_CUSTOM0_RD_RS1_RS2 0x707f #define MATCH_CUSTOM1 0x2b #define MASK_CUSTOM1 0x707f #define MATCH_CUSTOM1_RS1 0x202b #define MASK_CUSTOM1_RS1 0x707f #define MATCH_CUSTOM1_RS1_RS2 0x302b #define MASK_CUSTOM1_RS1_RS2 0x707f #define MATCH_CUSTOM1_RD 0x402b #define MASK_CUSTOM1_RD 0x707f #define MATCH_CUSTOM1_RD_RS1 0x602b #define MASK_CUSTOM1_RD_RS1 0x707f #define MATCH_CUSTOM1_RD_RS1_RS2 0x702b #define MASK_CUSTOM1_RD_RS1_RS2 0x707f #define MATCH_CUSTOM2 0x5b #define MASK_CUSTOM2 0x707f #define MATCH_CUSTOM2_RS1 0x205b #define MASK_CUSTOM2_RS1 0x707f #define MATCH_CUSTOM2_RS1_RS2 0x305b #define MASK_CUSTOM2_RS1_RS2 0x707f #define MATCH_CUSTOM2_RD 0x405b #define MASK_CUSTOM2_RD 0x707f #define MATCH_CUSTOM2_RD_RS1 0x605b #define MASK_CUSTOM2_RD_RS1 0x707f #define MATCH_CUSTOM2_RD_RS1_RS2 0x705b #define MASK_CUSTOM2_RD_RS1_RS2 0x707f #define MATCH_CUSTOM3 0x7b #define MASK_CUSTOM3 0x707f #define MATCH_CUSTOM3_RS1 0x207b #define MASK_CUSTOM3_RS1 0x707f #define MATCH_CUSTOM3_RS1_RS2 0x307b #define MASK_CUSTOM3_RS1_RS2 0x707f #define MATCH_CUSTOM3_RD 0x407b #define MASK_CUSTOM3_RD 0x707f #define MATCH_CUSTOM3_RD_RS1 0x607b #define MASK_CUSTOM3_RD_RS1 0x707f #define MATCH_CUSTOM3_RD_RS1_RS2 0x707b #define MASK_CUSTOM3_RD_RS1_RS2 0x707f #define CSR_FFLAGS 0x1 #define CSR_FRM 0x2 #define CSR_FCSR 0x3 #define CSR_CYCLE 0xc00 #define CSR_TIME 0xc01 #define CSR_INSTRET 0xc02 #define CSR_HPMCOUNTER3 0xc03 #define CSR_HPMCOUNTER4 0xc04 #define CSR_HPMCOUNTER5 0xc05 #define CSR_HPMCOUNTER6 0xc06 #define CSR_HPMCOUNTER7 0xc07 #define CSR_HPMCOUNTER8 0xc08 #define CSR_HPMCOUNTER9 0xc09 #define CSR_HPMCOUNTER10 0xc0a #define CSR_HPMCOUNTER11 0xc0b #define CSR_HPMCOUNTER12 0xc0c #define CSR_HPMCOUNTER13 0xc0d #define CSR_HPMCOUNTER14 0xc0e #define CSR_HPMCOUNTER15 0xc0f #define CSR_HPMCOUNTER16 0xc10 #define CSR_HPMCOUNTER17 0xc11 #define CSR_HPMCOUNTER18 0xc12 #define CSR_HPMCOUNTER19 0xc13 #define CSR_HPMCOUNTER20 0xc14 #define CSR_HPMCOUNTER21 0xc15 #define CSR_HPMCOUNTER22 0xc16 #define CSR_HPMCOUNTER23 0xc17 #define CSR_HPMCOUNTER24 0xc18 #define CSR_HPMCOUNTER25 0xc19 #define CSR_HPMCOUNTER26 0xc1a #define CSR_HPMCOUNTER27 0xc1b #define CSR_HPMCOUNTER28 0xc1c #define CSR_HPMCOUNTER29 0xc1d #define CSR_HPMCOUNTER30 0xc1e #define CSR_HPMCOUNTER31 0xc1f #define CSR_SSTATUS 0x100 #define CSR_SIE 0x104 #define CSR_STVEC 0x105 #define CSR_SCOUNTEREN 0x106 #define CSR_SSCRATCH 0x140 #define CSR_SEPC 0x141 #define CSR_SCAUSE 0x142 #define CSR_STVAL 0x143 #define CSR_SIP 0x144 #define CSR_SATP 0x180 #define CSR_MSTATUS 0x300 #define CSR_MISA 0x301 #define CSR_MEDELEG 0x302 #define CSR_MIDELEG 0x303 #define CSR_MIE 0x304 #define CSR_MTVEC 0x305 #define CSR_MCOUNTEREN 0x306 #define CSR_MSCRATCH 0x340 #define CSR_MEPC 0x341 #define CSR_MCAUSE 0x342 #define CSR_MTVAL 0x343 #define CSR_MIP 0x344 #define CSR_PMPCFG0 0x3a0 #define CSR_PMPCFG1 0x3a1 #define CSR_PMPCFG2 0x3a2 #define CSR_PMPCFG3 0x3a3 #define CSR_PMPADDR0 0x3b0 #define CSR_PMPADDR1 0x3b1 #define CSR_PMPADDR2 0x3b2 #define CSR_PMPADDR3 0x3b3 #define CSR_PMPADDR4 0x3b4 #define CSR_PMPADDR5 0x3b5 #define CSR_PMPADDR6 0x3b6 #define CSR_PMPADDR7 0x3b7 #define CSR_PMPADDR8 0x3b8 #define CSR_PMPADDR9 0x3b9 #define CSR_PMPADDR10 0x3ba #define CSR_PMPADDR11 0x3bb #define CSR_PMPADDR12 0x3bc #define CSR_PMPADDR13 0x3bd #define CSR_PMPADDR14 0x3be #define CSR_PMPADDR15 0x3bf #define CSR_TSELECT 0x7a0 #define CSR_TDATA1 0x7a1 #define CSR_TDATA2 0x7a2 #define CSR_TDATA3 0x7a3 #define CSR_DCSR 0x7b0 #define CSR_DPC 0x7b1 #define CSR_DSCRATCH 0x7b2 #define CSR_DSCRATCH0 CSR_DSCRATCH #define CSR_DSCRATCH1 0x7b3 #define CSR_MCYCLE 0xb00 #define CSR_MINSTRET 0xb02 #define CSR_MHPMCOUNTER3 0xb03 #define CSR_MHPMCOUNTER4 0xb04 #define CSR_MHPMCOUNTER5 0xb05 #define CSR_MHPMCOUNTER6 0xb06 #define CSR_MHPMCOUNTER7 0xb07 #define CSR_MHPMCOUNTER8 0xb08 #define CSR_MHPMCOUNTER9 0xb09 #define CSR_MHPMCOUNTER10 0xb0a #define CSR_MHPMCOUNTER11 0xb0b #define CSR_MHPMCOUNTER12 0xb0c #define CSR_MHPMCOUNTER13 0xb0d #define CSR_MHPMCOUNTER14 0xb0e #define CSR_MHPMCOUNTER15 0xb0f #define CSR_MHPMCOUNTER16 0xb10 #define CSR_MHPMCOUNTER17 0xb11 #define CSR_MHPMCOUNTER18 0xb12 #define CSR_MHPMCOUNTER19 0xb13 #define CSR_MHPMCOUNTER20 0xb14 #define CSR_MHPMCOUNTER21 0xb15 #define CSR_MHPMCOUNTER22 0xb16 #define CSR_MHPMCOUNTER23 0xb17 #define CSR_MHPMCOUNTER24 0xb18 #define CSR_MHPMCOUNTER25 0xb19 #define CSR_MHPMCOUNTER26 0xb1a #define CSR_MHPMCOUNTER27 0xb1b #define CSR_MHPMCOUNTER28 0xb1c #define CSR_MHPMCOUNTER29 0xb1d #define CSR_MHPMCOUNTER30 0xb1e #define CSR_MHPMCOUNTER31 0xb1f #define CSR_MHPMEVENT3 0x323 #define CSR_MHPMEVENT4 0x324 #define CSR_MHPMEVENT5 0x325 #define CSR_MHPMEVENT6 0x326 #define CSR_MHPMEVENT7 0x327 #define CSR_MHPMEVENT8 0x328 #define CSR_MHPMEVENT9 0x329 #define CSR_MHPMEVENT10 0x32a #define CSR_MHPMEVENT11 0x32b #define CSR_MHPMEVENT12 0x32c #define CSR_MHPMEVENT13 0x32d #define CSR_MHPMEVENT14 0x32e #define CSR_MHPMEVENT15 0x32f #define CSR_MHPMEVENT16 0x330 #define CSR_MHPMEVENT17 0x331 #define CSR_MHPMEVENT18 0x332 #define CSR_MHPMEVENT19 0x333 #define CSR_MHPMEVENT20 0x334 #define CSR_MHPMEVENT21 0x335 #define CSR_MHPMEVENT22 0x336 #define CSR_MHPMEVENT23 0x337 #define CSR_MHPMEVENT24 0x338 #define CSR_MHPMEVENT25 0x339 #define CSR_MHPMEVENT26 0x33a #define CSR_MHPMEVENT27 0x33b #define CSR_MHPMEVENT28 0x33c #define CSR_MHPMEVENT29 0x33d #define CSR_MHPMEVENT30 0x33e #define CSR_MHPMEVENT31 0x33f #define CSR_MVENDORID 0xf11 #define CSR_MARCHID 0xf12 #define CSR_MIMPID 0xf13 #define CSR_MHARTID 0xf14 #define CSR_CYCLEH 0xc80 #define CSR_TIMEH 0xc81 #define CSR_INSTRETH 0xc82 #define CSR_HPMCOUNTER3H 0xc83 #define CSR_HPMCOUNTER4H 0xc84 #define CSR_HPMCOUNTER5H 0xc85 #define CSR_HPMCOUNTER6H 0xc86 #define CSR_HPMCOUNTER7H 0xc87 #define CSR_HPMCOUNTER8H 0xc88 #define CSR_HPMCOUNTER9H 0xc89 #define CSR_HPMCOUNTER10H 0xc8a #define CSR_HPMCOUNTER11H 0xc8b #define CSR_HPMCOUNTER12H 0xc8c #define CSR_HPMCOUNTER13H 0xc8d #define CSR_HPMCOUNTER14H 0xc8e #define CSR_HPMCOUNTER15H 0xc8f #define CSR_HPMCOUNTER16H 0xc90 #define CSR_HPMCOUNTER17H 0xc91 #define CSR_HPMCOUNTER18H 0xc92 #define CSR_HPMCOUNTER19H 0xc93 #define CSR_HPMCOUNTER20H 0xc94 #define CSR_HPMCOUNTER21H 0xc95 #define CSR_HPMCOUNTER22H 0xc96 #define CSR_HPMCOUNTER23H 0xc97 #define CSR_HPMCOUNTER24H 0xc98 #define CSR_HPMCOUNTER25H 0xc99 #define CSR_HPMCOUNTER26H 0xc9a #define CSR_HPMCOUNTER27H 0xc9b #define CSR_HPMCOUNTER28H 0xc9c #define CSR_HPMCOUNTER29H 0xc9d #define CSR_HPMCOUNTER30H 0xc9e #define CSR_HPMCOUNTER31H 0xc9f #define CSR_MCYCLEH 0xb80 #define CSR_MINSTRETH 0xb82 #define CSR_MHPMCOUNTER3H 0xb83 #define CSR_MHPMCOUNTER4H 0xb84 #define CSR_MHPMCOUNTER5H 0xb85 #define CSR_MHPMCOUNTER6H 0xb86 #define CSR_MHPMCOUNTER7H 0xb87 #define CSR_MHPMCOUNTER8H 0xb88 #define CSR_MHPMCOUNTER9H 0xb89 #define CSR_MHPMCOUNTER10H 0xb8a #define CSR_MHPMCOUNTER11H 0xb8b #define CSR_MHPMCOUNTER12H 0xb8c #define CSR_MHPMCOUNTER13H 0xb8d #define CSR_MHPMCOUNTER14H 0xb8e #define CSR_MHPMCOUNTER15H 0xb8f #define CSR_MHPMCOUNTER16H 0xb90 #define CSR_MHPMCOUNTER17H 0xb91 #define CSR_MHPMCOUNTER18H 0xb92 #define CSR_MHPMCOUNTER19H 0xb93 #define CSR_MHPMCOUNTER20H 0xb94 #define CSR_MHPMCOUNTER21H 0xb95 #define CSR_MHPMCOUNTER22H 0xb96 #define CSR_MHPMCOUNTER23H 0xb97 #define CSR_MHPMCOUNTER24H 0xb98 #define CSR_MHPMCOUNTER25H 0xb99 #define CSR_MHPMCOUNTER26H 0xb9a #define CSR_MHPMCOUNTER27H 0xb9b #define CSR_MHPMCOUNTER28H 0xb9c #define CSR_MHPMCOUNTER29H 0xb9d #define CSR_MHPMCOUNTER30H 0xb9e #define CSR_MHPMCOUNTER31H 0xb9f #define CAUSE_MISALIGNED_FETCH 0x0 #define CAUSE_FETCH_ACCESS 0x1 #define CAUSE_ILLEGAL_INSTRUCTION 0x2 #define CAUSE_BREAKPOINT 0x3 #define CAUSE_MISALIGNED_LOAD 0x4 #define CAUSE_LOAD_ACCESS 0x5 #define CAUSE_MISALIGNED_STORE 0x6 #define CAUSE_STORE_ACCESS 0x7 #define CAUSE_USER_ECALL 0x8 #define CAUSE_SUPERVISOR_ECALL 0x9 #define CAUSE_HYPERVISOR_ECALL 0xa #define CAUSE_MACHINE_ECALL 0xb #define CAUSE_FETCH_PAGE_FAULT 0xc #define CAUSE_LOAD_PAGE_FAULT 0xd #define CAUSE_STORE_PAGE_FAULT 0xf #endif #ifdef DECLARE_INSN DECLARE_INSN(beq, MATCH_BEQ, MASK_BEQ) DECLARE_INSN(bne, MATCH_BNE, MASK_BNE) DECLARE_INSN(blt, MATCH_BLT, MASK_BLT) DECLARE_INSN(bge, MATCH_BGE, MASK_BGE) DECLARE_INSN(bltu, MATCH_BLTU, MASK_BLTU) DECLARE_INSN(bgeu, MATCH_BGEU, MASK_BGEU) DECLARE_INSN(jalr, MATCH_JALR, MASK_JALR) DECLARE_INSN(jal, MATCH_JAL, MASK_JAL) DECLARE_INSN(lui, MATCH_LUI, MASK_LUI) DECLARE_INSN(auipc, MATCH_AUIPC, MASK_AUIPC) DECLARE_INSN(addi, MATCH_ADDI, MASK_ADDI) DECLARE_INSN(slli, MATCH_SLLI, MASK_SLLI) DECLARE_INSN(slti, MATCH_SLTI, MASK_SLTI) DECLARE_INSN(sltiu, MATCH_SLTIU, MASK_SLTIU) DECLARE_INSN(xori, MATCH_XORI, MASK_XORI) DECLARE_INSN(srli, MATCH_SRLI, MASK_SRLI) DECLARE_INSN(srai, MATCH_SRAI, MASK_SRAI) DECLARE_INSN(ori, MATCH_ORI, MASK_ORI) DECLARE_INSN(andi, MATCH_ANDI, MASK_ANDI) DECLARE_INSN(add, MATCH_ADD, MASK_ADD) DECLARE_INSN(sub, MATCH_SUB, MASK_SUB) DECLARE_INSN(sll, MATCH_SLL, MASK_SLL) DECLARE_INSN(slt, MATCH_SLT, MASK_SLT) DECLARE_INSN(sltu, MATCH_SLTU, MASK_SLTU) DECLARE_INSN(xor, MATCH_XOR, MASK_XOR) DECLARE_INSN(srl, MATCH_SRL, MASK_SRL) DECLARE_INSN(sra, MATCH_SRA, MASK_SRA) DECLARE_INSN(or, MATCH_OR, MASK_OR) DECLARE_INSN(and, MATCH_AND, MASK_AND) DECLARE_INSN(addiw, MATCH_ADDIW, MASK_ADDIW) DECLARE_INSN(slliw, MATCH_SLLIW, MASK_SLLIW) DECLARE_INSN(srliw, MATCH_SRLIW, MASK_SRLIW) DECLARE_INSN(sraiw, MATCH_SRAIW, MASK_SRAIW) DECLARE_INSN(addw, MATCH_ADDW, MASK_ADDW) DECLARE_INSN(subw, MATCH_SUBW, MASK_SUBW) DECLARE_INSN(sllw, MATCH_SLLW, MASK_SLLW) DECLARE_INSN(srlw, MATCH_SRLW, MASK_SRLW) DECLARE_INSN(sraw, MATCH_SRAW, MASK_SRAW) DECLARE_INSN(lb, MATCH_LB, MASK_LB) DECLARE_INSN(lh, MATCH_LH, MASK_LH) DECLARE_INSN(lw, MATCH_LW, MASK_LW) DECLARE_INSN(ld, MATCH_LD, MASK_LD) DECLARE_INSN(lbu, MATCH_LBU, MASK_LBU) DECLARE_INSN(lhu, MATCH_LHU, MASK_LHU) DECLARE_INSN(lwu, MATCH_LWU, MASK_LWU) DECLARE_INSN(sb, MATCH_SB, MASK_SB) DECLARE_INSN(sh, MATCH_SH, MASK_SH) DECLARE_INSN(sw, MATCH_SW, MASK_SW) DECLARE_INSN(sd, MATCH_SD, MASK_SD) DECLARE_INSN(fence, MATCH_FENCE, MASK_FENCE) DECLARE_INSN(fence_i, MATCH_FENCE_I, MASK_FENCE_I) DECLARE_INSN(mul, MATCH_MUL, MASK_MUL) DECLARE_INSN(mulh, MATCH_MULH, MASK_MULH) DECLARE_INSN(mulhsu, MATCH_MULHSU, MASK_MULHSU) DECLARE_INSN(mulhu, MATCH_MULHU, MASK_MULHU) DECLARE_INSN(div, MATCH_DIV, MASK_DIV) DECLARE_INSN(divu, MATCH_DIVU, MASK_DIVU) DECLARE_INSN(rem, MATCH_REM, MASK_REM) DECLARE_INSN(remu, MATCH_REMU, MASK_REMU) DECLARE_INSN(mulw, MATCH_MULW, MASK_MULW) DECLARE_INSN(divw, MATCH_DIVW, MASK_DIVW) DECLARE_INSN(divuw, MATCH_DIVUW, MASK_DIVUW) DECLARE_INSN(remw, MATCH_REMW, MASK_REMW) DECLARE_INSN(remuw, MATCH_REMUW, MASK_REMUW) DECLARE_INSN(amoadd_w, MATCH_AMOADD_W, MASK_AMOADD_W) DECLARE_INSN(amoxor_w, MATCH_AMOXOR_W, MASK_AMOXOR_W) DECLARE_INSN(amoor_w, MATCH_AMOOR_W, MASK_AMOOR_W) DECLARE_INSN(amoand_w, MATCH_AMOAND_W, MASK_AMOAND_W) DECLARE_INSN(amomin_w, MATCH_AMOMIN_W, MASK_AMOMIN_W) DECLARE_INSN(amomax_w, MATCH_AMOMAX_W, MASK_AMOMAX_W) DECLARE_INSN(amominu_w, MATCH_AMOMINU_W, MASK_AMOMINU_W) DECLARE_INSN(amomaxu_w, MATCH_AMOMAXU_W, MASK_AMOMAXU_W) DECLARE_INSN(amoswap_w, MATCH_AMOSWAP_W, MASK_AMOSWAP_W) DECLARE_INSN(lr_w, MATCH_LR_W, MASK_LR_W) DECLARE_INSN(sc_w, MATCH_SC_W, MASK_SC_W) DECLARE_INSN(amoadd_d, MATCH_AMOADD_D, MASK_AMOADD_D) DECLARE_INSN(amoxor_d, MATCH_AMOXOR_D, MASK_AMOXOR_D) DECLARE_INSN(amoor_d, MATCH_AMOOR_D, MASK_AMOOR_D) DECLARE_INSN(amoand_d, MATCH_AMOAND_D, MASK_AMOAND_D) DECLARE_INSN(amomin_d, MATCH_AMOMIN_D, MASK_AMOMIN_D) DECLARE_INSN(amomax_d, MATCH_AMOMAX_D, MASK_AMOMAX_D) DECLARE_INSN(amominu_d, MATCH_AMOMINU_D, MASK_AMOMINU_D) DECLARE_INSN(amomaxu_d, MATCH_AMOMAXU_D, MASK_AMOMAXU_D) DECLARE_INSN(amoswap_d, MATCH_AMOSWAP_D, MASK_AMOSWAP_D) DECLARE_INSN(lr_d, MATCH_LR_D, MASK_LR_D) DECLARE_INSN(sc_d, MATCH_SC_D, MASK_SC_D) DECLARE_INSN(ecall, MATCH_ECALL, MASK_ECALL) DECLARE_INSN(ebreak, MATCH_EBREAK, MASK_EBREAK) DECLARE_INSN(uret, MATCH_URET, MASK_URET) DECLARE_INSN(sret, MATCH_SRET, MASK_SRET) DECLARE_INSN(mret, MATCH_MRET, MASK_MRET) DECLARE_INSN(dret, MATCH_DRET, MASK_DRET) DECLARE_INSN(sfence_vma, MATCH_SFENCE_VMA, MASK_SFENCE_VMA) DECLARE_INSN(wfi, MATCH_WFI, MASK_WFI) DECLARE_INSN(csrrw, MATCH_CSRRW, MASK_CSRRW) DECLARE_INSN(csrrs, MATCH_CSRRS, MASK_CSRRS) DECLARE_INSN(csrrc, MATCH_CSRRC, MASK_CSRRC) DECLARE_INSN(csrrwi, MATCH_CSRRWI, MASK_CSRRWI) DECLARE_INSN(csrrsi, MATCH_CSRRSI, MASK_CSRRSI) DECLARE_INSN(csrrci, MATCH_CSRRCI, MASK_CSRRCI) DECLARE_INSN(fadd_s, MATCH_FADD_S, MASK_FADD_S) DECLARE_INSN(fsub_s, MATCH_FSUB_S, MASK_FSUB_S) DECLARE_INSN(fmul_s, MATCH_FMUL_S, MASK_FMUL_S) DECLARE_INSN(fdiv_s, MATCH_FDIV_S, MASK_FDIV_S) DECLARE_INSN(fsgnj_s, MATCH_FSGNJ_S, MASK_FSGNJ_S) DECLARE_INSN(fsgnjn_s, MATCH_FSGNJN_S, MASK_FSGNJN_S) DECLARE_INSN(fsgnjx_s, MATCH_FSGNJX_S, MASK_FSGNJX_S) DECLARE_INSN(fmin_s, MATCH_FMIN_S, MASK_FMIN_S) DECLARE_INSN(fmax_s, MATCH_FMAX_S, MASK_FMAX_S) DECLARE_INSN(fsqrt_s, MATCH_FSQRT_S, MASK_FSQRT_S) DECLARE_INSN(fadd_d, MATCH_FADD_D, MASK_FADD_D) DECLARE_INSN(fsub_d, MATCH_FSUB_D, MASK_FSUB_D) DECLARE_INSN(fmul_d, MATCH_FMUL_D, MASK_FMUL_D) DECLARE_INSN(fdiv_d, MATCH_FDIV_D, MASK_FDIV_D) DECLARE_INSN(fsgnj_d, MATCH_FSGNJ_D, MASK_FSGNJ_D) DECLARE_INSN(fsgnjn_d, MATCH_FSGNJN_D, MASK_FSGNJN_D) DECLARE_INSN(fsgnjx_d, MATCH_FSGNJX_D, MASK_FSGNJX_D) DECLARE_INSN(fmin_d, MATCH_FMIN_D, MASK_FMIN_D) DECLARE_INSN(fmax_d, MATCH_FMAX_D, MASK_FMAX_D) DECLARE_INSN(fcvt_s_d, MATCH_FCVT_S_D, MASK_FCVT_S_D) DECLARE_INSN(fcvt_d_s, MATCH_FCVT_D_S, MASK_FCVT_D_S) DECLARE_INSN(fsqrt_d, MATCH_FSQRT_D, MASK_FSQRT_D) DECLARE_INSN(fadd_q, MATCH_FADD_Q, MASK_FADD_Q) DECLARE_INSN(fsub_q, MATCH_FSUB_Q, MASK_FSUB_Q) DECLARE_INSN(fmul_q, MATCH_FMUL_Q, MASK_FMUL_Q) DECLARE_INSN(fdiv_q, MATCH_FDIV_Q, MASK_FDIV_Q) DECLARE_INSN(fsgnj_q, MATCH_FSGNJ_Q, MASK_FSGNJ_Q) DECLARE_INSN(fsgnjn_q, MATCH_FSGNJN_Q, MASK_FSGNJN_Q) DECLARE_INSN(fsgnjx_q, MATCH_FSGNJX_Q, MASK_FSGNJX_Q) DECLARE_INSN(fmin_q, MATCH_FMIN_Q, MASK_FMIN_Q) DECLARE_INSN(fmax_q, MATCH_FMAX_Q, MASK_FMAX_Q) DECLARE_INSN(fcvt_s_q, MATCH_FCVT_S_Q, MASK_FCVT_S_Q) DECLARE_INSN(fcvt_q_s, MATCH_FCVT_Q_S, MASK_FCVT_Q_S) DECLARE_INSN(fcvt_d_q, MATCH_FCVT_D_Q, MASK_FCVT_D_Q) DECLARE_INSN(fcvt_q_d, MATCH_FCVT_Q_D, MASK_FCVT_Q_D) DECLARE_INSN(fsqrt_q, MATCH_FSQRT_Q, MASK_FSQRT_Q) DECLARE_INSN(fle_s, MATCH_FLE_S, MASK_FLE_S) DECLARE_INSN(flt_s, MATCH_FLT_S, MASK_FLT_S) DECLARE_INSN(feq_s, MATCH_FEQ_S, MASK_FEQ_S) DECLARE_INSN(fle_d, MATCH_FLE_D, MASK_FLE_D) DECLARE_INSN(flt_d, MATCH_FLT_D, MASK_FLT_D) DECLARE_INSN(feq_d, MATCH_FEQ_D, MASK_FEQ_D) DECLARE_INSN(fle_q, MATCH_FLE_Q, MASK_FLE_Q) DECLARE_INSN(flt_q, MATCH_FLT_Q, MASK_FLT_Q) DECLARE_INSN(feq_q, MATCH_FEQ_Q, MASK_FEQ_Q) DECLARE_INSN(fcvt_w_s, MATCH_FCVT_W_S, MASK_FCVT_W_S) DECLARE_INSN(fcvt_wu_s, MATCH_FCVT_WU_S, MASK_FCVT_WU_S) DECLARE_INSN(fcvt_l_s, MATCH_FCVT_L_S, MASK_FCVT_L_S) DECLARE_INSN(fcvt_lu_s, MATCH_FCVT_LU_S, MASK_FCVT_LU_S) DECLARE_INSN(fmv_x_w, MATCH_FMV_X_W, MASK_FMV_X_W) DECLARE_INSN(fclass_s, MATCH_FCLASS_S, MASK_FCLASS_S) DECLARE_INSN(fcvt_w_d, MATCH_FCVT_W_D, MASK_FCVT_W_D) DECLARE_INSN(fcvt_wu_d, MATCH_FCVT_WU_D, MASK_FCVT_WU_D) DECLARE_INSN(fcvt_l_d, MATCH_FCVT_L_D, MASK_FCVT_L_D) DECLARE_INSN(fcvt_lu_d, MATCH_FCVT_LU_D, MASK_FCVT_LU_D) DECLARE_INSN(fmv_x_d, MATCH_FMV_X_D, MASK_FMV_X_D) DECLARE_INSN(fclass_d, MATCH_FCLASS_D, MASK_FCLASS_D) DECLARE_INSN(fcvt_w_q, MATCH_FCVT_W_Q, MASK_FCVT_W_Q) DECLARE_INSN(fcvt_wu_q, MATCH_FCVT_WU_Q, MASK_FCVT_WU_Q) DECLARE_INSN(fcvt_l_q, MATCH_FCVT_L_Q, MASK_FCVT_L_Q) DECLARE_INSN(fcvt_lu_q, MATCH_FCVT_LU_Q, MASK_FCVT_LU_Q) DECLARE_INSN(fmv_x_q, MATCH_FMV_X_Q, MASK_FMV_X_Q) DECLARE_INSN(fclass_q, MATCH_FCLASS_Q, MASK_FCLASS_Q) DECLARE_INSN(fcvt_s_w, MATCH_FCVT_S_W, MASK_FCVT_S_W) DECLARE_INSN(fcvt_s_wu, MATCH_FCVT_S_WU, MASK_FCVT_S_WU) DECLARE_INSN(fcvt_s_l, MATCH_FCVT_S_L, MASK_FCVT_S_L) DECLARE_INSN(fcvt_s_lu, MATCH_FCVT_S_LU, MASK_FCVT_S_LU) DECLARE_INSN(fmv_w_x, MATCH_FMV_W_X, MASK_FMV_W_X) DECLARE_INSN(fcvt_d_w, MATCH_FCVT_D_W, MASK_FCVT_D_W) DECLARE_INSN(fcvt_d_wu, MATCH_FCVT_D_WU, MASK_FCVT_D_WU) DECLARE_INSN(fcvt_d_l, MATCH_FCVT_D_L, MASK_FCVT_D_L) DECLARE_INSN(fcvt_d_lu, MATCH_FCVT_D_LU, MASK_FCVT_D_LU) DECLARE_INSN(fmv_d_x, MATCH_FMV_D_X, MASK_FMV_D_X) DECLARE_INSN(fcvt_q_w, MATCH_FCVT_Q_W, MASK_FCVT_Q_W) DECLARE_INSN(fcvt_q_wu, MATCH_FCVT_Q_WU, MASK_FCVT_Q_WU) DECLARE_INSN(fcvt_q_l, MATCH_FCVT_Q_L, MASK_FCVT_Q_L) DECLARE_INSN(fcvt_q_lu, MATCH_FCVT_Q_LU, MASK_FCVT_Q_LU) DECLARE_INSN(fmv_q_x, MATCH_FMV_Q_X, MASK_FMV_Q_X) DECLARE_INSN(flw, MATCH_FLW, MASK_FLW) DECLARE_INSN(fld, MATCH_FLD, MASK_FLD) DECLARE_INSN(flq, MATCH_FLQ, MASK_FLQ) DECLARE_INSN(fsw, MATCH_FSW, MASK_FSW) DECLARE_INSN(fsd, MATCH_FSD, MASK_FSD) DECLARE_INSN(fsq, MATCH_FSQ, MASK_FSQ) DECLARE_INSN(fmadd_s, MATCH_FMADD_S, MASK_FMADD_S) DECLARE_INSN(fmsub_s, MATCH_FMSUB_S, MASK_FMSUB_S) DECLARE_INSN(fnmsub_s, MATCH_FNMSUB_S, MASK_FNMSUB_S) DECLARE_INSN(fnmadd_s, MATCH_FNMADD_S, MASK_FNMADD_S) DECLARE_INSN(fmadd_d, MATCH_FMADD_D, MASK_FMADD_D) DECLARE_INSN(fmsub_d, MATCH_FMSUB_D, MASK_FMSUB_D) DECLARE_INSN(fnmsub_d, MATCH_FNMSUB_D, MASK_FNMSUB_D) DECLARE_INSN(fnmadd_d, MATCH_FNMADD_D, MASK_FNMADD_D) DECLARE_INSN(fmadd_q, MATCH_FMADD_Q, MASK_FMADD_Q) DECLARE_INSN(fmsub_q, MATCH_FMSUB_Q, MASK_FMSUB_Q) DECLARE_INSN(fnmsub_q, MATCH_FNMSUB_Q, MASK_FNMSUB_Q) DECLARE_INSN(fnmadd_q, MATCH_FNMADD_Q, MASK_FNMADD_Q) DECLARE_INSN(c_nop, MATCH_C_NOP, MASK_C_NOP) DECLARE_INSN(c_addi16sp, MATCH_C_ADDI16SP, MASK_C_ADDI16SP) DECLARE_INSN(c_jr, MATCH_C_JR, MASK_C_JR) DECLARE_INSN(c_jalr, MATCH_C_JALR, MASK_C_JALR) DECLARE_INSN(c_ebreak, MATCH_C_EBREAK, MASK_C_EBREAK) DECLARE_INSN(c_ld, MATCH_C_LD, MASK_C_LD) DECLARE_INSN(c_sd, MATCH_C_SD, MASK_C_SD) DECLARE_INSN(c_addiw, MATCH_C_ADDIW, MASK_C_ADDIW) DECLARE_INSN(c_ldsp, MATCH_C_LDSP, MASK_C_LDSP) DECLARE_INSN(c_sdsp, MATCH_C_SDSP, MASK_C_SDSP) DECLARE_INSN(c_addi4spn, MATCH_C_ADDI4SPN, MASK_C_ADDI4SPN) DECLARE_INSN(c_fld, MATCH_C_FLD, MASK_C_FLD) DECLARE_INSN(c_lw, MATCH_C_LW, MASK_C_LW) DECLARE_INSN(c_flw, MATCH_C_FLW, MASK_C_FLW) DECLARE_INSN(c_fsd, MATCH_C_FSD, MASK_C_FSD) DECLARE_INSN(c_sw, MATCH_C_SW, MASK_C_SW) DECLARE_INSN(c_fsw, MATCH_C_FSW, MASK_C_FSW) DECLARE_INSN(c_addi, MATCH_C_ADDI, MASK_C_ADDI) DECLARE_INSN(c_jal, MATCH_C_JAL, MASK_C_JAL) DECLARE_INSN(c_li, MATCH_C_LI, MASK_C_LI) DECLARE_INSN(c_lui, MATCH_C_LUI, MASK_C_LUI) DECLARE_INSN(c_srli, MATCH_C_SRLI, MASK_C_SRLI) DECLARE_INSN(c_srai, MATCH_C_SRAI, MASK_C_SRAI) DECLARE_INSN(c_andi, MATCH_C_ANDI, MASK_C_ANDI) DECLARE_INSN(c_sub, MATCH_C_SUB, MASK_C_SUB) DECLARE_INSN(c_xor, MATCH_C_XOR, MASK_C_XOR) DECLARE_INSN(c_or, MATCH_C_OR, MASK_C_OR) DECLARE_INSN(c_and, MATCH_C_AND, MASK_C_AND) DECLARE_INSN(c_subw, MATCH_C_SUBW, MASK_C_SUBW) DECLARE_INSN(c_addw, MATCH_C_ADDW, MASK_C_ADDW) DECLARE_INSN(c_j, MATCH_C_J, MASK_C_J) DECLARE_INSN(c_beqz, MATCH_C_BEQZ, MASK_C_BEQZ) DECLARE_INSN(c_bnez, MATCH_C_BNEZ, MASK_C_BNEZ) DECLARE_INSN(c_slli, MATCH_C_SLLI, MASK_C_SLLI) DECLARE_INSN(c_fldsp, MATCH_C_FLDSP, MASK_C_FLDSP) DECLARE_INSN(c_lwsp, MATCH_C_LWSP, MASK_C_LWSP) DECLARE_INSN(c_flwsp, MATCH_C_FLWSP, MASK_C_FLWSP) DECLARE_INSN(c_mv, MATCH_C_MV, MASK_C_MV) DECLARE_INSN(c_add, MATCH_C_ADD, MASK_C_ADD) DECLARE_INSN(c_fsdsp, MATCH_C_FSDSP, MASK_C_FSDSP) DECLARE_INSN(c_swsp, MATCH_C_SWSP, MASK_C_SWSP) DECLARE_INSN(c_fswsp, MATCH_C_FSWSP, MASK_C_FSWSP) DECLARE_INSN(custom0, MATCH_CUSTOM0, MASK_CUSTOM0) DECLARE_INSN(custom0_rs1, MATCH_CUSTOM0_RS1, MASK_CUSTOM0_RS1) DECLARE_INSN(custom0_rs1_rs2, MATCH_CUSTOM0_RS1_RS2, MASK_CUSTOM0_RS1_RS2) DECLARE_INSN(custom0_rd, MATCH_CUSTOM0_RD, MASK_CUSTOM0_RD) DECLARE_INSN(custom0_rd_rs1, MATCH_CUSTOM0_RD_RS1, MASK_CUSTOM0_RD_RS1) DECLARE_INSN(custom0_rd_rs1_rs2, MATCH_CUSTOM0_RD_RS1_RS2, MASK_CUSTOM0_RD_RS1_RS2) DECLARE_INSN(custom1, MATCH_CUSTOM1, MASK_CUSTOM1) DECLARE_INSN(custom1_rs1, MATCH_CUSTOM1_RS1, MASK_CUSTOM1_RS1) DECLARE_INSN(custom1_rs1_rs2, MATCH_CUSTOM1_RS1_RS2, MASK_CUSTOM1_RS1_RS2) DECLARE_INSN(custom1_rd, MATCH_CUSTOM1_RD, MASK_CUSTOM1_RD) DECLARE_INSN(custom1_rd_rs1, MATCH_CUSTOM1_RD_RS1, MASK_CUSTOM1_RD_RS1) DECLARE_INSN(custom1_rd_rs1_rs2, MATCH_CUSTOM1_RD_RS1_RS2, MASK_CUSTOM1_RD_RS1_RS2) DECLARE_INSN(custom2, MATCH_CUSTOM2, MASK_CUSTOM2) DECLARE_INSN(custom2_rs1, MATCH_CUSTOM2_RS1, MASK_CUSTOM2_RS1) DECLARE_INSN(custom2_rs1_rs2, MATCH_CUSTOM2_RS1_RS2, MASK_CUSTOM2_RS1_RS2) DECLARE_INSN(custom2_rd, MATCH_CUSTOM2_RD, MASK_CUSTOM2_RD) DECLARE_INSN(custom2_rd_rs1, MATCH_CUSTOM2_RD_RS1, MASK_CUSTOM2_RD_RS1) DECLARE_INSN(custom2_rd_rs1_rs2, MATCH_CUSTOM2_RD_RS1_RS2, MASK_CUSTOM2_RD_RS1_RS2) DECLARE_INSN(custom3, MATCH_CUSTOM3, MASK_CUSTOM3) DECLARE_INSN(custom3_rs1, MATCH_CUSTOM3_RS1, MASK_CUSTOM3_RS1) DECLARE_INSN(custom3_rs1_rs2, MATCH_CUSTOM3_RS1_RS2, MASK_CUSTOM3_RS1_RS2) DECLARE_INSN(custom3_rd, MATCH_CUSTOM3_RD, MASK_CUSTOM3_RD) DECLARE_INSN(custom3_rd_rs1, MATCH_CUSTOM3_RD_RS1, MASK_CUSTOM3_RD_RS1) DECLARE_INSN(custom3_rd_rs1_rs2, MATCH_CUSTOM3_RD_RS1_RS2, MASK_CUSTOM3_RD_RS1_RS2) #endif #ifdef DECLARE_CSR DECLARE_CSR(fflags, CSR_FFLAGS) DECLARE_CSR(frm, CSR_FRM) DECLARE_CSR(fcsr, CSR_FCSR) DECLARE_CSR(cycle, CSR_CYCLE) DECLARE_CSR(time, CSR_TIME) DECLARE_CSR(instret, CSR_INSTRET) DECLARE_CSR(hpmcounter3, CSR_HPMCOUNTER3) DECLARE_CSR(hpmcounter4, CSR_HPMCOUNTER4) DECLARE_CSR(hpmcounter5, CSR_HPMCOUNTER5) DECLARE_CSR(hpmcounter6, CSR_HPMCOUNTER6) DECLARE_CSR(hpmcounter7, CSR_HPMCOUNTER7) DECLARE_CSR(hpmcounter8, CSR_HPMCOUNTER8) DECLARE_CSR(hpmcounter9, CSR_HPMCOUNTER9) DECLARE_CSR(hpmcounter10, CSR_HPMCOUNTER10) DECLARE_CSR(hpmcounter11, CSR_HPMCOUNTER11) DECLARE_CSR(hpmcounter12, CSR_HPMCOUNTER12) DECLARE_CSR(hpmcounter13, CSR_HPMCOUNTER13) DECLARE_CSR(hpmcounter14, CSR_HPMCOUNTER14) DECLARE_CSR(hpmcounter15, CSR_HPMCOUNTER15) DECLARE_CSR(hpmcounter16, CSR_HPMCOUNTER16) DECLARE_CSR(hpmcounter17, CSR_HPMCOUNTER17) DECLARE_CSR(hpmcounter18, CSR_HPMCOUNTER18) DECLARE_CSR(hpmcounter19, CSR_HPMCOUNTER19) DECLARE_CSR(hpmcounter20, CSR_HPMCOUNTER20) DECLARE_CSR(hpmcounter21, CSR_HPMCOUNTER21) DECLARE_CSR(hpmcounter22, CSR_HPMCOUNTER22) DECLARE_CSR(hpmcounter23, CSR_HPMCOUNTER23) DECLARE_CSR(hpmcounter24, CSR_HPMCOUNTER24) DECLARE_CSR(hpmcounter25, CSR_HPMCOUNTER25) DECLARE_CSR(hpmcounter26, CSR_HPMCOUNTER26) DECLARE_CSR(hpmcounter27, CSR_HPMCOUNTER27) DECLARE_CSR(hpmcounter28, CSR_HPMCOUNTER28) DECLARE_CSR(hpmcounter29, CSR_HPMCOUNTER29) DECLARE_CSR(hpmcounter30, CSR_HPMCOUNTER30) DECLARE_CSR(hpmcounter31, CSR_HPMCOUNTER31) DECLARE_CSR(sstatus, CSR_SSTATUS) DECLARE_CSR(sie, CSR_SIE) DECLARE_CSR(stvec, CSR_STVEC) DECLARE_CSR(scounteren, CSR_SCOUNTEREN) DECLARE_CSR(sscratch, CSR_SSCRATCH) DECLARE_CSR(sepc, CSR_SEPC) DECLARE_CSR(scause, CSR_SCAUSE) DECLARE_CSR(stval, CSR_STVAL) DECLARE_CSR(sip, CSR_SIP) DECLARE_CSR(satp, CSR_SATP) DECLARE_CSR(mstatus, CSR_MSTATUS) DECLARE_CSR(misa, CSR_MISA) DECLARE_CSR(medeleg, CSR_MEDELEG) DECLARE_CSR(mideleg, CSR_MIDELEG) DECLARE_CSR(mie, CSR_MIE) DECLARE_CSR(mtvec, CSR_MTVEC) DECLARE_CSR(mcounteren, CSR_MCOUNTEREN) DECLARE_CSR(mscratch, CSR_MSCRATCH) DECLARE_CSR(mepc, CSR_MEPC) DECLARE_CSR(mcause, CSR_MCAUSE) DECLARE_CSR(mtval, CSR_MTVAL) DECLARE_CSR(mip, CSR_MIP) DECLARE_CSR(pmpcfg0, CSR_PMPCFG0) DECLARE_CSR(pmpcfg1, CSR_PMPCFG1) DECLARE_CSR(pmpcfg2, CSR_PMPCFG2) DECLARE_CSR(pmpcfg3, CSR_PMPCFG3) DECLARE_CSR(pmpaddr0, CSR_PMPADDR0) DECLARE_CSR(pmpaddr1, CSR_PMPADDR1) DECLARE_CSR(pmpaddr2, CSR_PMPADDR2) DECLARE_CSR(pmpaddr3, CSR_PMPADDR3) DECLARE_CSR(pmpaddr4, CSR_PMPADDR4) DECLARE_CSR(pmpaddr5, CSR_PMPADDR5) DECLARE_CSR(pmpaddr6, CSR_PMPADDR6) DECLARE_CSR(pmpaddr7, CSR_PMPADDR7) DECLARE_CSR(pmpaddr8, CSR_PMPADDR8) DECLARE_CSR(pmpaddr9, CSR_PMPADDR9) DECLARE_CSR(pmpaddr10, CSR_PMPADDR10) DECLARE_CSR(pmpaddr11, CSR_PMPADDR11) DECLARE_CSR(pmpaddr12, CSR_PMPADDR12) DECLARE_CSR(pmpaddr13, CSR_PMPADDR13) DECLARE_CSR(pmpaddr14, CSR_PMPADDR14) DECLARE_CSR(pmpaddr15, CSR_PMPADDR15) DECLARE_CSR(tselect, CSR_TSELECT) DECLARE_CSR(tdata1, CSR_TDATA1) DECLARE_CSR(tdata2, CSR_TDATA2) DECLARE_CSR(tdata3, CSR_TDATA3) DECLARE_CSR(dcsr, CSR_DCSR) DECLARE_CSR(dpc, CSR_DPC) DECLARE_CSR(dscratch, CSR_DSCRATCH) DECLARE_CSR(dscratch0, CSR_DSCRATCH0) DECLARE_CSR(dscratch1, CSR_DSCRATCH1) DECLARE_CSR(mcycle, CSR_MCYCLE) DECLARE_CSR(minstret, CSR_MINSTRET) DECLARE_CSR(mhpmcounter3, CSR_MHPMCOUNTER3) DECLARE_CSR(mhpmcounter4, CSR_MHPMCOUNTER4) DECLARE_CSR(mhpmcounter5, CSR_MHPMCOUNTER5) DECLARE_CSR(mhpmcounter6, CSR_MHPMCOUNTER6) DECLARE_CSR(mhpmcounter7, CSR_MHPMCOUNTER7) DECLARE_CSR(mhpmcounter8, CSR_MHPMCOUNTER8) DECLARE_CSR(mhpmcounter9, CSR_MHPMCOUNTER9) DECLARE_CSR(mhpmcounter10, CSR_MHPMCOUNTER10) DECLARE_CSR(mhpmcounter11, CSR_MHPMCOUNTER11) DECLARE_CSR(mhpmcounter12, CSR_MHPMCOUNTER12) DECLARE_CSR(mhpmcounter13, CSR_MHPMCOUNTER13) DECLARE_CSR(mhpmcounter14, CSR_MHPMCOUNTER14) DECLARE_CSR(mhpmcounter15, CSR_MHPMCOUNTER15) DECLARE_CSR(mhpmcounter16, CSR_MHPMCOUNTER16) DECLARE_CSR(mhpmcounter17, CSR_MHPMCOUNTER17) DECLARE_CSR(mhpmcounter18, CSR_MHPMCOUNTER18) DECLARE_CSR(mhpmcounter19, CSR_MHPMCOUNTER19) DECLARE_CSR(mhpmcounter20, CSR_MHPMCOUNTER20) DECLARE_CSR(mhpmcounter21, CSR_MHPMCOUNTER21) DECLARE_CSR(mhpmcounter22, CSR_MHPMCOUNTER22) DECLARE_CSR(mhpmcounter23, CSR_MHPMCOUNTER23) DECLARE_CSR(mhpmcounter24, CSR_MHPMCOUNTER24) DECLARE_CSR(mhpmcounter25, CSR_MHPMCOUNTER25) DECLARE_CSR(mhpmcounter26, CSR_MHPMCOUNTER26) DECLARE_CSR(mhpmcounter27, CSR_MHPMCOUNTER27) DECLARE_CSR(mhpmcounter28, CSR_MHPMCOUNTER28) DECLARE_CSR(mhpmcounter29, CSR_MHPMCOUNTER29) DECLARE_CSR(mhpmcounter30, CSR_MHPMCOUNTER30) DECLARE_CSR(mhpmcounter31, CSR_MHPMCOUNTER31) DECLARE_CSR(mhpmevent3, CSR_MHPMEVENT3) DECLARE_CSR(mhpmevent4, CSR_MHPMEVENT4) DECLARE_CSR(mhpmevent5, CSR_MHPMEVENT5) DECLARE_CSR(mhpmevent6, CSR_MHPMEVENT6) DECLARE_CSR(mhpmevent7, CSR_MHPMEVENT7) DECLARE_CSR(mhpmevent8, CSR_MHPMEVENT8) DECLARE_CSR(mhpmevent9, CSR_MHPMEVENT9) DECLARE_CSR(mhpmevent10, CSR_MHPMEVENT10) DECLARE_CSR(mhpmevent11, CSR_MHPMEVENT11) DECLARE_CSR(mhpmevent12, CSR_MHPMEVENT12) DECLARE_CSR(mhpmevent13, CSR_MHPMEVENT13) DECLARE_CSR(mhpmevent14, CSR_MHPMEVENT14) DECLARE_CSR(mhpmevent15, CSR_MHPMEVENT15) DECLARE_CSR(mhpmevent16, CSR_MHPMEVENT16) DECLARE_CSR(mhpmevent17, CSR_MHPMEVENT17) DECLARE_CSR(mhpmevent18, CSR_MHPMEVENT18) DECLARE_CSR(mhpmevent19, CSR_MHPMEVENT19) DECLARE_CSR(mhpmevent20, CSR_MHPMEVENT20) DECLARE_CSR(mhpmevent21, CSR_MHPMEVENT21) DECLARE_CSR(mhpmevent22, CSR_MHPMEVENT22) DECLARE_CSR(mhpmevent23, CSR_MHPMEVENT23) DECLARE_CSR(mhpmevent24, CSR_MHPMEVENT24) DECLARE_CSR(mhpmevent25, CSR_MHPMEVENT25) DECLARE_CSR(mhpmevent26, CSR_MHPMEVENT26) DECLARE_CSR(mhpmevent27, CSR_MHPMEVENT27) DECLARE_CSR(mhpmevent28, CSR_MHPMEVENT28) DECLARE_CSR(mhpmevent29, CSR_MHPMEVENT29) DECLARE_CSR(mhpmevent30, CSR_MHPMEVENT30) DECLARE_CSR(mhpmevent31, CSR_MHPMEVENT31) DECLARE_CSR(mvendorid, CSR_MVENDORID) DECLARE_CSR(marchid, CSR_MARCHID) DECLARE_CSR(mimpid, CSR_MIMPID) DECLARE_CSR(mhartid, CSR_MHARTID) DECLARE_CSR(cycleh, CSR_CYCLEH) DECLARE_CSR(timeh, CSR_TIMEH) DECLARE_CSR(instreth, CSR_INSTRETH) DECLARE_CSR(hpmcounter3h, CSR_HPMCOUNTER3H) DECLARE_CSR(hpmcounter4h, CSR_HPMCOUNTER4H) DECLARE_CSR(hpmcounter5h, CSR_HPMCOUNTER5H) DECLARE_CSR(hpmcounter6h, CSR_HPMCOUNTER6H) DECLARE_CSR(hpmcounter7h, CSR_HPMCOUNTER7H) DECLARE_CSR(hpmcounter8h, CSR_HPMCOUNTER8H) DECLARE_CSR(hpmcounter9h, CSR_HPMCOUNTER9H) DECLARE_CSR(hpmcounter10h, CSR_HPMCOUNTER10H) DECLARE_CSR(hpmcounter11h, CSR_HPMCOUNTER11H) DECLARE_CSR(hpmcounter12h, CSR_HPMCOUNTER12H) DECLARE_CSR(hpmcounter13h, CSR_HPMCOUNTER13H) DECLARE_CSR(hpmcounter14h, CSR_HPMCOUNTER14H) DECLARE_CSR(hpmcounter15h, CSR_HPMCOUNTER15H) DECLARE_CSR(hpmcounter16h, CSR_HPMCOUNTER16H) DECLARE_CSR(hpmcounter17h, CSR_HPMCOUNTER17H) DECLARE_CSR(hpmcounter18h, CSR_HPMCOUNTER18H) DECLARE_CSR(hpmcounter19h, CSR_HPMCOUNTER19H) DECLARE_CSR(hpmcounter20h, CSR_HPMCOUNTER20H) DECLARE_CSR(hpmcounter21h, CSR_HPMCOUNTER21H) DECLARE_CSR(hpmcounter22h, CSR_HPMCOUNTER22H) DECLARE_CSR(hpmcounter23h, CSR_HPMCOUNTER23H) DECLARE_CSR(hpmcounter24h, CSR_HPMCOUNTER24H) DECLARE_CSR(hpmcounter25h, CSR_HPMCOUNTER25H) DECLARE_CSR(hpmcounter26h, CSR_HPMCOUNTER26H) DECLARE_CSR(hpmcounter27h, CSR_HPMCOUNTER27H) DECLARE_CSR(hpmcounter28h, CSR_HPMCOUNTER28H) DECLARE_CSR(hpmcounter29h, CSR_HPMCOUNTER29H) DECLARE_CSR(hpmcounter30h, CSR_HPMCOUNTER30H) DECLARE_CSR(hpmcounter31h, CSR_HPMCOUNTER31H) DECLARE_CSR(mcycleh, CSR_MCYCLEH) DECLARE_CSR(minstreth, CSR_MINSTRETH) DECLARE_CSR(mhpmcounter3h, CSR_MHPMCOUNTER3H) DECLARE_CSR(mhpmcounter4h, CSR_MHPMCOUNTER4H) DECLARE_CSR(mhpmcounter5h, CSR_MHPMCOUNTER5H) DECLARE_CSR(mhpmcounter6h, CSR_MHPMCOUNTER6H) DECLARE_CSR(mhpmcounter7h, CSR_MHPMCOUNTER7H) DECLARE_CSR(mhpmcounter8h, CSR_MHPMCOUNTER8H) DECLARE_CSR(mhpmcounter9h, CSR_MHPMCOUNTER9H) DECLARE_CSR(mhpmcounter10h, CSR_MHPMCOUNTER10H) DECLARE_CSR(mhpmcounter11h, CSR_MHPMCOUNTER11H) DECLARE_CSR(mhpmcounter12h, CSR_MHPMCOUNTER12H) DECLARE_CSR(mhpmcounter13h, CSR_MHPMCOUNTER13H) DECLARE_CSR(mhpmcounter14h, CSR_MHPMCOUNTER14H) DECLARE_CSR(mhpmcounter15h, CSR_MHPMCOUNTER15H) DECLARE_CSR(mhpmcounter16h, CSR_MHPMCOUNTER16H) DECLARE_CSR(mhpmcounter17h, CSR_MHPMCOUNTER17H) DECLARE_CSR(mhpmcounter18h, CSR_MHPMCOUNTER18H) DECLARE_CSR(mhpmcounter19h, CSR_MHPMCOUNTER19H) DECLARE_CSR(mhpmcounter20h, CSR_MHPMCOUNTER20H) DECLARE_CSR(mhpmcounter21h, CSR_MHPMCOUNTER21H) DECLARE_CSR(mhpmcounter22h, CSR_MHPMCOUNTER22H) DECLARE_CSR(mhpmcounter23h, CSR_MHPMCOUNTER23H) DECLARE_CSR(mhpmcounter24h, CSR_MHPMCOUNTER24H) DECLARE_CSR(mhpmcounter25h, CSR_MHPMCOUNTER25H) DECLARE_CSR(mhpmcounter26h, CSR_MHPMCOUNTER26H) DECLARE_CSR(mhpmcounter27h, CSR_MHPMCOUNTER27H) DECLARE_CSR(mhpmcounter28h, CSR_MHPMCOUNTER28H) DECLARE_CSR(mhpmcounter29h, CSR_MHPMCOUNTER29H) DECLARE_CSR(mhpmcounter30h, CSR_MHPMCOUNTER30H) DECLARE_CSR(mhpmcounter31h, CSR_MHPMCOUNTER31H) #endif #ifdef DECLARE_CAUSE DECLARE_CAUSE("misaligned fetch", CAUSE_MISALIGNED_FETCH) DECLARE_CAUSE("fetch access", CAUSE_FETCH_ACCESS) DECLARE_CAUSE("illegal instruction", CAUSE_ILLEGAL_INSTRUCTION) DECLARE_CAUSE("breakpoint", CAUSE_BREAKPOINT) DECLARE_CAUSE("misaligned load", CAUSE_MISALIGNED_LOAD) DECLARE_CAUSE("load access", CAUSE_LOAD_ACCESS) DECLARE_CAUSE("misaligned store", CAUSE_MISALIGNED_STORE) DECLARE_CAUSE("store access", CAUSE_STORE_ACCESS) DECLARE_CAUSE("user_ecall", CAUSE_USER_ECALL) DECLARE_CAUSE("supervisor_ecall", CAUSE_SUPERVISOR_ECALL) DECLARE_CAUSE("hypervisor_ecall", CAUSE_HYPERVISOR_ECALL) DECLARE_CAUSE("machine_ecall", CAUSE_MACHINE_ECALL) DECLARE_CAUSE("fetch page fault", CAUSE_FETCH_PAGE_FAULT) DECLARE_CAUSE("load page fault", CAUSE_LOAD_PAGE_FAULT) DECLARE_CAUSE("store page fault", CAUSE_STORE_PAGE_FAULT) #endif
#!/usr/bin/env python3 from string import Template import argparse import os.path import sys import binascii parser = argparse.ArgumentParser(description='Convert binary file to verilog rom') parser.add_argument('filename', metavar='filename', nargs=1, help='filename of input binary') args = parser.parse_args() file = args.filename[0]; # check that file exists if not os.path.isfile(file): print("File {} does not exist.".format(filename)) sys.exit(1) filename = os.path.splitext(file)[0] license = """\ /* Copyright 2018 ETH Zurich and University of Bologna. * Copyright and related rights are licensed under the Solderpad Hardware * License, Version 0.51 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law * or agreed to in writing, software, hardware and materials distributed under * this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * File: $filename.v * * Description: Auto-generated bootrom */ // Auto-generated code """ module = """\ module $filename ( input logic clk_i, input logic req_i, input logic [63:0] addr_i, output logic [63:0] rdata_o ); localparam int unsigned RomSize = $size; logic [RomSize-1:0][63:0] mem; assign mem = { $content }; logic [$$clog2(RomSize)-1:0] addr_q; always_ff @(posedge clk_i) begin if (req_i) begin addr_q <= addr_i[$$clog2(RomSize)-1+3:3]; end end // this prevents spurious Xes from propagating into // the speculative fetch stage of the core always_comb begin : p_outmux rdata_o = '0; if (addr_q < $$clog2(RomSize)'(RomSize)) begin rdata_o = mem[addr_q]; end end endmodule """ c_var = """\ // Auto-generated code const int reset_vec_size = $size; uint32_t reset_vec[reset_vec_size] = { $content }; """ def read_bin(): with open(filename + ".img", 'rb') as f: rom = binascii.hexlify(f.read()) rom = map(''.join, zip(rom[::2], rom[1::2])) # align to 64 bit align = (int((len(rom) + 7) / 8 )) * 8; for i in range(len(rom), align): rom.append("00") return rom rom = read_bin() """ Generate C header file for simulator """ with open(filename + ".h", "w") as f: rom_str = "" # process in junks of 32 bit (4 byte) for i in range(0, int(len(rom)/4)): rom_str += " 0x" + "".join(rom[i*4:i*4+4][::-1]) + ",\n" # remove the trailing comma rom_str = rom_str[:-2] s = Template(c_var) f.write(s.substitute(filename=filename, size=int(len(rom)/4), content=rom_str)) f.close() """ Generate SystemVerilog bootcode for FPGA and ASIC """ with open(filename + ".sv", "w") as f: rom_str = "" # process in junks of 64 bit (8 byte) for i in reversed(range(int(len(rom)/8))): rom_str += " 64'h" + "".join(rom[i*8+4:i*8+8][::-1]) + "_" + "".join(rom[i*8:i*8+4][::-1]) + ",\n" # remove the trailing comma rom_str = rom_str[:-2] f.write(license) s = Template(module) f.write(s.substitute(filename=filename, size=int(len(rom)/8), content=rom_str))
/* See LICENSE.SiFive for license details. */ OUTPUT_ARCH( "riscv" ) ENTRY( entry ) SECTIONS { .whereto 0x300 : { *(.whereto) } . = 0x800; .text : { *(.text) } _end = .; }
# See LICENSE.SiFive for license details debug_rom = debug_rom.sv debug_rom_one_scratch.sv GCC?=riscv64-unknown-elf-gcc OBJCOPY?=riscv64-unknown-elf-objcopy OBJDUMP?=riscv64-unknown-elf-objdump PYTHON?=python all: $(debug_rom) %.sv: %.img $(PYTHON) gen_rom.py $< %.img: %.bin dd if=$< of=$@ bs=256 count=1 %.bin: %.elf $(OBJCOPY) -O binary $< $@ %.elf: $(findstring debug_rom, $(debug_rom)).S link.ld $(GCC) $(if $(findstring one_scratch,$@),,-DSND_SCRATCH=1) -I$(RISCV)/include -Tlink.ld $< -nostdlib -fPIC -static -Wl,--no-gc-sections -o $@ %.dump: %.elf $(OBJDUMP) -d $< --disassemble-all --disassemble-zeroes --section=.text --section=.text.startup --section=.text.init --section=.data > $@ clean: rm -f *.img *.dump *.bin *.sv
# Overview This document specifies the processor debug system. The debug system implements run-control debug and bus access functionality according to the [RISC-V Debug Specification 0.13.2](https://github.com/riscv/riscv-debug-spec/raw/4e0bb0fc2d843473db2356623792c6b7603b94d4/riscv-debug-release.pdf). It can be accessed over JTAG (IEEE Std 1149.1-2013). ## Features - Run-control debug functionality according to the [RISC-V Debug Specification version 0.13.2](https://github.com/riscv/riscv-debug-spec/raw/4e0bb0fc2d843473db2356623792c6b7603b94d4/riscv-debug-release.pdf), which includes all standard debug features: breakpoints, stepping, access to the CPU's GPRs and arbitrary memory locations. - Implementation following the Execution Based method as outlined in Section A.2 of the RISC-V Debug Specification. This allows the execution of arbitrary instructions on the core and requires minimal changes to the core. - JTAG Debug Transport Module (DTM) according to the RISC-V Debug Specification. - System Bus Access with generic 32 or 64 bit bus interface. - Support for up to 2^20 harts through one Debug Module - Support for arbitrary memory location of DM - Support for one debug scratch register if the DM is located at the zero page. ## Description The debug system described in this document consists of two modules, which are implemented according to the RISC-V Debug Specification: The Debug Module (DM) implemented with a Program Buffer, and a JTAG Debug Transport Module (DTM). ## Compatibility The debug system is compatible with the RISC-V Debug Specification 0.13.2. The specification marks some features as optional. The status of these features is visible from the table below. **Feature** | **Support** -------------------------------------- | -------------------------------------------------------------------------------------- External triggers (Section 3.6) | Not supported at this time. Halt groups (Section 3.6) | Not supported at this time. Hardware triggers | Not supported at this time. Triggers read 0 according to the specification. System Bus Access (SBA) (Section 3.10) | Supported with generic 32 or 64 bit wide interface. Authentication | Not supported at this time. Non-intrusive access to core registers | Not supported at this time. All registers must be accessed through the program buffer. # Theory of Operations The functionality of the debug system is implemented according to the RISC-V Debug Specification. Refer to this document for more information. ## Block Diagram ![Block diagram of the debug system](debugsys_schematic.svg) ## Debug Module Registers An external debugger performs all interaction with the Debug Module through a register interface, accessed over a dedicated bus, the Debug Module Interface (DMI). The registers are called "Debug Module Registers" and defined in the RISC-V Debug Specification, Section 3.14. Our implementation only provides a single Debug Module on the DMI bus mapped to base address 0, hence all addresses below can be considered absolute. **Address** | **Name** | **Implementation Notes** ----------- | -------------------------------------------- | ------------------------ 0x04 | Abstract Data 0 (data0) 0x0f | Abstract Data 11 (data11) 0x10 | Debug Module Control (dmcontrol) | see table below 0x11 | Debug Module Status (dmstatus) | see table below 0x12 | Hart Info (hartinfo) 0x13 | Halt Summary 1 (haltsum1) 0x14 | Hart Array Window Select (hawindowsel) 0x15 | Hart Array Window (hawindow) 0x16 | Abstract Control and Status (abstractcs) 0x17 | Abstract Command (command) 0x18 | Abstract Command Autoexec (abstractauto) 0x19 | Configuration String Pointer 0 (confstrptr0) 0x1a | Configuration String Pointer 1 (confstrptr1) 0x1b | Configuration String Pointer 2 (confstrptr2) 0x1c | Configuration String Pointer 3 (confstrptr3) 0x1d | Next Debug Module (nextdm) 0x1f | Custom Features (custom) 0x20 | Program Buffer 0 (progbuf0) 0x2f | Program Buffer 15 (progbuf15) 0x30 | Authentication Data (authdata) 0x32 | Debug Module Control and Status 2 (dmcs2) 0x34 | Halt Summary 2 (haltsum2) 0x35 | Halt Summary 3 (haltsum3) 0x37 | System Bus Address 127:96 (sbaddress3) 0x38 | System Bus Access Control and Status (sbcs) 0x39 | System Bus Address 31:0 (sbaddress0) 0x3a | System Bus Address 63:32 (sbaddress1) 0x3b | System Bus Address 95:64 (sbaddress2) 0x3c | System Bus Data 31:0 (sbdata0) 0x3d | System Bus Data 63:32 (sbdata1) 0x3e | System Bus Data 95:64 (sbdata2) 0x3f | System Bus Data 127:96 (sbdata3) 0x40 | Halt Summary 0 (haltsum0) ### dmcontrol (0x10) **Field** | **Access** | **(Reset) Value** | **Comment** --------------- | ---------- | ----------------- | ------------------------------------------------------------------------------------------------------------- haltreq | WARZ resumereq | W1 hartreset | WARL | 0 | Not implemented, reads constant 0 ackhavereset | W1 hasel | WARL | 0 | Hart array masks are not supported hartsello | R/W hartselhi | R/W setresethaltreq | W1 | - | Writing this register is a no-op. Halt-on-reset is not implemented, as indicated by dmstatus.hasresethaltreq. clrresethaltreq | W1 | - | Writing this register is a no-op. Halt-on-reset is not implemented, as indicated by dmstatus.hasresethaltreq. ndmreset | R/W dmactive | R/W ### dmstatus (0x11) **Field** | **Access** | **(Reset) Value** | **Comment** --------------- | ---------- | ----------------- | --------------------------------------------------------------- impebreak | R | 0 | No implicit ebreak is inserted after the Program Buffer. allhavereset | R | | Hart array masks are not supported; identical to anyhavereset. anyhavereset | R | | Hart array masks are not supported; identical to allhavereset. allresumeack | R | | Hart array masks are not supported; identical to anyresumeack. anyresumeack | R | | Hart array masks are not supported; identical to allresumeack. allnonexistent | R | | Hart array masks are not supported; identical to anynonexistent anynonexistent | R | | Hart array masks are not supported; identical to allnonexistent allunavail | R | | Hart array masks are not supported; identical to anyunavail. anyunavail | R | | Hart array masks are not supported; identical to allunavail. allrunning | R | | Hart array masks are not supported; identical to anyrunning. anyrunning | R | | Hart array masks are not supported; identical to allrunning. allhalted | R | | Hart array masks are not supported; identical to anyhalted. anyhalted | R | | Hart array masks are not supported; identical to allhalted. authenticated | R | 1 | Authentication is not implemented, reads always 1. authbusy | R | 0 | Authentication is not implemented, reads always 0. hasresethaltreq | R | 0 | Halt-on-reset is not implemented, reads always 0. confstrptrvalid | R | 0 | Configuration strings are not supported. version | R | 2 | Specification version 0.13 ## Customization The debug system can be configured at synthesis time through parameters. **Parameter Name** | **Valid values** | **Default** | **Description** ------------------ | ---------------- | ----------- | ------------------------------------------------------------------------------------------------------------- NrHarts | 1..2^20 | 1 | Number of connected harts BusWidth | 32, 64 | 32 | Bus width (for debug memory and SBA busses) SelectableHarts | | 1 | Bitmask to select physically available harts for systems that don't use hart numbers in a contiguous fashion. In addition to these parameters, additional configuration is provided through top-level signals, which are expected to be set to a fixed value at synthesis time. Signal Name | Data Type | Width | Description ----------- | ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- hartinfo | hartinfo_t | NrHarts | Value of the hartinfo DM register, see the RISC-V Debug Specification v0.13, Section 3.14.2 for details. **nscratch**: Number of debug scratch registers. Must be set to 2. **dataaccess**: Must be set to 1. (The data register are shadowed in the hart's memory.) **datasize**: Must be set to `dm::DataCount`. **dataaddr**: Must be set to `dm::DataAddr` (0x380). **SystemVerilog definition of the hartinfo_t structure** ```verilog typedef struct packed { logic [31:24] zero1; logic [23:20] nscratch; logic [19:17] zero0; logic dataaccess; logic [15:12] datasize; logic [11:0] dataaddr; } hartinfo_t; ``` ## Hardware Interfaces The debug system interacts with multiple components, which are described in this section. The Debug Module interacts the debugged hart(s) through the core interface, with the system bus through its bus host and device, and with system management and reset functionality, and with the Debug Transport Module through the Debug Module Interface (DMI). The JTAG Debug Transport Module interacts with the host PC through JTAG, and with the Debug Module through the Debug Module Interface (DMI). ### System Interface **Signal** | **Direction** | **Description** ---------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- clk_i | input | clock. All components of the debug module and the DMI are synchronous to this clock, except for the JTAG components, which are clocked with the external TCLK. rst_ni | input | asynchronous, active low reset. testmode_i | input | not used currently ndmreset_o | output | Non-Debug Mode reset (ndmreset). ndmreset is triggered externally through JTAG, e.g. by a debugger, and should reset the whole system except for the debug system. See the RISC-V Debug Specification v0.13, Section 3.2 (Reset Control) for more details. dmactive_o | output | debug module is active **SystemVerilog interface definition** ```verilog input logic clk_i, input logic rst_ni, input logic testmode_i, output logic ndmreset_o, output logic dmactive_o ``` ### Core Interface The debug system is compatible with any RISC-V compliant CPU core, given that it support execution based debugging according to the RISC-V Debug Specification, Section A.2. #### Debug Request Interrupt The debug request interrupt is a level-sensitive interrupt. It is issued by the Debug Module to the hart(s). **Signal** | **Direction** | **Description** ------------------------ | ------------- | --------------------------------------- debug_req_o[NrHarts-1:0] | output | Level-sensitive debug request interrupt The Debug Module issues the debug request to request the core to enter its debug mode. In consequence, the core is expected to - jump to the halt address in the Debug ROM, - save pc in dpc, - update dcsr. #### Auxiliary Signalling **Signal** | **Direction** | **Description** ------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ unavailable_i[NrHarts-1] | input | Set to 0 to mark the hart has unavailable (e.g.: power down). This information is made available to the debugger through the dmstatus.allunavail and dmstatus.anyavail fields. #### Debug Control and Status Register (CSRs) Four debug-specific CSRs must be supported by the core, as described in the Debug Specification Section 4.8. **Address** | **Name** | **Access** | **Description** ----------- | --------- | ----------------------------- | ---------------------------------------------------------------------------- 0x7b0 | dcsr | _field-dependent; check spec_ | Debug Control and Status 0x7b1 | dpc | RW from Debug Mode only | Debug PC 0x7b2 | dscratch0 | RW from Debug Mode only | Debug Scratch Register 0 0x7b3 | dscratch1 | RW from Debug Mode only | Debug Scratch Register 1 (only required if DM is not located at address 0x0) #### DRET Instruction To return from debug mode the DRET instruction must be supported by the core according to the Debug Specification Section 4.7. ### JTAG The JTAG Debug Transport Module (JTAG DTM) provides a standard IEEE 1149.1 JTAG connection. **Signal** | **Direction** | **Description** ---------- | ------------- | ----------------------------------------------------------------------------------------------------- tck_i | input | Test Clock tms_i | input | Test Mode Select td_i | input | Test Data In (host to debug system) td_o | output | Test Data Out (debug system to host) tdo_oe_o | output | TDO output enable trst_ni | input | Test Reset (active low). Usage of TRST is optional, but recommended for reliable reset functionality. ### Bus Interface The Debug Module connects to the system bus as device, exposing the debug memory (the Program Buffer and the Debug ROM), and as host for the System Bus Access (SBA) functionality. The same generic bus interface is used in both cases. The bus width is configurable to be 32 or 64 bit using the `BusWidth` parameter. #### Host (Master) Interface The bus host interface is compatible to the [instruction and data interfaces of Ibex](https://ibex-core.readthedocs.io/en/latest/load_store_unit.html). **Signal** | **Width (bit)** | **Direction** | **Description** ---------- | --------------- | ------------- | --------------------------------------------------------------------------------------------------------- req | 1 | output | Request valid, must stay high until gnt is high for one cycle add | BusWidth | output | Address, word aligned we | BusWidth | output | Write Enable, high for writes, low for reads. Sent together with req be | 1 | output | Byte Enable. Is set for the bytes to write/read, sent together with req wdata | BusWidth | output | Data to be written to device, sent together with req gnt | 1 | input | The device accepted the request. Host outputs may change in the next cycle. r_valid | 1 | input | r_rdata hold valid data when r_valid is high. This signal will be high for exactly one cycle per request. r_rdata | BusWidth | input | Data read from the device No error response is currently implemented. **SystemVerilog interface definition (host side)** ```verilog output logic req_o, output logic [BusWidth-1:0] add_o, output logic we_o, output logic [BusWidth-1:0] wdata_o, output logic [BusWidth/8-1:0] be_o, input logic gnt_i, input logic r_valid_i, input logic [BusWidth-1:0] r_rdata_i ``` **SystemVerilog interface definition (device side)** ```verilog input logic slave_req_i, input logic slave_we_i, input logic [BusWidth-1:0] slave_addr_i, input logic [BusWidth/8-1:0] slave_be_i, input logic [BusWidth-1:0] slave_wdata_i, output logic [BusWidth-1:0] slave_rdata_o ``` ### OBI Bus Interface (optional) A wrapper (called dm_obi_top) is provided which wraps the Debug Module (dm_top) and makes it OBI compliant. This wrapper can be ignored (and dm_top can be used directly instead) in case of non OBI compatible systems. The OBI (Open Bus Interface) specification is at https://github.com/openhwgroup/core-v-docs/blob/master/cores/cv32e40p/. The Debug Module connects to the system bus as device, exposing the debug memory (the Program Buffer and the Debug ROM), and as host for the System Bus Access (SBA) functionality. The bus interface is according to the OBI specification in both cases. The bus width is configurable to be 32 or 64 bit using the `BusWidth` parameter. The transfer identifier width is configurable using the `IdWidth` parameter. #### Host (Master) OBI Interface Compared to dm_top the slave interface of dm_obi_top has the following additional signals: slave_gnt_o, slave_rvalid_o, slave_aid_i, slave_rid_o. Compared to dm_top the master interface of dm_obi_top has some renamed signals (master_addr_o, master_rvalid_i, master_rdata_i instead of master_add_o, master_r_valid_i, master_r_rdata_i). Both interfaces are OBI compliant. **Signal** | **Width (bit)** | **Direction** | **Description** ---------- | --------------- | ------------- | --------------------------------------------------------------------------------------------------------- req | 1 | output | Request valid, must stay high until gnt is high for one cycle addr | BusWidth | output | Address, word aligned we | BusWidth | output | Write Enable, high for writes, low for reads. Sent together with req be | 1 | output | Byte Enable. Is set for the bytes to write/read, sent together with req wdata | BusWidth | output | Data to be written to device, sent together with req gnt | 1 | input | The device accepted the request. Host outputs may change in the next cycle. rvalid | 1 | input | r_rdata hold valid data when r_valid is high. This signal will be high for exactly one cycle per request. rdata | BusWidth | input | Data read from the device No error response is currently implemented. **SystemVerilog interface definition (host side)** ```verilog output logic master_req_o, output logic [BusWidth-1:0] master_addr_o, output logic master_we_o, output logic [BusWidth-1:0] master_wdata_o, output logic [BusWidth/8-1:0] master_be_o, input logic master_gnt_i, input logic master_rvalid_i, input logic [BusWidth-1:0] master_rdata_i ``` **SystemVerilog interface definition (device side)** ```verilog input logic slave_req_i, output logic slave_gnt_o, input logic slave_we_i, input logic [BusWidth-1:0] slave_addr_i, input logic [BusWidth/8-1:0] slave_be_i, input logic [BusWidth-1:0] slave_wdata_i, input logic [IdWidth-1:0] slave_aid_i, output logic slave_rvalid_o, output logic [BusWidth-1:0] slave_rdata_o, output logic [IdWidth-1:0] slave_rid_o ``` ### The Debug Module Interface (DMI) The Debug Module Interface is a bus connecting the JTAG Debug Transport Module (DTM) with the Debug Module (DM). The Debug Specification does not require a specific implementation or hardware interface of the DMI bus. Our implementation is inspired by the implementation used by the Rocket Chip Generator. Transfers on the DMI are performed on two channels, a request and a response channel. A valid and a ready signal on each channel is used for handshaking. #### DMI Request Channel A DMI request is issued from a DMI host to a DMI device. **Signal** | **Width (bit)** | **Direction** | **Description** ---------- | --------------- | -------------- | ---------------------------------------------------------------------------------------- addr | 7 | host -> device | Address of a debug module register (c.f. Section 3.14 of the RISC-V Debug Specification) op | 2 | host -> device | Performed operation: DTM_NOP = 2'h0, DTM_READ = 2'h1, DTM_WRITE = 2'h2 data | 32 | host -> device | write data valid | 1 | host -> device | handshaking: request is valid ready | 1 | device -> host | handshaking: transaction processed **SystemVerilog interface definition (host side)** ```verilog typedef enum logic [1:0] { DTM_NOP = 2'h0, DTM_READ = 2'h1, DTM_WRITE = 2'h2 } dtm_op_e; typedef struct packed { logic [6:0] addr; dtm_op_e op; logic [31:0] data; } dmi_req_t; output logic dmi_req_valid_o, input logic dmi_req_ready_i, output dmi_req_t dmi_req_o ``` #### DMI Response Channel **Signal** | **Width (bit)** | **Direction** | **Description** ---------- | --------------- | -------------- | ------------------------------------------- resp | 2 | device -> host | Result of the operation. DTM_SUCCESS = 2'h0 data | 32 | device -> host | requested read data valid | 1 | device -> host | handshaking: response is valid ready | 1 | host -> device | handshaking: transaction processed **SystemVerilog interface definition (host side)** ```verilog typedef struct packed { logic [31:0] data; logic [1:0] resp; } dmi_resp_t; input dmi_resp_t dmi_resp_i, output logic dmi_resp_ready_o, input logic dmi_resp_valid_i ``` #### Protocol A DMI transaction consists of a request and a response. A DMI host issues a request on the request channel. The request is transmitted as soon as both ready and valid are high. After some time, the device sends the answers the request on the response channel. The response is considered sent as soon as ready and valid of the response channel are both high. A transaction is completed as soon as the response is received by the host. Only one transaction may be active at any given time. The following timing diagram shows two DMI transactions. A READ transaction, reading address 0x12 successfully, the value 0x1234 is returned. A WRITE transaction, writing the value 0xabcd to address 0x34 successfully. ![DMI protocol](dmi_protocol.svg) ## System Bus Access The system bus and all attached peripherals, including the memories, can be accessed from the host system through the System Bus Access (SBA) component. A typical use case is writing the program memory through this interface, or verifying its contents. The implementation conforms to the [RISC-V Debug Specification v0.13](https://github.com/riscv/riscv-debug-spec/raw/4e0bb0fc2d843473db2356623792c6b7603b94d4/riscv-debug-release.pdf), refer to this document for further information. ## Debug Memory The Debug Module exposes a 16 kB memory over its device bus interface. This memory is called the Debug Memory. It consists of a ROM portion, containing the Debug ROM, multiple memory-mapped control and status registers, and a RAM portion, the Program Buffer. The Debug Memory should only be accessible from the CPU if it is in debug mode. ### Debug Memory Map The memory map is an implementation detail of the Debug Module and should not be relied on when using the Debug Module. Address | Description --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ 0x0 to 0x0ff | _unused_ 0x100 | Halted. Write to this address to acknowledge that the core is halted. 0x104 | Going. Write to this address to acknowledge that the core is executing. 0x108 | Resuming. Write to this address to acknowledge that the core is resuming non-debug operation. 0x10c | Exception. An exception was triggered while the core was in debug mode. 0x300 | WhereTo 0x338 to 0x35f | AbstractCmd 0x360 to 0x37f | Program Buffer (8 words) 0x380 to 0x388 | DataAddr 0x400 to 0x7ff | Flags 0x800 to 0x1000 | Debug ROM 0x800 | HaltAddress. Entry point into the Debug Module. The core must jump to this address when it was requested to halt. 0x804 | ResumeAddress. Entry point into the Debug Module. Jumping to this address instructs the debug module to bring the core out of debug mode and back into normal operation mode. 0x808 | ExceptionAddress. Entry point into the Debug Module. The core must jump to this address when it receives an exception while being in debug mode. (Note: The debug memory addressing scheme is adopted from the Rocket Chip Generator.)
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="156.09554mm" height="95.26458mm" viewBox="0 0 156.09554 95.26458" version="1.1" id="svg8" inkscape:version="0.92.4 (5da689c313, 2019-01-14)" sodipodi:docname="debugsys_schematic.svg"> <defs id="defs2"> <marker inkscape:isstock="true" style="overflow:visible" id="marker1317" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow1Mend"> <path transform="matrix(-0.4,0,0,-0.4,-4,0)" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1" d="M 0,0 5,-5 -12.5,0 5,5 Z" id="path1315" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow1Mend" orient="auto" refY="0" refX="0" id="Arrow1Mend" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path id="path1048" d="M 0,0 5,-5 -12.5,0 5,5 Z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1" transform="matrix(-0.4,0,0,-0.4,-4,0)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker2731" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mend"> <path transform="scale(-0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path2729" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker2723" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mstart"> <path transform="scale(0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path2721" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker1603" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mend"> <path transform="scale(-0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path1601" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker1595" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mstart"> <path transform="scale(0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path1593" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow2Mend" orient="auto" refY="0" refX="0" id="marker1407" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path id="path1405" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(-0.6)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow2Mstart" orient="auto" refY="0" refX="0" id="marker1403" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path id="path1401" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(0.6)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker921" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mend" inkscape:collect="always"> <path transform="scale(-0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path919" inkscape:connector-curvature="0" /> </marker> <marker inkscape:isstock="true" style="overflow:visible" id="marker917" refX="0" refY="0" orient="auto" inkscape:stockid="Arrow2Mstart" inkscape:collect="always"> <path transform="scale(0.6)" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" id="path915" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow2Mend" orient="auto" refY="0" refX="0" id="Arrow2Mend" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path id="path1070" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(-0.6)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow2Mstart" orient="auto" refY="0" refX="0" id="Arrow2Mstart" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path id="path1067" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(0.6)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow1Lstart" orient="auto" refY="0" refX="0" id="Arrow1Lstart" style="overflow:visible" inkscape:isstock="true"> <path id="path1043" d="M 0,0 5,-5 -12.5,0 5,5 Z" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1" transform="matrix(0.8,0,0,0.8,10,0)" inkscape:connector-curvature="0" /> </marker> <marker inkscape:stockid="Arrow2Mstart" orient="auto" refY="0" refX="0" id="Arrow2Mstart-0" style="overflow:visible" inkscape:isstock="true"> <path inkscape:connector-curvature="0" id="path1067-2" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(0.6)" /> </marker> <marker inkscape:stockid="Arrow2Mend" orient="auto" refY="0" refX="0" id="Arrow2Mend-3" style="overflow:visible" inkscape:isstock="true"> <path inkscape:connector-curvature="0" id="path1070-7" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(-0.6)" /> </marker> <marker inkscape:stockid="Arrow2Mstart" orient="auto" refY="0" refX="0" id="marker1403-3" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path inkscape:connector-curvature="0" id="path1401-6" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(0.6)" /> </marker> <marker inkscape:stockid="Arrow2Mend" orient="auto" refY="0" refX="0" id="marker1407-7" style="overflow:visible" inkscape:isstock="true" inkscape:collect="always"> <path inkscape:connector-curvature="0" id="path1405-5" style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1" d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z" transform="scale(-0.6)" /> </marker> </defs> <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="1.568905" inkscape:cx="296.11683" inkscape:cy="145.21959" inkscape:document-units="mm" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="1920" inkscape:window-height="1141" inkscape:window-x="1920" inkscape:window-y="0" inkscape:window-maximized="1" showguides="false" inkscape:guide-bbox="true" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0"> <inkscape:grid type="xygrid" id="grid817" originx="-14.867708" originy="-179.8677" /> <sodipodi:guide position="-49.867706,115.1323" orientation="1,0" id="guide911" inkscape:locked="false" /> </sodipodi:namedview> <metadata id="metadata5"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title /> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Ebene 1" inkscape:groupmode="layer" id="layer1" transform="translate(-14.867708,-21.867708)"> <rect style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect815" width="30" height="10" x="30" y="32" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="45.124023" y="35.914021" id="text821"><tspan sodipodi:role="line" id="tspan819" x="45.5364" y="35.914021" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;">JTAG Test Access </tspan><tspan sodipodi:role="line" x="45.124023" y="39.882771" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan1011">Port (TAP)</tspan></text> <rect y="72" x="15" height="45" width="95" id="rect823-5" style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;text-align:start;letter-spacing:0px;word-spacing:0px;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332" x="18.374674" y="114.12811" id="text827-6"><tspan sodipodi:role="line" x="18.374674" y="114.12811" style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Bold';text-align:start;text-anchor:start;stroke-width:0.26458332" id="tspan833-9">Debug Module (DM)</tspan></text> <rect style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect815-7" width="30" height="25" x="20" y="82" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="34.926361" y="93.340378" id="text821-0"><tspan sodipodi:role="line" id="tspan819-9" x="34.926361" y="93.340378" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;">Debug Module</tspan><tspan sodipodi:role="line" x="34.926361" y="97.309128" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan1033">Registers</tspan></text> <rect style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect815-7-3" width="40" height="10" x="65" y="97" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="85.051163" y="102.88676" id="text821-0-6"><tspan sodipodi:role="line" id="tspan819-9-0" x="85.051163" y="102.88676" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;">System Bus Access (SBA)</tspan></text> <rect style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" id="rect815-7-3-6" width="40" height="10" x="65" y="82" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="85.051163" y="87.886757" id="text821-0-6-2"><tspan sodipodi:role="line" id="tspan819-9-0-6" x="85.051163" y="87.886757" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;">Debug Memory</tspan></text> <rect y="22" x="15" height="40" width="60" id="rect823-5-1" style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="81.875168" y="38.118382" id="text1015"><tspan sodipodi:role="line" id="tspan1013" x="81.875168" y="38.118382" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;stroke-width:0.26458332;">JTAG</tspan></text> <path style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-start:url(#Arrow2Mstart);marker-end:url(#Arrow2Mend)" d="M 60,37 H 80" id="path1041" inkscape:connector-curvature="0" sodipodi:nodetypes="cc" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="36.626106" y="66.203865" id="text1015-5"><tspan sodipodi:role="line" id="tspan1013-9" x="36.626106" y="66.203865" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;stroke-width:0.26458332;">Debug Module </tspan><tspan sodipodi:role="line" x="36.626106" y="70.172615" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;stroke-width:0.26458332;" id="tspan2322">Interface (DMI)</tspan></text> <path style="fill:none;stroke:#000000;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#Arrow2Mstart-0);marker-end:url(#Arrow2Mend-3)" d="M 35,62 V 82" id="path1041-2" inkscape:connector-curvature="0" sodipodi:nodetypes="cc" /> <rect y="47" x="30" height="10" width="30" id="rect861" style="opacity:1;fill:none;fill-opacity:1;stroke:#000000;stroke-width:0.26458332;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="45.248047" y="50.783794" id="text865"><tspan sodipodi:role="line" x="45.660423" y="50.783794" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan871">JTAG DTM </tspan><tspan sodipodi:role="line" x="45.248047" y="54.752544" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan875">Registers</tspan></text> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="115.26498" y="73.68927" id="text883"><tspan sodipodi:role="line" x="115.26498" y="73.68927" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;stroke-width:0.26458332;" id="tspan901">debug request (IRQ)</tspan></text> <path style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 155,94.116668 h -5 v -25 h 5" id="path889" inkscape:connector-curvature="0" sodipodi:nodetypes="cccc" /> <text xml:space="preserve" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:'Arial Italic';letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="152.84979" y="79.832794" id="text893"><tspan sodipodi:role="line" x="152.84979" y="79.832794" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Italic';text-align:start;text-anchor:start;stroke-width:0.26458332;" id="tspan895">RISC-V </tspan><tspan sodipodi:role="line" x="152.84979" y="83.801544" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Italic';text-align:start;text-anchor:start;stroke-width:0.26458332;" id="tspan903">hart</tspan></text> <path style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M 130,82.116668 V 107.11667" id="path905" inkscape:connector-curvature="0" sodipodi:nodetypes="cc" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="121.9762" y="111.825" id="text909"><tspan sodipodi:role="line" id="tspan907" x="121.9762" y="111.825" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;stroke-width:0.26458332;">system bus</tspan></text> <path inkscape:connector-curvature="0" id="path913" d="m 105,102.11667 h 25" style="fill:none;stroke:#000000;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#marker917);marker-end:url(#marker921)" sodipodi:nodetypes="cc" /> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="119.5764" y="96.360718" id="text925"><tspan sodipodi:role="line" x="119.98878" y="96.360718" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan927">bus host </tspan><tspan sodipodi:role="line" x="119.5764" y="100.32947" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan931">(SBA)</tspan></text> <path sodipodi:nodetypes="cc" style="fill:none;stroke:#000000;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#marker1403);marker-end:url(#marker1407)" d="m 105,87.116668 h 25" id="path1393" inkscape:connector-curvature="0" /> <text id="text1399" y="81.360718" x="119.5764" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:Arial;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" xml:space="preserve"><tspan id="tspan1395" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" y="81.360718" x="119.98878" sodipodi:role="line">bus device </tspan><tspan id="tspan1397" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:Arial;text-align:center;text-anchor:middle;stroke-width:0.26458332;" y="85.329468" x="119.5764" sodipodi:role="line">(mem)</tspan></text> <path inkscape:connector-curvature="0" id="path1587" d="m 105,75 h 45" style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1603)" sodipodi:nodetypes="cc" /> <path sodipodi:nodetypes="cc" style="fill:none;stroke:#000000;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#marker1403-3);marker-end:url(#marker1407-7)" d="m 130,87.116668 h 20" id="path1393-3" inkscape:connector-curvature="0" /> <path sodipodi:nodetypes="cccc" inkscape:connector-curvature="0" id="path2601" d="m 155,112.11667 h -5 V 97.116668 h 5" style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> <text xml:space="preserve" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:Arial;-inkscape-font-specification:'Arial Italic';letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="153" y="103.43286" id="text2701"><tspan sodipodi:role="line" x="153" y="103.43286" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Italic';stroke-width:0.26458332;" id="tspan2703">memory and</tspan><tspan sodipodi:role="line" x="153" y="107.40161" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Italic';stroke-width:0.26458332;" id="tspan12737">peripherals</tspan></text> <path inkscape:connector-curvature="0" id="path2715" d="m 130,102.11667 h 20" style="fill:none;stroke:#000000;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#marker2723);marker-end:url(#marker2731)" sodipodi:nodetypes="cc" /> <path style="fill:none;stroke:#000000;stroke-width:0.26499999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#marker1317)" d="M 50.000001,89.999999 65,87" id="path1035" inkscape:connector-curvature="0" /> <path style="fill:none;stroke:#000000;stroke-width:0.26499999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#Arrow1Mend)" d="M 50.000001,99 65,102" id="path1037" inkscape:connector-curvature="0" /> <text xml:space="preserve" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:3.17499995px;line-height:1;font-family:Arial;-inkscape-font-specification:'Arial Italic';letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332;" x="57.113335" y="93.754929" id="text1487"><tspan sodipodi:role="line" id="tspan1485" x="57.113335" y="93.754929" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:1;font-family:Arial;-inkscape-font-specification:'Arial Italic';text-align:center;text-anchor:middle;stroke-width:0.26458332;">access</tspan><tspan sodipodi:role="line" x="57.113335" y="96.929932" style="font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;line-height:1;font-family:Arial;-inkscape-font-specification:'Arial Italic';text-align:center;text-anchor:middle;stroke-width:0.26458332;" id="tspan1489">to</tspan></text> <text xml:space="preserve" style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:3.17499995px;line-height:1.25;font-family:'Open Sans';-inkscape-font-specification:'Open Sans Bold';text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332" x="45.056587" y="27.58337" id="text1158"><tspan sodipodi:role="line" id="tspan1156" x="45.056587" y="27.58337" style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-family:Arial;-inkscape-font-specification:'Arial Bold';text-align:center;text-anchor:middle;stroke-width:0.26458332">JTAG Debug Transport Module (DTM)</tspan></text> </g> </svg>
{signal: [ {name: 'clk', wave: 'p...|....|....|....'}, {name: 'dmi_req.op', wave: 'x=.x|....|x=.x|....', data: ['READ', 'WRITE']}, {name: 'dmi_req.addr', wave: 'x=.x|....|x=.x|....', data: ['0x12', '0x34']}, {name: 'dmi_req.data', wave: 'x...|....|x=.x|....', data: ['0xabcd']}, {name: 'dmi_req_valid', wave: '01.0|....|.1.0|....'}, {name: 'dmi_req_ready', wave: '0.1.|..0.|..1.|....'}, {}, {name: 'dmi_resp.resp',wave: 'x...|x=.x|....|x=.x', data: ['SUCCESS', 'SUCCESS']}, {name: 'dmi_resp.data',wave: 'x...|x=.x|....|....', data: ['0x1234']}, {name: 'dmi_resp_valid', wave: '0...|.1.0|....|..10'}, {name: 'dmi_resp_ready', wave: '1...|0.1.|....|....'}, ]}
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <!-- Created with WaveDrom --> <svg id="svgcontent_0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="330" width="920" viewBox="0 0 920 330" overflow="hidden" class="WaveDrom"><style type="text/css">text{font-size:11pt;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;fill-opacity:1;font-family:Helvetica}.muted{fill:#aaa}.warning{fill:#f6b900}.error{fill:#f60000}.info{fill:#0041c4}.success{fill:#00ab00}.h1{font-size:33pt;font-weight:bold}.h2{font-size:27pt;font-weight:bold}.h3{font-size:20pt;font-weight:bold}.h4{font-size:14pt;font-weight:bold}.h5{font-size:11pt;font-weight:bold}.h6{font-size:8pt;font-weight:bold}.s1{fill:none;stroke:#000;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none}.s2{fill:none;stroke:#000;stroke-width:0.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none}.s3{color:#000;fill:none;stroke:#000;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:1, 3;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate}.s4{color:#000;fill:none;stroke:#000;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker:none;visibility:visible;display:inline;overflow:visible}.s5{fill:#fff;stroke:none}.s6{color:#000;fill:#ffffb4;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate}.s7{color:#000;fill:#ffe0b9;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate}.s8{color:#000;fill:#b9e0ff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate}.s9{fill:#000;fill-opacity:1;stroke:none}.s10{color:#000;fill:#fff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1px;marker:none;visibility:visible;display:inline;overflow:visible;enable-background:accumulate}.s11{fill:#0041c4;fill-opacity:1;stroke:none}.s12{fill:none;stroke:#0041c4;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none}</style><defs><g id="socket"><rect y="15" x="6" height="20" width="20"/></g><g id="pclk"><path d="M0,20 0,0 20,0" class="s1"/></g><g id="nclk"><path d="m0,0 0,20 20,0" class="s1"/></g><g id="000"><path d="m0,20 20,0" class="s1"/></g><g id="0m0"><path d="m0,20 3,0 3,-10 3,10 11,0" class="s1"/></g><g id="0m1"><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="0mx"><path d="M3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 5,20" class="s2"/><path d="M20,0 4,16" class="s2"/><path d="M15,0 6,9" class="s2"/><path d="M10,0 9,1" class="s2"/><path d="m0,20 20,0" class="s1"/></g><g id="0md"><path d="m8,20 10,0" class="s3"/><path d="m0,20 5,0" class="s1"/></g><g id="0mu"><path d="m0,20 3,0 C 7,10 10.107603,0 20,0" class="s1"/></g><g id="0mz"><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="111"><path d="M0,0 20,0" class="s1"/></g><g id="1m0"><path d="m0,0 3,0 6,20 11,0" class="s1"/></g><g id="1m1"><path d="M0,0 3,0 6,10 9,0 20,0" class="s1"/></g><g id="1mx"><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 6,9" class="s2"/><path d="M10,0 5,5" class="s2"/><path d="M3.5,1.5 5,0" class="s2"/></g><g id="1md"><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/></g><g id="1mu"><path d="M0,0 5,0" class="s1"/><path d="M8,0 18,0" class="s3"/></g><g id="1mz"><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s1"/></g><g id="xxx"><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/><path d="M0,5 5,0" class="s2"/><path d="M0,10 10,0" class="s2"/><path d="M0,15 15,0" class="s2"/><path d="M0,20 20,0" class="s2"/><path d="M5,20 20,5" class="s2"/><path d="M10,20 20,10" class="s2"/><path d="m15,20 5,-5" class="s2"/></g><g id="xm0"><path d="M0,0 4,0 9,20" class="s1"/><path d="m0,20 20,0" class="s1"/><path d="M0,5 4,1" class="s2"/><path d="M0,10 5,5" class="s2"/><path d="M0,15 6,9" class="s2"/><path d="M0,20 7,13" class="s2"/><path d="M5,20 8,17" class="s2"/></g><g id="xm1"><path d="M0,0 20,0" class="s1"/><path d="M0,20 4,20 9,0" class="s1"/><path d="M0,5 5,0" class="s2"/><path d="M0,10 9,1" class="s2"/><path d="M0,15 7,8" class="s2"/><path d="M0,20 5,15" class="s2"/></g><g id="xmx"><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/><path d="M0,5 5,0" class="s2"/><path d="M0,10 10,0" class="s2"/><path d="M0,15 15,0" class="s2"/><path d="M0,20 20,0" class="s2"/><path d="M5,20 20,5" class="s2"/><path d="M10,20 20,10" class="s2"/><path d="m15,20 5,-5" class="s2"/></g><g id="xmd"><path d="m0,0 4,0 c 3,10 6,20 16,20" class="s1"/><path d="m0,20 20,0" class="s1"/><path d="M0,5 4,1" class="s2"/><path d="M0,10 5.5,4.5" class="s2"/><path d="M0,15 6.5,8.5" class="s2"/><path d="M0,20 8,12" class="s2"/><path d="m5,20 5,-5" class="s2"/><path d="m10,20 2.5,-2.5" class="s2"/></g><g id="xmu"><path d="M0,0 20,0" class="s1"/><path d="m0,20 4,0 C 7,10 10,0 20,0" class="s1"/><path d="M0,5 5,0" class="s2"/><path d="M0,10 10,0" class="s2"/><path d="M0,15 10,5" class="s2"/><path d="M0,20 6,14" class="s2"/></g><g id="xmz"><path d="m0,0 4,0 c 6,10 11,10 16,10" class="s1"/><path d="m0,20 4,0 C 10,10 15,10 20,10" class="s1"/><path d="M0,5 4.5,0.5" class="s2"/><path d="M0,10 6.5,3.5" class="s2"/><path d="M0,15 8.5,6.5" class="s2"/><path d="M0,20 11.5,8.5" class="s2"/></g><g id="ddd"><path d="m0,20 20,0" class="s3"/></g><g id="dm0"><path d="m0,20 10,0" class="s3"/><path d="m12,20 8,0" class="s1"/></g><g id="dm1"><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="dmx"><path d="M3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 5,20" class="s2"/><path d="M20,0 4,16" class="s2"/><path d="M15,0 6,9" class="s2"/><path d="M10,0 9,1" class="s2"/><path d="m0,20 20,0" class="s1"/></g><g id="dmd"><path d="m0,20 20,0" class="s3"/></g><g id="dmu"><path d="m0,20 3,0 C 7,10 10.107603,0 20,0" class="s1"/></g><g id="dmz"><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="uuu"><path d="M0,0 20,0" class="s3"/></g><g id="um0"><path d="m0,0 3,0 6,20 11,0" class="s1"/></g><g id="um1"><path d="M0,0 10,0" class="s3"/><path d="m12,0 8,0" class="s1"/></g><g id="umx"><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 6,9" class="s2"/><path d="M10,0 5,5" class="s2"/><path d="M3.5,1.5 5,0" class="s2"/></g><g id="umd"><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/></g><g id="umu"><path d="M0,0 20,0" class="s3"/></g><g id="umz"><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s4"/></g><g id="zzz"><path d="m0,10 20,0" class="s1"/></g><g id="zm0"><path d="m0,10 6,0 3,10 11,0" class="s1"/></g><g id="zm1"><path d="M0,10 6,10 9,0 20,0" class="s1"/></g><g id="zmx"><path d="m6,10 3,10 11,0" class="s1"/><path d="M0,10 6,10 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 6.5,8.5" class="s2"/><path d="M10,0 9,1" class="s2"/></g><g id="zmd"><path d="m0,10 7,0 c 3,5 8,10 13,10" class="s1"/></g><g id="zmu"><path d="m0,10 7,0 C 10,5 15,0 20,0" class="s1"/></g><g id="zmz"><path d="m0,10 20,0" class="s1"/></g><g id="gap"><path d="m7,-2 -4,0 c -5,0 -5,24 -10,24 l 4,0 C 2,22 2,-2 7,-2 z" class="s5"/><path d="M-7,22 C -2,22 -2,-2 3,-2" class="s1"/><path d="M-3,22 C 2,22 2,-2 7,-2" class="s1"/></g><g id="0mv-3"><path d="M9,0 20,0 20,20 3,20 z" class="s6"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="1mv-3"><path d="M2.875,0 20,0 20,20 9,20 z" class="s6"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="xmv-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,5 3.5,1.5" class="s2"/><path d="M0,10 4.5,5.5" class="s2"/><path d="M0,15 6,9" class="s2"/><path d="M0,20 4,16" class="s2"/></g><g id="dmv-3"><path d="M9,0 20,0 20,20 3,20 z" class="s6"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="umv-3"><path d="M3,0 20,0 20,20 9,20 z" class="s6"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="zmv-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="m6,10 3,10 11,0" class="s1"/><path d="M0,10 6,10 9,0 20,0" class="s1"/></g><g id="vvv-3"><path d="M20,20 0,20 0,0 20,0" class="s6"/><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vm0-3"><path d="M0,20 0,0 3,0 9,20" class="s6"/><path d="M0,0 3,0 9,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vm1-3"><path d="M0,0 0,20 3,20 9,0" class="s6"/><path d="M0,0 20,0" class="s1"/><path d="M0,20 3,20 9,0" class="s1"/></g><g id="vmx-3"><path d="M0,0 0,20 3,20 6,10 3,0" class="s6"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 7,8" class="s2"/><path d="M10,0 9,1" class="s2"/></g><g id="vmd-3"><path d="m0,0 0,20 20,0 C 10,20 7,10 3,0" class="s6"/><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vmu-3"><path d="m0,0 0,20 3,0 C 7,10 10,0 20,0" class="s6"/><path d="m0,20 3,0 C 7,10 10,0 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vmz-3"><path d="M0,0 3,0 C 10,10 15,10 20,10 15,10 10,10 3,20 L 0,20" class="s6"/><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s1"/><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="vmv-3-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s6"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-3-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s6"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-3-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s6"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-4-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s7"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-4-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s7"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-4-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s7"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-5-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s8"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-5-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s8"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-5-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s8"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="0mv-4"><path d="M9,0 20,0 20,20 3,20 z" class="s7"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="1mv-4"><path d="M2.875,0 20,0 20,20 9,20 z" class="s7"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="xmv-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,5 3.5,1.5" class="s2"/><path d="M0,10 4.5,5.5" class="s2"/><path d="M0,15 6,9" class="s2"/><path d="M0,20 4,16" class="s2"/></g><g id="dmv-4"><path d="M9,0 20,0 20,20 3,20 z" class="s7"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="umv-4"><path d="M3,0 20,0 20,20 9,20 z" class="s7"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="zmv-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="m6,10 3,10 11,0" class="s1"/><path d="M0,10 6,10 9,0 20,0" class="s1"/></g><g id="0mv-5"><path d="M9,0 20,0 20,20 3,20 z" class="s8"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="1mv-5"><path d="M2.875,0 20,0 20,20 9,20 z" class="s8"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="xmv-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,5 3.5,1.5" class="s2"/><path d="M0,10 4.5,5.5" class="s2"/><path d="M0,15 6,9" class="s2"/><path d="M0,20 4,16" class="s2"/></g><g id="dmv-5"><path d="M9,0 20,0 20,20 3,20 z" class="s8"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="umv-5"><path d="M3,0 20,0 20,20 9,20 z" class="s8"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="zmv-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="m6,10 3,10 11,0" class="s1"/><path d="M0,10 6,10 9,0 20,0" class="s1"/></g><g id="vvv-4"><path d="M20,20 0,20 0,0 20,0" class="s7"/><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vm0-4"><path d="M0,20 0,0 3,0 9,20" class="s7"/><path d="M0,0 3,0 9,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vm1-4"><path d="M0,0 0,20 3,20 9,0" class="s7"/><path d="M0,0 20,0" class="s1"/><path d="M0,20 3,20 9,0" class="s1"/></g><g id="vmx-4"><path d="M0,0 0,20 3,20 6,10 3,0" class="s7"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 7,8" class="s2"/><path d="M10,0 9,1" class="s2"/></g><g id="vmd-4"><path d="m0,0 0,20 20,0 C 10,20 7,10 3,0" class="s7"/><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vmu-4"><path d="m0,0 0,20 3,0 C 7,10 10,0 20,0" class="s7"/><path d="m0,20 3,0 C 7,10 10,0 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vmz-4"><path d="M0,0 3,0 C 10,10 15,10 20,10 15,10 10,10 3,20 L 0,20" class="s7"/><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s1"/><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="vvv-5"><path d="M20,20 0,20 0,0 20,0" class="s8"/><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vm0-5"><path d="M0,20 0,0 3,0 9,20" class="s8"/><path d="M0,0 3,0 9,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vm1-5"><path d="M0,0 0,20 3,20 9,0" class="s8"/><path d="M0,0 20,0" class="s1"/><path d="M0,20 3,20 9,0" class="s1"/></g><g id="vmx-5"><path d="M0,0 0,20 3,20 6,10 3,0" class="s8"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 7,8" class="s2"/><path d="M10,0 9,1" class="s2"/></g><g id="vmd-5"><path d="m0,0 0,20 20,0 C 10,20 7,10 3,0" class="s8"/><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vmu-5"><path d="m0,0 0,20 3,0 C 7,10 10,0 20,0" class="s8"/><path d="m0,20 3,0 C 7,10 10,0 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vmz-5"><path d="M0,0 3,0 C 10,10 15,10 20,10 15,10 10,10 3,20 L 0,20" class="s8"/><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s1"/><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="Pclk"><path d="M-3,12 0,3 3,12 C 1,11 -1,11 -3,12 z" class="s9"/><path d="M0,20 0,0 20,0" class="s1"/></g><g id="Nclk"><path d="M-3,8 0,17 3,8 C 1,9 -1,9 -3,8 z" class="s9"/><path d="m0,0 0,20 20,0" class="s1"/></g><g id="vvv-2"><path d="M20,20 0,20 0,0 20,0" class="s10"/><path d="m0,20 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vm0-2"><path d="M0,20 0,0 3,0 9,20" class="s10"/><path d="M0,0 3,0 9,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vm1-2"><path d="M0,0 0,20 3,20 9,0" class="s10"/><path d="M0,0 20,0" class="s1"/><path d="M0,20 3,20 9,0" class="s1"/></g><g id="vmx-2"><path d="M0,0 0,20 3,20 6,10 3,0" class="s10"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m20,15 -5,5" class="s2"/><path d="M20,10 10,20" class="s2"/><path d="M20,5 8,17" class="s2"/><path d="M20,0 7,13" class="s2"/><path d="M15,0 7,8" class="s2"/><path d="M10,0 9,1" class="s2"/></g><g id="vmd-2"><path d="m0,0 0,20 20,0 C 10,20 7,10 3,0" class="s10"/><path d="m0,0 3,0 c 4,10 7,20 17,20" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="vmu-2"><path d="m0,0 0,20 3,0 C 7,10 10,0 20,0" class="s10"/><path d="m0,20 3,0 C 7,10 10,0 20,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="vmz-2"><path d="M0,0 3,0 C 10,10 15,10 20,10 15,10 10,10 3,20 L 0,20" class="s10"/><path d="m0,0 3,0 c 7,10 12,10 17,10" class="s1"/><path d="m0,20 3,0 C 10,10 15,10 20,10" class="s1"/></g><g id="0mv-2"><path d="M9,0 20,0 20,20 3,20 z" class="s10"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="1mv-2"><path d="M2.875,0 20,0 20,20 9,20 z" class="s10"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="xmv-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="M0,20 3,20 9,0 20,0" class="s1"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,5 3.5,1.5" class="s2"/><path d="M0,10 4.5,5.5" class="s2"/><path d="M0,15 6,9" class="s2"/><path d="M0,20 4,16" class="s2"/></g><g id="dmv-2"><path d="M9,0 20,0 20,20 3,20 z" class="s10"/><path d="M3,20 9,0 20,0" class="s1"/><path d="m0,20 20,0" class="s1"/></g><g id="umv-2"><path d="M3,0 20,0 20,20 9,20 z" class="s10"/><path d="m3,0 6,20 11,0" class="s1"/><path d="M0,0 20,0" class="s1"/></g><g id="zmv-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="m6,10 3,10 11,0" class="s1"/><path d="M0,10 6,10 9,0 20,0" class="s1"/></g><g id="vmv-3-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s6"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-4-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s7"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-5-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s8"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-2-3"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s6"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s10"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-2-4"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s7"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s10"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-2-5"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s8"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s10"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="vmv-2-2"><path d="M9,0 20,0 20,20 9,20 6,10 z" class="s10"/><path d="M3,0 0,0 0,20 3,20 6,10 z" class="s10"/><path d="m0,0 3,0 6,20 11,0" class="s1"/><path d="M0,20 3,20 9,0 20,0" class="s1"/></g><g id="arrow0"><path d="m-12,-3 9,3 -9,3 c 1,-2 1,-4 0,-6 z" class="s11"/><path d="M0,0 -15,0" class="s12"/></g><marker id="arrowhead" style="fill:#0041c4" markerHeight="7" markerWidth="10" markerUnits="strokeWidth" viewBox="0 -4 11 8" refX="15" refY="0" orient="auto"><path d="M0 -4 11 0 0 4z"/></marker><marker id="arrowtail" style="fill:#0041c4" markerHeight="7" markerWidth="10" markerUnits="strokeWidth" viewBox="-11 -4 11 8" refX="-15" refY="0" orient="auto"><path d="M0 -4 -11 0 0 4z"/></marker></defs><g id="waves_0"><g id="lanes_0" transform="translate(140.5, 0.5)"><g id="gmarks_0"><path id="gmark_0_0" d="m 0,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_1_0" d="m 40,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_2_0" d="m 80,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_3_0" d="m 120,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_4_0" d="m 160,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_5_0" d="m 200,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_6_0" d="m 240,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_7_0" d="m 280,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_8_0" d="m 320,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_9_0" d="m 360,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_10_0" d="m 400,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_11_0" d="m 440,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_12_0" d="m 480,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_13_0" d="m 520,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_14_0" d="m 560,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_15_0" d="m 600,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_16_0" d="m 640,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_17_0" d="m 680,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_18_0" d="m 720,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/><path id="gmark_19_0" d="m 760,0 0,330" style="stroke:#888;stroke-width:0.5;stroke-dasharray:1,3"/></g><g id="wavelane_0_0" transform="translate(0,5)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>clk</tspan></text><g id="wavelane_draw_0_0" transform="translate(0, 0)"><use xlink:href="#pclk" transform="translate(0)"/><use xlink:href="#nclk" transform="translate(20)"/><use xlink:href="#pclk" transform="translate(40)"/><use xlink:href="#nclk" transform="translate(60)"/><use xlink:href="#pclk" transform="translate(80)"/><use xlink:href="#nclk" transform="translate(100)"/><use xlink:href="#pclk" transform="translate(120)"/><use xlink:href="#nclk" transform="translate(140)"/><use xlink:href="#pclk" transform="translate(160)"/><use xlink:href="#nclk" transform="translate(180)"/><use xlink:href="#pclk" transform="translate(200)"/><use xlink:href="#nclk" transform="translate(220)"/><use xlink:href="#pclk" transform="translate(240)"/><use xlink:href="#nclk" transform="translate(260)"/><use xlink:href="#pclk" transform="translate(280)"/><use xlink:href="#nclk" transform="translate(300)"/><use xlink:href="#pclk" transform="translate(320)"/><use xlink:href="#nclk" transform="translate(340)"/><use xlink:href="#pclk" transform="translate(360)"/><use xlink:href="#nclk" transform="translate(380)"/><use xlink:href="#pclk" transform="translate(400)"/><use xlink:href="#nclk" transform="translate(420)"/><use xlink:href="#pclk" transform="translate(440)"/><use xlink:href="#nclk" transform="translate(460)"/><use xlink:href="#pclk" transform="translate(480)"/><use xlink:href="#nclk" transform="translate(500)"/><use xlink:href="#pclk" transform="translate(520)"/><use xlink:href="#nclk" transform="translate(540)"/><use xlink:href="#pclk" transform="translate(560)"/><use xlink:href="#nclk" transform="translate(580)"/><use xlink:href="#pclk" transform="translate(600)"/><use xlink:href="#nclk" transform="translate(620)"/><use xlink:href="#pclk" transform="translate(640)"/><use xlink:href="#nclk" transform="translate(660)"/><use xlink:href="#pclk" transform="translate(680)"/><use xlink:href="#nclk" transform="translate(700)"/><use xlink:href="#pclk" transform="translate(720)"/><use xlink:href="#nclk" transform="translate(740)"/></g></g><g id="wavelane_1_0" transform="translate(0,35)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_req.op</tspan></text><g id="wavelane_draw_1_0" transform="translate(0, 0)"><use xlink:href="#xxx" transform="translate(0)"/><use xlink:href="#xxx" transform="translate(20)"/><use xlink:href="#xmv-2" transform="translate(40)"/><use xlink:href="#vvv-2" transform="translate(60)"/><use xlink:href="#vvv-2" transform="translate(80)"/><use xlink:href="#vvv-2" transform="translate(100)"/><use xlink:href="#vmx-2" transform="translate(120)"/><use xlink:href="#xxx" transform="translate(140)"/><use xlink:href="#xxx" transform="translate(160)"/><use xlink:href="#xxx" transform="translate(180)"/><use xlink:href="#xxx" transform="translate(200)"/><use xlink:href="#xxx" transform="translate(220)"/><use xlink:href="#xxx" transform="translate(240)"/><use xlink:href="#xxx" transform="translate(260)"/><use xlink:href="#xxx" transform="translate(280)"/><use xlink:href="#xxx" transform="translate(300)"/><use xlink:href="#xxx" transform="translate(320)"/><use xlink:href="#xxx" transform="translate(340)"/><use xlink:href="#xxx" transform="translate(360)"/><use xlink:href="#xxx" transform="translate(380)"/><use xlink:href="#xmx" transform="translate(400)"/><use xlink:href="#xxx" transform="translate(420)"/><use xlink:href="#xmv-2" transform="translate(440)"/><use xlink:href="#vvv-2" transform="translate(460)"/><use xlink:href="#vvv-2" transform="translate(480)"/><use xlink:href="#vvv-2" transform="translate(500)"/><use xlink:href="#vmx-2" transform="translate(520)"/><use xlink:href="#xxx" transform="translate(540)"/><use xlink:href="#xxx" transform="translate(560)"/><use xlink:href="#xxx" transform="translate(580)"/><use xlink:href="#xxx" transform="translate(600)"/><use xlink:href="#xxx" transform="translate(620)"/><use xlink:href="#xxx" transform="translate(640)"/><use xlink:href="#xxx" transform="translate(660)"/><use xlink:href="#xxx" transform="translate(680)"/><use xlink:href="#xxx" transform="translate(700)"/><use xlink:href="#xxx" transform="translate(720)"/><use xlink:href="#xxx" transform="translate(740)"/><text x="86" y="15" text-anchor="middle" xml:space="preserve"><tspan>READ</tspan></text><text x="486" y="15" text-anchor="middle" xml:space="preserve"><tspan>WRITE</tspan></text></g></g><g id="wavelane_2_0" transform="translate(0,65)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_req.addr</tspan></text><g id="wavelane_draw_2_0" transform="translate(0, 0)"><use xlink:href="#xxx" transform="translate(0)"/><use xlink:href="#xxx" transform="translate(20)"/><use xlink:href="#xmv-2" transform="translate(40)"/><use xlink:href="#vvv-2" transform="translate(60)"/><use xlink:href="#vvv-2" transform="translate(80)"/><use xlink:href="#vvv-2" transform="translate(100)"/><use xlink:href="#vmx-2" transform="translate(120)"/><use xlink:href="#xxx" transform="translate(140)"/><use xlink:href="#xxx" transform="translate(160)"/><use xlink:href="#xxx" transform="translate(180)"/><use xlink:href="#xxx" transform="translate(200)"/><use xlink:href="#xxx" transform="translate(220)"/><use xlink:href="#xxx" transform="translate(240)"/><use xlink:href="#xxx" transform="translate(260)"/><use xlink:href="#xxx" transform="translate(280)"/><use xlink:href="#xxx" transform="translate(300)"/><use xlink:href="#xxx" transform="translate(320)"/><use xlink:href="#xxx" transform="translate(340)"/><use xlink:href="#xxx" transform="translate(360)"/><use xlink:href="#xxx" transform="translate(380)"/><use xlink:href="#xmx" transform="translate(400)"/><use xlink:href="#xxx" transform="translate(420)"/><use xlink:href="#xmv-2" transform="translate(440)"/><use xlink:href="#vvv-2" transform="translate(460)"/><use xlink:href="#vvv-2" transform="translate(480)"/><use xlink:href="#vvv-2" transform="translate(500)"/><use xlink:href="#vmx-2" transform="translate(520)"/><use xlink:href="#xxx" transform="translate(540)"/><use xlink:href="#xxx" transform="translate(560)"/><use xlink:href="#xxx" transform="translate(580)"/><use xlink:href="#xxx" transform="translate(600)"/><use xlink:href="#xxx" transform="translate(620)"/><use xlink:href="#xxx" transform="translate(640)"/><use xlink:href="#xxx" transform="translate(660)"/><use xlink:href="#xxx" transform="translate(680)"/><use xlink:href="#xxx" transform="translate(700)"/><use xlink:href="#xxx" transform="translate(720)"/><use xlink:href="#xxx" transform="translate(740)"/><text x="86" y="15" text-anchor="middle" xml:space="preserve"><tspan>0x12</tspan></text><text x="486" y="15" text-anchor="middle" xml:space="preserve"><tspan>0x34</tspan></text></g></g><g id="wavelane_3_0" transform="translate(0,95)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_req.data</tspan></text><g id="wavelane_draw_3_0" transform="translate(0, 0)"><use xlink:href="#xxx" transform="translate(0)"/><use xlink:href="#xxx" transform="translate(20)"/><use xlink:href="#xxx" transform="translate(40)"/><use xlink:href="#xxx" transform="translate(60)"/><use xlink:href="#xxx" transform="translate(80)"/><use xlink:href="#xxx" transform="translate(100)"/><use xlink:href="#xxx" transform="translate(120)"/><use xlink:href="#xxx" transform="translate(140)"/><use xlink:href="#xxx" transform="translate(160)"/><use xlink:href="#xxx" transform="translate(180)"/><use xlink:href="#xxx" transform="translate(200)"/><use xlink:href="#xxx" transform="translate(220)"/><use xlink:href="#xxx" transform="translate(240)"/><use xlink:href="#xxx" transform="translate(260)"/><use xlink:href="#xxx" transform="translate(280)"/><use xlink:href="#xxx" transform="translate(300)"/><use xlink:href="#xxx" transform="translate(320)"/><use xlink:href="#xxx" transform="translate(340)"/><use xlink:href="#xxx" transform="translate(360)"/><use xlink:href="#xxx" transform="translate(380)"/><use xlink:href="#xmx" transform="translate(400)"/><use xlink:href="#xxx" transform="translate(420)"/><use xlink:href="#xmv-2" transform="translate(440)"/><use xlink:href="#vvv-2" transform="translate(460)"/><use xlink:href="#vvv-2" transform="translate(480)"/><use xlink:href="#vvv-2" transform="translate(500)"/><use xlink:href="#vmx-2" transform="translate(520)"/><use xlink:href="#xxx" transform="translate(540)"/><use xlink:href="#xxx" transform="translate(560)"/><use xlink:href="#xxx" transform="translate(580)"/><use xlink:href="#xxx" transform="translate(600)"/><use xlink:href="#xxx" transform="translate(620)"/><use xlink:href="#xxx" transform="translate(640)"/><use xlink:href="#xxx" transform="translate(660)"/><use xlink:href="#xxx" transform="translate(680)"/><use xlink:href="#xxx" transform="translate(700)"/><use xlink:href="#xxx" transform="translate(720)"/><use xlink:href="#xxx" transform="translate(740)"/><text x="486" y="15" text-anchor="middle" xml:space="preserve"><tspan>0xabcd</tspan></text></g></g><g id="wavelane_4_0" transform="translate(0,125)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_req_valid</tspan></text><g id="wavelane_draw_4_0" transform="translate(0, 0)"><use xlink:href="#000" transform="translate(0)"/><use xlink:href="#000" transform="translate(20)"/><use xlink:href="#0m1" transform="translate(40)"/><use xlink:href="#111" transform="translate(60)"/><use xlink:href="#111" transform="translate(80)"/><use xlink:href="#111" transform="translate(100)"/><use xlink:href="#1m0" transform="translate(120)"/><use xlink:href="#000" transform="translate(140)"/><use xlink:href="#000" transform="translate(160)"/><use xlink:href="#000" transform="translate(180)"/><use xlink:href="#000" transform="translate(200)"/><use xlink:href="#000" transform="translate(220)"/><use xlink:href="#000" transform="translate(240)"/><use xlink:href="#000" transform="translate(260)"/><use xlink:href="#000" transform="translate(280)"/><use xlink:href="#000" transform="translate(300)"/><use xlink:href="#000" transform="translate(320)"/><use xlink:href="#000" transform="translate(340)"/><use xlink:href="#000" transform="translate(360)"/><use xlink:href="#000" transform="translate(380)"/><use xlink:href="#000" transform="translate(400)"/><use xlink:href="#000" transform="translate(420)"/><use xlink:href="#0m1" transform="translate(440)"/><use xlink:href="#111" transform="translate(460)"/><use xlink:href="#111" transform="translate(480)"/><use xlink:href="#111" transform="translate(500)"/><use xlink:href="#1m0" transform="translate(520)"/><use xlink:href="#000" transform="translate(540)"/><use xlink:href="#000" transform="translate(560)"/><use xlink:href="#000" transform="translate(580)"/><use xlink:href="#000" transform="translate(600)"/><use xlink:href="#000" transform="translate(620)"/><use xlink:href="#000" transform="translate(640)"/><use xlink:href="#000" transform="translate(660)"/><use xlink:href="#000" transform="translate(680)"/><use xlink:href="#000" transform="translate(700)"/><use xlink:href="#000" transform="translate(720)"/><use xlink:href="#000" transform="translate(740)"/></g></g><g id="wavelane_5_0" transform="translate(0,155)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_req_ready</tspan></text><g id="wavelane_draw_5_0" transform="translate(0, 0)"><use xlink:href="#000" transform="translate(0)"/><use xlink:href="#000" transform="translate(20)"/><use xlink:href="#000" transform="translate(40)"/><use xlink:href="#000" transform="translate(60)"/><use xlink:href="#0m1" transform="translate(80)"/><use xlink:href="#111" transform="translate(100)"/><use xlink:href="#111" transform="translate(120)"/><use xlink:href="#111" transform="translate(140)"/><use xlink:href="#111" transform="translate(160)"/><use xlink:href="#111" transform="translate(180)"/><use xlink:href="#111" transform="translate(200)"/><use xlink:href="#111" transform="translate(220)"/><use xlink:href="#111" transform="translate(240)"/><use xlink:href="#111" transform="translate(260)"/><use xlink:href="#1m0" transform="translate(280)"/><use xlink:href="#000" transform="translate(300)"/><use xlink:href="#000" transform="translate(320)"/><use xlink:href="#000" transform="translate(340)"/><use xlink:href="#000" transform="translate(360)"/><use xlink:href="#000" transform="translate(380)"/><use xlink:href="#000" transform="translate(400)"/><use xlink:href="#000" transform="translate(420)"/><use xlink:href="#000" transform="translate(440)"/><use xlink:href="#000" transform="translate(460)"/><use xlink:href="#0m1" transform="translate(480)"/><use xlink:href="#111" transform="translate(500)"/><use xlink:href="#111" transform="translate(520)"/><use xlink:href="#111" transform="translate(540)"/><use xlink:href="#111" transform="translate(560)"/><use xlink:href="#111" transform="translate(580)"/><use xlink:href="#111" transform="translate(600)"/><use xlink:href="#111" transform="translate(620)"/><use xlink:href="#111" transform="translate(640)"/><use xlink:href="#111" transform="translate(660)"/><use xlink:href="#111" transform="translate(680)"/><use xlink:href="#111" transform="translate(700)"/><use xlink:href="#111" transform="translate(720)"/><use xlink:href="#111" transform="translate(740)"/></g></g><g id="wavelane_6_0" transform="translate(0,185)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan/></text><g id="wavelane_draw_6_0" transform="translate(0, 0)"/></g><g id="wavelane_7_0" transform="translate(0,215)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_resp.resp</tspan></text><g id="wavelane_draw_7_0" transform="translate(0, 0)"><use xlink:href="#xxx" transform="translate(0)"/><use xlink:href="#xxx" transform="translate(20)"/><use xlink:href="#xxx" transform="translate(40)"/><use xlink:href="#xxx" transform="translate(60)"/><use xlink:href="#xxx" transform="translate(80)"/><use xlink:href="#xxx" transform="translate(100)"/><use xlink:href="#xxx" transform="translate(120)"/><use xlink:href="#xxx" transform="translate(140)"/><use xlink:href="#xxx" transform="translate(160)"/><use xlink:href="#xxx" transform="translate(180)"/><use xlink:href="#xmx" transform="translate(200)"/><use xlink:href="#xxx" transform="translate(220)"/><use xlink:href="#xmv-2" transform="translate(240)"/><use xlink:href="#vvv-2" transform="translate(260)"/><use xlink:href="#vvv-2" transform="translate(280)"/><use xlink:href="#vvv-2" transform="translate(300)"/><use xlink:href="#vmx-2" transform="translate(320)"/><use xlink:href="#xxx" transform="translate(340)"/><use xlink:href="#xxx" transform="translate(360)"/><use xlink:href="#xxx" transform="translate(380)"/><use xlink:href="#xxx" transform="translate(400)"/><use xlink:href="#xxx" transform="translate(420)"/><use xlink:href="#xxx" transform="translate(440)"/><use xlink:href="#xxx" transform="translate(460)"/><use xlink:href="#xxx" transform="translate(480)"/><use xlink:href="#xxx" transform="translate(500)"/><use xlink:href="#xxx" transform="translate(520)"/><use xlink:href="#xxx" transform="translate(540)"/><use xlink:href="#xxx" transform="translate(560)"/><use xlink:href="#xxx" transform="translate(580)"/><use xlink:href="#xmx" transform="translate(600)"/><use xlink:href="#xxx" transform="translate(620)"/><use xlink:href="#xmv-2" transform="translate(640)"/><use xlink:href="#vvv-2" transform="translate(660)"/><use xlink:href="#vvv-2" transform="translate(680)"/><use xlink:href="#vvv-2" transform="translate(700)"/><use xlink:href="#vmx-2" transform="translate(720)"/><use xlink:href="#xxx" transform="translate(740)"/><text x="286" y="15" text-anchor="middle" xml:space="preserve"><tspan>SUCCESS</tspan></text><text x="686" y="15" text-anchor="middle" xml:space="preserve"><tspan>SUCCESS</tspan></text></g></g><g id="wavelane_8_0" transform="translate(0,245)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_resp.data</tspan></text><g id="wavelane_draw_8_0" transform="translate(0, 0)"><use xlink:href="#xxx" transform="translate(0)"/><use xlink:href="#xxx" transform="translate(20)"/><use xlink:href="#xxx" transform="translate(40)"/><use xlink:href="#xxx" transform="translate(60)"/><use xlink:href="#xxx" transform="translate(80)"/><use xlink:href="#xxx" transform="translate(100)"/><use xlink:href="#xxx" transform="translate(120)"/><use xlink:href="#xxx" transform="translate(140)"/><use xlink:href="#xxx" transform="translate(160)"/><use xlink:href="#xxx" transform="translate(180)"/><use xlink:href="#xmx" transform="translate(200)"/><use xlink:href="#xxx" transform="translate(220)"/><use xlink:href="#xmv-2" transform="translate(240)"/><use xlink:href="#vvv-2" transform="translate(260)"/><use xlink:href="#vvv-2" transform="translate(280)"/><use xlink:href="#vvv-2" transform="translate(300)"/><use xlink:href="#vmx-2" transform="translate(320)"/><use xlink:href="#xxx" transform="translate(340)"/><use xlink:href="#xxx" transform="translate(360)"/><use xlink:href="#xxx" transform="translate(380)"/><use xlink:href="#xxx" transform="translate(400)"/><use xlink:href="#xxx" transform="translate(420)"/><use xlink:href="#xxx" transform="translate(440)"/><use xlink:href="#xxx" transform="translate(460)"/><use xlink:href="#xxx" transform="translate(480)"/><use xlink:href="#xxx" transform="translate(500)"/><use xlink:href="#xxx" transform="translate(520)"/><use xlink:href="#xxx" transform="translate(540)"/><use xlink:href="#xxx" transform="translate(560)"/><use xlink:href="#xxx" transform="translate(580)"/><use xlink:href="#xxx" transform="translate(600)"/><use xlink:href="#xxx" transform="translate(620)"/><use xlink:href="#xxx" transform="translate(640)"/><use xlink:href="#xxx" transform="translate(660)"/><use xlink:href="#xxx" transform="translate(680)"/><use xlink:href="#xxx" transform="translate(700)"/><use xlink:href="#xxx" transform="translate(720)"/><use xlink:href="#xxx" transform="translate(740)"/><text x="286" y="15" text-anchor="middle" xml:space="preserve"><tspan>0x1234</tspan></text></g></g><g id="wavelane_9_0" transform="translate(0,275)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_resp_valid</tspan></text><g id="wavelane_draw_9_0" transform="translate(0, 0)"><use xlink:href="#000" transform="translate(0)"/><use xlink:href="#000" transform="translate(20)"/><use xlink:href="#000" transform="translate(40)"/><use xlink:href="#000" transform="translate(60)"/><use xlink:href="#000" transform="translate(80)"/><use xlink:href="#000" transform="translate(100)"/><use xlink:href="#000" transform="translate(120)"/><use xlink:href="#000" transform="translate(140)"/><use xlink:href="#000" transform="translate(160)"/><use xlink:href="#000" transform="translate(180)"/><use xlink:href="#000" transform="translate(200)"/><use xlink:href="#000" transform="translate(220)"/><use xlink:href="#0m1" transform="translate(240)"/><use xlink:href="#111" transform="translate(260)"/><use xlink:href="#111" transform="translate(280)"/><use xlink:href="#111" transform="translate(300)"/><use xlink:href="#1m0" transform="translate(320)"/><use xlink:href="#000" transform="translate(340)"/><use xlink:href="#000" transform="translate(360)"/><use xlink:href="#000" transform="translate(380)"/><use xlink:href="#000" transform="translate(400)"/><use xlink:href="#000" transform="translate(420)"/><use xlink:href="#000" transform="translate(440)"/><use xlink:href="#000" transform="translate(460)"/><use xlink:href="#000" transform="translate(480)"/><use xlink:href="#000" transform="translate(500)"/><use xlink:href="#000" transform="translate(520)"/><use xlink:href="#000" transform="translate(540)"/><use xlink:href="#000" transform="translate(560)"/><use xlink:href="#000" transform="translate(580)"/><use xlink:href="#000" transform="translate(600)"/><use xlink:href="#000" transform="translate(620)"/><use xlink:href="#000" transform="translate(640)"/><use xlink:href="#000" transform="translate(660)"/><use xlink:href="#0m1" transform="translate(680)"/><use xlink:href="#111" transform="translate(700)"/><use xlink:href="#1m0" transform="translate(720)"/><use xlink:href="#000" transform="translate(740)"/></g></g><g id="wavelane_10_0" transform="translate(0,305)"><text x="-10" y="15" class="info" text-anchor="end" xml:space="preserve"><tspan>dmi_resp_ready</tspan></text><g id="wavelane_draw_10_0" transform="translate(0, 0)"><use xlink:href="#111" transform="translate(0)"/><use xlink:href="#111" transform="translate(20)"/><use xlink:href="#111" transform="translate(40)"/><use xlink:href="#111" transform="translate(60)"/><use xlink:href="#111" transform="translate(80)"/><use xlink:href="#111" transform="translate(100)"/><use xlink:href="#111" transform="translate(120)"/><use xlink:href="#111" transform="translate(140)"/><use xlink:href="#111" transform="translate(160)"/><use xlink:href="#111" transform="translate(180)"/><use xlink:href="#1m0" transform="translate(200)"/><use xlink:href="#000" transform="translate(220)"/><use xlink:href="#000" transform="translate(240)"/><use xlink:href="#000" transform="translate(260)"/><use xlink:href="#0m1" transform="translate(280)"/><use xlink:href="#111" transform="translate(300)"/><use xlink:href="#111" transform="translate(320)"/><use xlink:href="#111" transform="translate(340)"/><use xlink:href="#111" transform="translate(360)"/><use xlink:href="#111" transform="translate(380)"/><use xlink:href="#111" transform="translate(400)"/><use xlink:href="#111" transform="translate(420)"/><use xlink:href="#111" transform="translate(440)"/><use xlink:href="#111" transform="translate(460)"/><use xlink:href="#111" transform="translate(480)"/><use xlink:href="#111" transform="translate(500)"/><use xlink:href="#111" transform="translate(520)"/><use xlink:href="#111" transform="translate(540)"/><use xlink:href="#111" transform="translate(560)"/><use xlink:href="#111" transform="translate(580)"/><use xlink:href="#111" transform="translate(600)"/><use xlink:href="#111" transform="translate(620)"/><use xlink:href="#111" transform="translate(640)"/><use xlink:href="#111" transform="translate(660)"/><use xlink:href="#111" transform="translate(680)"/><use xlink:href="#111" transform="translate(700)"/><use xlink:href="#111" transform="translate(720)"/><use xlink:href="#111" transform="translate(740)"/></g></g><g id="wavearcs_0"/><g id="wavegaps_0"><g id="wavegap_0_0" transform="translate(0,5)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_1_0" transform="translate(0,35)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_2_0" transform="translate(0,65)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_3_0" transform="translate(0,95)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_4_0" transform="translate(0,125)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_5_0" transform="translate(0,155)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_6_0" transform="translate(0,185)"/><g id="wavegap_7_0" transform="translate(0,215)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_8_0" transform="translate(0,245)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_9_0" transform="translate(0,275)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g><g id="wavegap_10_0" transform="translate(0,305)"><use xlink:href="#gap" transform="translate(180)"/><use xlink:href="#gap" transform="translate(380)"/><use xlink:href="#gap" transform="translate(580)"/></g></g></g><g id="groups_0">g</g></g></svg>
// Copyright 2020 Silicon Labs, Inc. // // This file, and derivatives thereof are licensed under the // Solderpad License, Version 2.0 (the "License"). // // Use of this file means you agree to the terms and conditions // of the license and are in full compliance with the License. // // You may obtain a copy of the License at: // // https://solderpad.org/licenses/SHL-2.0/ // // Unless required by applicable law or agreed to in writing, software // and hardware implementations thereof distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESSED OR IMPLIED. // // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// // Engineer: Arjan Bink - [email protected] // // // // Design Name: OBI Wrapper for Debug Module (dm_top) // // Project Name: CV32E40P // // Language: SystemVerilog // // // // Description: Wrapper for the Debug Module (dm_top) which gives it an // // OBI (Open Bus Interface) compatible interfaces so that it // // can be integrated without further glue logic (other than // // tie offs in an OBI compliant system. // // // // This wrapper is only intended for OBI compliant systems; // // in other systems the existing dm_top can be used as before // // and this wrapper can be ignored. // // // // The OBI spec is available at: // // // // - https://github.com/openhwgroup/core-v-docs/blob/master/ // // cores/cv32e40p/ // // // // Compared to 'logint' interfaces of dm_top the following // // signals are added: // // // // - slave_* OBI interface: // // // // - slave_gnt_o // // - slave_rvalid_o // // - slave_aid_i // // - slave_rid_o // // // // Compared to 'logint' interfaces of dm_top the following // // signals have been renamed: // // // // - master_* OBI interface: // // // // - Renamed master_add_o to master_addr_o // // - Renamed master_r_valid_i to master_rvalid_i // // - Renamed master_r_rdata_i to master_rdata_i // // // //////////////////////////////////////////////////////////////////////////////// module dm_obi_top #( parameter int unsigned IdWidth = 1, // Width of aid/rid parameter int unsigned NrHarts = 1, parameter int unsigned BusWidth = 32, parameter int unsigned DmBaseAddress = 'h1000, // default to non-zero page // Bitmask to select physically available harts for systems // that don't use hart numbers in a contiguous fashion. parameter logic [NrHarts-1:0] SelectableHarts = {NrHarts{1'b1}} ) ( input logic clk_i, // clock // asynchronous reset active low, connect PoR here, not the system reset input logic rst_ni, input logic testmode_i, output logic ndmreset_o, // non-debug module reset output logic dmactive_o, // debug module is active output logic [NrHarts-1:0] debug_req_o, // async debug request // communicate whether the hart is unavailable (e.g.: power down) input logic [NrHarts-1:0] unavailable_i, input dm::hartinfo_t [NrHarts-1:0] hartinfo_i, input logic slave_req_i, // OBI grant for slave_req_i (not present on dm_top) output logic slave_gnt_o, input logic slave_we_i, input logic [BusWidth-1:0] slave_addr_i, input logic [BusWidth/8-1:0] slave_be_i, input logic [BusWidth-1:0] slave_wdata_i, // Address phase transaction identifier (not present on dm_top) input logic [IdWidth-1:0] slave_aid_i, // OBI rvalid signal (end of response phase for reads/writes) (not present on dm_top) output logic slave_rvalid_o, output logic [BusWidth-1:0] slave_rdata_o, // Response phase transaction identifier (not present on dm_top) output logic [IdWidth-1:0] slave_rid_o, output logic master_req_o, output logic [BusWidth-1:0] master_addr_o, // Renamed according to OBI spec output logic master_we_o, output logic [BusWidth-1:0] master_wdata_o, output logic [BusWidth/8-1:0] master_be_o, input logic master_gnt_i, input logic master_rvalid_i, // Renamed according to OBI spec input logic [BusWidth-1:0] master_rdata_i, // Renamed according to OBI spec // Connection to DTM - compatible to RocketChip Debug Module input logic dmi_rst_ni, input logic dmi_req_valid_i, output logic dmi_req_ready_o, input dm::dmi_req_t dmi_req_i, output logic dmi_resp_valid_o, input logic dmi_resp_ready_i, output dm::dmi_resp_t dmi_resp_o ); // Slave response phase (rvalid and identifier) logic slave_rvalid_q; logic [IdWidth-1:0] slave_rid_q; // dm_top instance dm_top #( .NrHarts ( NrHarts ), .BusWidth ( BusWidth ), .DmBaseAddress ( DmBaseAddress ), .SelectableHarts ( SelectableHarts ) ) i_dm_top ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .testmode_i ( testmode_i ), .ndmreset_o ( ndmreset_o ), .dmactive_o ( dmactive_o ), .debug_req_o ( debug_req_o ), .unavailable_i ( unavailable_i ), .hartinfo_i ( hartinfo_i ), .slave_req_i ( slave_req_i ), .slave_we_i ( slave_we_i ), .slave_addr_i ( slave_addr_i ), .slave_be_i ( slave_be_i ), .slave_wdata_i ( slave_wdata_i ), .slave_rdata_o ( slave_rdata_o ), .master_req_o ( master_req_o ), .master_add_o ( master_addr_o ), // Renamed according to OBI spec .master_we_o ( master_we_o ), .master_wdata_o ( master_wdata_o ), .master_be_o ( master_be_o ), .master_gnt_i ( master_gnt_i ), .master_r_valid_i ( master_rvalid_i ), // Renamed according to OBI spec .master_r_rdata_i ( master_rdata_i ), // Renamed according to OBI spec .dmi_rst_ni ( dmi_rst_ni ), .dmi_req_valid_i ( dmi_req_valid_i ), .dmi_req_ready_o ( dmi_req_ready_o ), .dmi_req_i ( dmi_req_i ), .dmi_resp_valid_o ( dmi_resp_valid_o ), .dmi_resp_ready_i ( dmi_resp_ready_i ), .dmi_resp_o ( dmi_resp_o ) ); // Extension to wrap dm_top as an OBI-compliant module // // dm_top has an implied rvalid pulse the cycle after its granted request. // Registers always_ff @(posedge clk_i or negedge rst_ni) begin : obi_regs if (!rst_ni) begin slave_rvalid_q <= 1'b0; slave_rid_q <= 'b0; end else begin if (slave_req_i && slave_gnt_o) begin // 1 cycle pulse on rvalid for every granted request slave_rvalid_q <= 1'b1; slave_rid_q <= slave_aid_i; // Mirror aid to rid end else begin slave_rvalid_q <= 1'b0; // rid is don't care if rvalid = 0 end end end assign slave_gnt_o = 1'b1; // Always receptive to request (slave_req_i) assign slave_rvalid_o = slave_rvalid_q; assign slave_rid_o = slave_rid_q; endmodule : dm_obi_top
// Copyright 2020 Silicon Labs, Inc. // // This file, and derivatives thereof are licensed under the // Solderpad License, Version 2.0 (the "License"). // // Use of this file means you agree to the terms and conditions // of the license and are in full compliance with the License. // // You may obtain a copy of the License at: // // https://solderpad.org/licenses/SHL-2.0/ // // Unless required by applicable law or agreed to in writing, software // and hardware implementations thereof distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESSED OR IMPLIED. // // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// // Engineer: Arjan Bink - [email protected] // // // // Design Name: dm_csrs_sva // // Language: SystemVerilog // // // // Description: SystemVerilog assertions for dm_csrs // // // //////////////////////////////////////////////////////////////////////////////// module dm_csrs_sva #( parameter int unsigned NrHarts = 1, parameter int unsigned BusWidth = 32, parameter logic [NrHarts-1:0] SelectableHarts = {NrHarts{1'b1}} )( input logic clk_i, input logic rst_ni, input logic dmi_req_valid_i, input logic dmi_req_ready_o, input dm::dmi_req_t dmi_req_i, input dm::dtm_op_e dtm_op ); /////////////////////////////////////////////////////// // Assertions /////////////////////////////////////////////////////// haltsum: assert property ( @(posedge clk_i) disable iff (!rst_ni) (dmi_req_ready_o && dmi_req_valid_i && dtm_op == dm::DTM_READ) |-> !({1'b0, dmi_req_i.addr} inside {dm::HaltSum0, dm::HaltSum1, dm::HaltSum2, dm::HaltSum3})) else $warning("Haltsums have not been properly tested yet."); endmodule: dm_csrs_sva
// Copyright 2020 Silicon Labs, Inc. // // This file, and derivatives thereof are licensed under the // Solderpad License, Version 2.0 (the "License"). // // Use of this file means you agree to the terms and conditions // of the license and are in full compliance with the License. // // You may obtain a copy of the License at: // // https://solderpad.org/licenses/SHL-2.0/ // // Unless required by applicable law or agreed to in writing, software // and hardware implementations thereof distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESSED OR IMPLIED. // // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// // Engineer: Arjan Bink - [email protected] // // // // Design Name: dm_sba_sva // // Language: SystemVerilog // // // // Description: SystemVerilog assertions for dm_sba // // // //////////////////////////////////////////////////////////////////////////////// module dm_sba_sva #( parameter int unsigned BusWidth = 32, parameter bit ReadByteEnable = 1 )( input logic clk_i, input logic dmactive_i, input logic [2:0] sbaccess_i, input dm::sba_state_e state_d ); /////////////////////////////////////////////////////// // Assertions /////////////////////////////////////////////////////// // maybe bump severity to $error if not handled at runtime dm_sba_access_size: assert property(@(posedge clk_i) disable iff (dmactive_i !== 1'b0) (state_d != dm::Idle) |-> (sbaccess_i < 4)) else $warning ("accesses > 8 byte not supported at the moment"); endmodule: dm_sba_sva
// Copyright 2020 Silicon Labs, Inc. // // This file, and derivatives thereof are licensed under the // Solderpad License, Version 2.0 (the "License"). // // Use of this file means you agree to the terms and conditions // of the license and are in full compliance with the License. // // You may obtain a copy of the License at: // // https://solderpad.org/licenses/SHL-2.0/ // // Unless required by applicable law or agreed to in writing, software // and hardware implementations thereof distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESSED OR IMPLIED. // // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// // Engineer: Arjan Bink - [email protected] // // // // Design Name: dm_top_sva // // Language: SystemVerilog // // // // Description: SystemVerilog assertions for dm_top // // // //////////////////////////////////////////////////////////////////////////////// module dm_top_sva #( parameter int unsigned NrHarts = 1, parameter int unsigned BusWidth = 32, parameter int unsigned DmBaseAddress = 'h1000, parameter logic [NrHarts-1:0] SelectableHarts = {NrHarts{1'b1}}, parameter bit ReadByteEnable = 1 )( input logic clk_i, input logic rst_ni, input dm::hartinfo_t [NrHarts-1:0] hartinfo_i ); /////////////////////////////////////////////////////// // Assertions /////////////////////////////////////////////////////// // Check that BusWidth is supported bus_width: assert property ( @(posedge clk_i) disable iff (!rst_ni) (1'b1) |-> (BusWidth == 32 || BusWidth == 64)) else $fatal(1, "DM needs a bus width of either 32 or 64 bits"); // Fail if the DM is not located on the zero page and one hart doesn't have two scratch registers. genvar i; generate for (i = 0; i < NrHarts; i++) begin hart_info: assert property ( @(posedge clk_i) disable iff (!rst_ni) (1'b1) |-> ((DmBaseAddress > 0 && hartinfo_i[i].nscratch >= 2) || (DmBaseAddress == 0 && hartinfo_i[i].nscratch >= 1))) else $fatal(1, "If the DM is not located at the zero page each hart needs at least two scratch registers %d %d",i, hartinfo_i[i].nscratch); end endgenerate endmodule: dm_top_sva
--- BasedOnStyle: LLVM IndentWidth: 4 UseTab: Never BreakBeforeBraces: Linux AlwaysBreakBeforeMultilineStrings: true AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AllowShortFunctionsOnASingleLine: false IndentCaseLabels: false AlignEscapedNewlinesLeft: false AlignTrailingComments: true AlignOperands: true AllowAllParametersOfDeclarationOnNextLine: false AlignAfterOpenBracket: true SpaceAfterCStyleCast: false MaxEmptyLinesToKeep: 2 BreakBeforeBinaryOperators: NonAssignment BreakStringLiterals: false SortIncludes: false ContinuationIndentWidth: 4 ColumnLimit: 80 IndentPPDirectives: AfterHash BinPackArguments: true BinPackParameters: true ForEachMacros: - 'TAILQ_FOREACH' - 'TAILQ_FOREACH_REVERSE' BreakBeforeBinaryOperators: None MaxEmptyLinesToKeep: 1 AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlignConsecutiveAssignments: true ...
TAGS memory_dump.bin modelsim.ini *.o work/* *.vstf *.wlf *.log objdump .build-rtl .lib-rtl .opt-rtl *.elf *.hex riscv common_cells tech_cells_generic fpnew transcript .nfs* simv* ucli.key DVEfiles cobj_dir obj_dir testbench_verilator
// Copyright 2020 ETH Zurich and University of Bologna. // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // Author: Robert Balas <[email protected]> // Description: Bootrom for firmware booting module boot_rom ( input logic clk_i, input logic req_i, input logic [31:0] addr_i, output logic [31:0] rdata_o ); localparam int RomSize = 2; localparam logic [31:0] entry_addr = 32'h1c00_0080; logic [RomSize-1:0][31:0] mem; assign mem = { dm_tb_pkg::jalr(5'h0, 5'h1, entry_addr[11:0]), dm_tb_pkg::lui(5'h1, entry_addr[31:12]) }; logic [$clog2(RomSize)-1:0] addr_q; assign rdata_o = (addr_q < RomSize) ? mem[addr_q] : '0; always_ff @(posedge clk_i) begin if (req_i) begin addr_q <= addr_i[$clog2(RomSize)-1+3:2]; end end endmodule
debug_level 4 adapter_khz 10000 interface remote_bitbang remote_bitbang_host localhost remote_bitbang_port 9999 set _CHIPNAME riscv jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id 0x249511C3 foreach t [jtag names] { puts [format "TAP: %s\n" $t] } set _TARGETNAME $_CHIPNAME.cpu #target create $_TARGETNAME riscv -chain-position $_TARGETNAME -coreid 0x3e0 target create $_TARGETNAME riscv -chain-position $_TARGETNAME -rtos riscv riscv set_reset_timeout_sec 2000 riscv set_command_timeout_sec 2000 # prefer to use sba for system bus access riscv set_prefer_sba on # dump jtag chain scan_chain init riscv test_compliance shutdown
debug_level 4 adapter_khz 10000 interface remote_bitbang remote_bitbang_host localhost remote_bitbang_port $::env(JTAG_VPI_PORT) set _CHIPNAME riscv jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id 0x249511C3 foreach t [jtag names] { puts [format "TAP: %s\n" $t] } set _TARGETNAME $_CHIPNAME.cpu #target create $_TARGETNAME riscv -chain-position $_TARGETNAME -coreid 0x3e0 target create $_TARGETNAME riscv -chain-position $_TARGETNAME -rtos riscv riscv set_reset_timeout_sec 2000 riscv set_command_timeout_sec 2000 # prefer to use sba for system bus access riscv set_prefer_sba on # dump jtag chain scan_chain init halt echo "Ready for Remote Connections"
// Copyright 2020 ETH Zurich and University of Bologna. // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // // Contributor: Robert Balas <[email protected]> package dm_tb_pkg; // PULPissimo-like memory map typedef enum logic [31:0] { ROM_BASE = 32'h1A00_0000, FLL_BASE = 32'h1A10_0000, GPIO_BASE = 32'h1A10_1000, UDMA_BASE = 32'h1A10_2000, CNTRL_BASE = 32'h1A10_4000, ADVTIMER_BASE = 32'h1A10_5000, EVENT_BASE = 32'h1A10_6000, TIMER_BASE = 32'h1A10_B000, HWPE_BASE = 32'h1A10_C000, STDOUT_BASE = 32'h1A10_F000, DEBUG_BASE = 32'h1A11_0000, SRAM_BASE = 32'h1C00_0000 } mmap_base_t; localparam logic [31:0] ROM_LEN = 32'h0010_0000; localparam logic [31:0] FLL_LEN = 32'h0000_1000; localparam logic [31:0] GPIO_LEN = 32'h0000_1000; localparam logic [31:0] UDMA_LEN = 32'h0000_2000; localparam logic [31:0] CNTRL_LEN = 32'h0000_1000; localparam logic [31:0] ADVTIMER_LEN = 32'h0000_1000; localparam logic [31:0] EVENT_LEN = 32'h0000_5000; localparam logic [31:0] TIMER_LEN = 32'h0000_1000; localparam logic [31:0] HWPE_LEN = 32'h0000_3000; localparam logic [31:0] STDOUT_LEN = 32'h0000_1000; localparam logic [31:0] DEBUG_LEN = 32'h0000_1000; localparam logic [31:0] SRAM_LEN = 32'h000f_C000; // helper functions function automatic logic [31:0] jal (logic[4:0] rd, logic [20:0] imm); return {imm[20], imm[10:1], imm[11], imm[19:12], rd, 7'h6f}; endfunction function automatic logic [31:0] jalr (logic[4:0] rd, logic[4:0] rs1, logic [11:0] offset); return {offset[11:0], rs1, 3'b0, rd, 7'h67}; endfunction function automatic logic [31:0] lui (logic[4:0] rd, logic [19:0] uimm); return {uimm, rd, 7'b0110111}; endfunction endpackage // riscv_tb_pkg
// Copyright 2020 ETH Zurich and University of Bologna. // Copyright 2017 Embecosm Limited <www.embecosm.com> // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. module dp_ram #( parameter int unsigned ADDR_WIDTH = 8, parameter int unsigned INSTR_RDATA_WIDTH = 128 ) ( input logic clk_i, input logic en_a_i, input logic [ADDR_WIDTH-1:0] addr_a_i, input logic [31:0] wdata_a_i, output logic [INSTR_RDATA_WIDTH-1:0] rdata_a_o, input logic we_a_i, input logic [3:0] be_a_i, input logic en_b_i, input logic [ADDR_WIDTH-1:0] addr_b_i, input logic [31:0] wdata_b_i, output logic [31:0] rdata_b_o, input logic we_b_i, input logic [3:0] be_b_i ); localparam bytes = 2**ADDR_WIDTH; logic [7:0] mem[bytes]; logic [ADDR_WIDTH-1:0] addr_a_int; logic [ADDR_WIDTH-1:0] addr_b_int; always_comb addr_a_int = {addr_a_i[ADDR_WIDTH-1:2], 2'b0}; always_comb addr_b_int = {addr_b_i[ADDR_WIDTH-1:2], 2'b0}; always @(posedge clk_i) begin for (int i = 0; i < INSTR_RDATA_WIDTH/8; i++) begin rdata_a_o[(i*8)+: 8] <= mem[addr_a_int + i]; end /* addr_b_i is the actual memory address referenced */ if (en_b_i) begin /* handle writes */ if (we_b_i) begin if (be_b_i[0]) mem[addr_b_int ] <= wdata_b_i[ 0+:8]; if (be_b_i[1]) mem[addr_b_int + 1] <= wdata_b_i[ 8+:8]; if (be_b_i[2]) mem[addr_b_int + 2] <= wdata_b_i[16+:8]; if (be_b_i[3]) mem[addr_b_int + 3] <= wdata_b_i[24+:8]; end /* handle reads */ else begin if ($test$plusargs("verbose")) $display("read addr=0x%08x: data=0x%08x", addr_b_int, {mem[addr_b_int + 3], mem[addr_b_int + 2], mem[addr_b_int + 1], mem[addr_b_int + 0]}); rdata_b_o[ 7: 0] <= mem[addr_b_int ]; rdata_b_o[15: 8] <= mem[addr_b_int + 1]; rdata_b_o[23:16] <= mem[addr_b_int + 2]; rdata_b_o[31:24] <= mem[addr_b_int + 3]; end end end export "DPI-C" function read_byte; export "DPI-C" task write_byte; function int read_byte(input logic [ADDR_WIDTH-1:0] byte_addr); read_byte = mem[byte_addr]; endfunction task write_byte(input integer byte_addr, logic [7:0] val, output logic [7:0] other); mem[byte_addr] = val; other = mem[byte_addr]; endtask endmodule // dp_ram
Copyright (c) 2011-2016, The Regents of the University of California (Regents). All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Regents nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016-2017 SiFive, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# Copyright 2019 Clifford Wolf # Copyright 2019 Robert Balas # Copyright 2020 ETH Zurich and University of Bologna. # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # Author: Robert Balas ([email protected]) # Description: All in one. Uses parts of picorv32's makefile. MAKE = make CTAGS = ctags # vsim configuration VVERSION = "10.7b" VLIB = vlib-$(VVERSION) VWORK = work VLOG = vlog-$(VVERSION) VLOG_FLAGS = -pedanticerrors -suppress 2577 -suppress 2583 VLOG_LOG = vloggy VOPT = vopt-$(VVERSION) VOPT_FLAGS = -debugdb -fsmdebug -pedanticerrors #=mnprft VSIM = vsim-$(VVERSION) VSIM_HOME = /usr/pack/modelsim-$(VVERSION)-kgf/questasim VSIM_FLAGS = # user defined ALL_VSIM_FLAGS = $(VSIM_FLAGS) -sv_lib remote_bitbang/librbs_vsim VSIM_DEBUG_FLAGS = -debugdb VSIM_GUI_FLAGS = -gui -debugdb VSIM_SCRIPT_BATCH = vsim_batch.tcl VSIM_SCRIPT_GUI = vsim_gui.tcl VCS = vcs-2017.03-kgf vcs VCS_HOME = /usr/pack/vcs-2017.03-kgf VCS_FLAGS = SIMV_FLAGS = # verilator configuration VERILATOR = verilator VERI_FLAGS = VERI_COMPILE_FLAGS = VERI_TRACE = VERI_DIR = cobj_dir VERI_CFLAGS = -O2 # RTL source files RTLSRC_TB_PKG := RTLSRC_TB_TOP := tb_top.sv RTLSRC_TB := boot_rom.sv \ dp_ram.sv \ mm_ram.sv \ SimJTAG.sv \ ../sva/dm_top_sva.sv \ ../sva/dm_csrs_sva.sv \ ../sva/dm_sba_sva.sv \ tb_test_env.sv \ tb_top.sv RTLSRC_VERI_TB := boot_rom.sv \ dp_ram.sv \ mm_ram.sv \ SimJTAG.sv \ tb_top_verilator.sv RTLSRC_INCDIR := riscv/rtl/include RTLSRC_FPNEW_PKG := fpnew/src/fpnew_pkg.sv RTLSRC_RISCV_PKG += $(addprefix riscv/rtl/include/,\ cv32e40p_apu_core_pkg.sv cv32e40p_pkg.sv \ ../../bhv/include/cv32e40p_tracer_pkg.sv) RTLSRC_DM_PKG += ../src/dm_pkg.sv RTLSRC_PKG = $(RTLSRC_FPNEW_PKG) dm_tb_pkg.sv $(RTLSRC_RISCV_PKG) $(RTLSRC_DM_PKG) RTLSRC_RISCV := $(addprefix riscv/rtl/,\ ../bhv/cv32e40p_sim_clock_gate.sv \ ../bhv/cv32e40p_tracer.sv \ cv32e40p_if_stage.sv \ cv32e40p_cs_registers.sv \ cv32e40p_register_file_ff.sv \ cv32e40p_load_store_unit.sv \ cv32e40p_id_stage.sv \ cv32e40p_aligner.sv \ cv32e40p_decoder.sv \ cv32e40p_compressed_decoder.sv \ cv32e40p_fifo.sv \ cv32e40p_prefetch_buffer.sv \ cv32e40p_hwloop_regs.sv \ cv32e40p_mult.sv \ cv32e40p_int_controller.sv \ cv32e40p_ex_stage.sv \ cv32e40p_alu_div.sv \ cv32e40p_alu.sv \ cv32e40p_ff_one.sv \ cv32e40p_popcnt.sv \ cv32e40p_apu_disp.sv \ cv32e40p_controller.sv \ cv32e40p_obi_interface.sv \ cv32e40p_prefetch_controller.sv \ cv32e40p_sleep_unit.sv \ cv32e40p_core.sv) RTLSRC_COMMON := $(addprefix common_cells/src/,\ cdc_2phase.sv fifo_v2.sv fifo_v3.sv\ rstgen.sv rstgen_bypass.sv) RTLSRC_TECH := $(addprefix tech_cells_generic/src/,\ cluster_clock_inverter.sv pulp_clock_mux2.sv\ cluster_clock_gating.sv) RTLSRC_DEBUG := ../debug_rom/debug_rom.sv RTLSRC_DEBUG += $(addprefix ../src/,\ dm_csrs.sv dmi_cdc.sv dmi_jtag.sv \ dmi_jtag_tap.sv dm_mem.sv \ dm_sba.sv dm_top.sv dm_obi_top.sv) RTLSRC += $(RTLSRC_RISCV) $(RTLSRC_COMMON) $(RTLSRC_TECH) $(RTLSRC_DEBUG) # versions for this tb CV32E40P_SHA = f9d63290eea738cb0a6fbf1e77bbd18555015a03 FPU_SHA = v0.6.1 COMMON_SHA = 337f54a7cdfdad78b124cbdd2a627db3e0939141 TECH_SHA = b35652608124b7ea813818b14a00ca76edd7599d RAM_START_ADDR = 0x1c000000 # TODO: clean this up RTLSRC_VLOG_TB_TOP := $(basename $(notdir $(RTLSRC_TB_TOP))) RTLSRC_VOPT_TB_TOP := $(addsuffix _vopt, $(RTLSRC_VLOG_TB_TOP)) # riscv bare metal cross compiling RISCV ?= $(HOME)/.riscv RV_CC = $(RISCV)/bin/riscv32-unknown-elf-gcc RV_CFLAGS = -march=rv32imc -Os -g RV_LDFLAGS = -nostdlib -static -T prog/link.ld RV_LDLIBS = -lc -lm -lgcc RV_OBJCOPY = $(RISCV)/bin/riscv32-unknown-elf-objcopy # assume verilator if no target chosen .DEFAULT_GOAL := veri-run all: veri-run # vsim testbench compilation and optimization vlib: .lib-rtl .lib-rtl: $(VLIB) $(VWORK) touch .lib-rtl # rebuild if we change some sourcefile .build-rtl: .lib-rtl $(RTLSRC_PKG) $(RTLSRC) $(RTLSRC_TB_PKG) $(RTLSRC_TB) $(VLOG) -work $(VWORK) +incdir+$(RTLSRC_INCDIR) $(VLOG_FLAGS) \ $(RTLSRC_PKG) $(RTLSRC) $(RTLSRC_TB_PKG) $(RTLSRC_TB) touch .build-rtl vsim-all: .opt-rtl .opt-rtl: .build-rtl $(VOPT) -work $(VWORK) $(VOPT_FLAGS) $(RTLSRC_VLOG_TB_TOP) -o \ $(RTLSRC_VOPT_TB_TOP) touch .opt-rtl # vcs testbench compilation vcsify: $(RTLSRC_PKG) $(RTLSRC) $(RTLSRC_TB_PKG) $(RTLSRC_TB) remote_bitbang/librbs_vcs.so $(VCS) +vc -sverilog -race=all -ignore unique_checks -full64 \ -timescale=1ns/1ps \ -CC "-I$(VCS_HOME)/include -O3 -march=native" $(VCS_FLAGS) \ $(RTLSRC_PKG) $(RTLSRC) $(RTLSRC_TB_PKG) $(RTLSRC_TB) \ +incdir+$(RTLSRC_INCDIR) vcs-clean: rm -rf simv* *.daidir *.vpd *.db csrc ucli.key vc_hdrs.h # verilator testbench compilation # We first test if the user wants to to vcd dumping. This hacky part is required # because we need to conditionally compile the testbench (-DVCD_TRACE) and pass # the --trace flags to the verilator call ifeq ($(findstring +vcd,$(VERI_FLAGS)),+vcd) VERI_TRACE="--trace" VERI_CFLAGS+="-DVCD_TRACE" endif VPATH += ../ verilate: testbench_verilator # We set the RUNPATH (not RPATH, allows LD_LIBRARY_PATH to overwrite) to # remote_bitbang and manually link against librbs_veri since putting in # librbs_veri.so as parameter doesn't work because it searches in the build # directory testbench_verilator: $(RTLSRC_VERI_TB) $(RTLSRC_PKG) $(RTLSRC) \ remote_bitbang/librbs_veri.so $(VERILATOR) --cc --sv --exe $(VERI_TRACE) \ --Wno-lint --Wno-UNOPTFLAT --Wno-BLKANDNBLK \ --Wno-MODDUP +incdir+$(RTLSRC_INCDIR) --top-module \ tb_top_verilator --Mdir $(VERI_DIR) \ -CFLAGS "-std=gnu++11 $(VERI_CFLAGS)" $(VERI_COMPILE_FLAGS) \ $(RTLSRC_PKG) $(RTLSRC_VERI_TB) $(RTLSRC) \ -LDFLAGS "-L../remote_bitbang \ -Wl,--enable-new-dtags -Wl,-rpath,remote_bitbang -lrbs_veri" \ tb_top_verilator.cpp cd $(VERI_DIR) && $(MAKE) -f Vtb_top_verilator.mk cp $(VERI_DIR)/Vtb_top_verilator testbench_verilator verilate-clean: if [ -d $(VERI_DIR) ]; then rm -r $(VERI_DIR); fi rm -rf testbench_verilator # git dependencies download_deps: fpnew/src/fpnew_pkg.sv $(RTLSRC_COMMON) $(RTLSRC_TECH) $(RTLSRC_RISCV) fpnew/src/fpnew_pkg.sv: git clone https://github.com/pulp-platform/fpnew.git --recurse -b v0.6.1 $(RTLSRC_COMMON): git clone https://github.com/pulp-platform/common_cells.git cd common_cells/ && git checkout $(COMMON_SHA) $(RTLSRC_TECH): git clone https://github.com/pulp-platform/tech_cells_generic.git cd tech_cells_generic/ && git checkout $(TECH_SHA) $(RTLSRC_RISCV_PKG) $(RTLSRC_RISCV): git clone https://github.com/openhwgroup/cv32e40p.git riscv cd riscv/ && git checkout $(CV32E40P_SHA) # openocd server remote_bitbang/librbs_veri.so: INCLUDE_DIRS =./ $(VSIM_HOME)/include remote_bitbang/librbs_veri.so: $(MAKE) -C remote_bitbang all mv remote_bitbang/librbs.so $@ remote_bitbang/librbs_vsim.so: INCLUDE_DIRS =./ $(VSIM_HOME)/include remote_bitbang/librbs_vsim.so: $(MAKE) -C remote_bitbang all mv remote_bitbang/librbs.so $@ remote_bitbang/librbs_vcs.so: INCLUDE_DIRS =./ $(VCS_HOME)/include remote_bitbang/librbs_vcs.so: $(MAKE) -C remote_bitbang all mv remote_bitbang/librbs.so $@ rbs-clean: $(MAKE) -C remote_bitbang clean rm -rf remote_bitbang/librbs_vsim.so remote_bitbang/librbs_vcs.so # run tb and exit .PHONY: vsim-tb-run vsim-tb-run: ALL_VSIM_FLAGS += -c vsim-tb-run: vsim-all remote_bitbang/librbs_vsim.so $(VSIM) -work $(VWORK) $(ALL_VSIM_FLAGS) \ $(RTLSRC_VOPT_TB_TOP) -do 'source $(VSIM_SCRIPT_BATCH); exit -f' # run tb and drop into interactive shell .PHONY: vsim-tb-run-sh vsim-tb-run: ALL_VSIM_FLAGS += -c vsim-tb-run-sh: vsim-all remote_bitbang/librbs_vsim.so $(VSIM) -work $(VWORK) $(ALL_VSIM_FLAGS) \ $(RTLSRC_VOPT_TB_TOP) -do $(VSIM_SCRIPT_BATCH) # run tb with simulator gui .PHONY: vsim-tb-run-gui vsim-tb-run-gui: ALL_VSIM_FLAGS += $(VSIM_GUI_FLAGS) vsim-tb-run-gui: vsim-all remote_bitbang/librbs_vsim.so $(VSIM) -work $(VWORK) $(ALL_VSIM_FLAGS) \ $(RTLSRC_VOPT_TB_TOP) -do $(VSIM_SCRIPT_GUI) .PHONY: vsim-clean vsim-clean: if [ -d $(VWORK) ]; then rm -r $(VWORK); fi rm -f transcript vsim.wlf vsim.dbg trace_core*.log \ .build-rtl .opt-rtl .lib-rtl *.vcd objdump # compile and dump program prog/test.elf: prog/test.c prog/crt0.S prog/syscalls.c prog/vectors.S $(RV_CC) $(RV_CFLAGS) $(RV_CPPFLAGS) $(RV_LDFLAGS) $^ $(RV_LDLIBS) -o $@ prog/test.hex: prog/test.elf $(RV_OBJCOPY) -O verilog --change-addresses -$(RAM_START_ADDR) $< $@ .PHONY: prog-clean prog-clean: rm -vrf $(addprefix prog/,test.elf test.hex) # run program .PHONY: veri-run veri-run: verilate prog/test.hex ./testbench_verilator $(VERI_FLAGS) \ "+firmware=prog/test.hex" .PHONY: vsim-run vsim-run: vsim-all prog/test.hex vsim-run: ALL_VSIM_FLAGS += "+firmware=prog/test.hex" vsim-run: vsim-tb-run .PHONY: vsim-run-gui vsim-run-gui: vsim-all prog/test.hex vsim-run-gui: ALL_VSIM_FLAGS += "+firmware=prog/test.hex" vsim-run-gui: vsim-tb-run-gui .PHONY: vcs-run vcs-run: vcsify prog/test.hex ./simv -sv_lib remote_bitbang/librbs_vcs $(SIMV_FLAGS) "+firmware=prog/test.hex" .PHONY: vcs-run-gui vcs-run-gui: VCS_FLAGS+=-debug_all vcs-run-gui: vcsify prog/test.hex ./simv -sv_lib remote_bitbang/librbs_vcs $(SIMV_FLAGS) -gui "+firmware=prog/test.hex" # general targets .PHONY: clean clean: vsim-clean verilate-clean vcs-clean rbs-clean prog-clean .PHONY: distclean distclean: clean rm -rf common_cells/ tech_cells_generic/ fpnew/ riscv/
// Copyright 2020 ETH Zurich and University of Bologna. // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // RAM and MM wrapper for RI5CY // Contributor: Robert Balas <[email protected]> // // This maps the dp_ram module to the instruction and data ports of the RI5CY // processor core and some pseudo peripherals module mm_ram #( parameter int unsigned RAM_ADDR_WIDTH = 16, parameter int unsigned INSTR_RDATA_WIDTH = 32, parameter bit JTAG_BOOT = 1 ) ( input logic clk_i, input logic rst_ni, input logic instr_req_i, input logic [31:0] instr_addr_i, output logic [INSTR_RDATA_WIDTH-1:0] instr_rdata_o, output logic instr_rvalid_o, output logic instr_gnt_o, input logic data_req_i, input logic [31:0] data_addr_i, input logic data_we_i, input logic [3:0] data_be_i, input logic [31:0] data_wdata_i, output logic [31:0] data_rdata_o, output logic data_rvalid_o, output logic data_gnt_o, input logic sb_req_i, input logic [31:0] sb_addr_i, input logic sb_we_i, input logic [3:0] sb_be_i, input logic [31:0] sb_wdata_i, output logic [31:0] sb_rdata_o, output logic sb_rvalid_o, output logic sb_gnt_o, output logic dm_req_o, output logic [31:0] dm_addr_o, output logic dm_we_o, output logic [3:0] dm_be_o, output logic [31:0] dm_wdata_o, input logic [31:0] dm_rdata_i, input logic dm_rvalid_i, input logic dm_gnt_i, input logic [4:0] irq_id_i, input logic irq_ack_i, output logic [4:0] irq_id_o, output logic irq_o, output logic tests_passed_o, output logic tests_failed_o ); import dm_tb_pkg::*; localparam int TIMER_IRQ_ID = 3; // mux for read and writes enum logic [2:0]{RAM, DEBUG, ROM, UNMAP, IDLE_READ} select_rdata_d, select_rdata_q; enum logic [1:0]{SB, CORE, IDLE_WRITE} select_wdata_d, select_wdata_q; logic data_rvalid_d, data_rvalid_q; logic sb_rvalid_d, sb_rvalid_q; logic instr_rvalid_d, instr_rvalid_q; // TODO: oof logic [31:0] data_addr_aligned; // signals to ram logic ram_data_req; logic [RAM_ADDR_WIDTH-1:0] ram_data_addr; logic [31:0] ram_data_wdata; logic [31:0] ram_data_rdata; logic ram_data_we; logic [3:0] ram_data_be; // signals to rom logic rom_req; logic [31:0] rom_addr; logic [31:0] rom_rdata; // signals to read access debug unit logic dm_req; logic [31:0] dm_addr; logic dm_we; logic [3:0] dm_be; logic [31:0] dm_wdata; logic [31:0] dm_rdata; logic dm_rvalid; logic dm_gnt; logic ram_instr_req; logic [31:0] ram_instr_addr; logic [INSTR_RDATA_WIDTH-1:0] ram_instr_rdata; // signals to print peripheral logic [31:0] print_wdata; logic print_valid; // signals to timer logic [31:0] timer_irq_mask_q; logic [31:0] timer_cnt_q; logic irq_q; logic timer_reg_valid; logic timer_val_valid; logic [31:0] timer_wdata; // uhh, align? always_comb data_addr_aligned = {data_addr_i[31:2], 2'b0}; // Handle system bus, core data accesses and instr access to rom, ram and // debug unit. Someone make a for gen loop here. always_comb begin sb_gnt_o = '0; data_gnt_o = '0; instr_gnt_o = '0; ram_data_req = '0; ram_data_addr = '0; ram_data_wdata = '0; ram_data_we = '0; ram_data_be = '0; ram_instr_req = '0; ram_instr_addr = '0; dm_req = '0; dm_addr = '0; dm_we = '0; dm_be = '0; dm_wdata = '0; rom_req = '0; rom_addr = '0; print_wdata = '0; print_valid = '0; select_rdata_d = IDLE_READ; select_wdata_d = IDLE_WRITE; data_rvalid_d = '0; sb_rvalid_d = '0; instr_rvalid_d = '0; tests_passed_o = '0; tests_failed_o = '0; // memory map: // the ram is mapped from 0 to SRAM_LEN and SRAM_BASE to SRAM_BASE + SRAM_LEN // this mirroring is the same as in pulpissimo // instruction data reads to ram can always go if (instr_req_i && ((instr_addr_i >= SRAM_BASE && instr_addr_i < SRAM_BASE + SRAM_LEN) || (instr_addr_i >= 0 && instr_addr_i < SRAM_LEN))) begin instr_gnt_o = '1; instr_rvalid_d = '1; ram_instr_req = '1; ram_instr_addr = instr_addr_i; end // priority to sb access over data access if (sb_req_i) begin sb_gnt_o = '1; sb_rvalid_d = '1; if (sb_we_i) begin // handle writes if (sb_addr_i >= ROM_BASE && sb_addr_i < ROM_BASE + ROM_LEN) begin end else if (sb_addr_i >= FLL_BASE && sb_addr_i < FLL_BASE + FLL_LEN) begin end else if (sb_addr_i >= GPIO_BASE && sb_addr_i < GPIO_BASE + GPIO_LEN) begin end else if (sb_addr_i >= UDMA_BASE && sb_addr_i < UDMA_BASE + UDMA_LEN) begin end else if (sb_addr_i >= CNTRL_BASE && sb_addr_i < CNTRL_BASE + CNTRL_LEN) begin end else if (sb_addr_i >= ADVTIMER_BASE && sb_addr_i < ADVTIMER_BASE + ADVTIMER_LEN) begin end else if (sb_addr_i >= EVENT_BASE && sb_addr_i < EVENT_BASE + EVENT_LEN) begin end else if (sb_addr_i >= TIMER_BASE && sb_addr_i < TIMER_BASE + TIMER_LEN) begin end else if (sb_addr_i >= HWPE_BASE && sb_addr_i < HWPE_BASE + HWPE_LEN) begin end else if (sb_addr_i >= STDOUT_BASE && sb_addr_i < STDOUT_BASE + STDOUT_LEN) begin select_wdata_d = SB; print_wdata = sb_wdata_i; print_valid = '1; end else if (sb_addr_i >= DEBUG_BASE && sb_addr_i < DEBUG_BASE + DEBUG_LEN) begin end else if ((sb_addr_i >= SRAM_BASE && sb_addr_i < SRAM_BASE + SRAM_LEN) || (sb_addr_i >= 0 && sb_addr_i < SRAM_LEN)) begin select_wdata_d = SB; ram_data_req = sb_req_i; ram_data_addr = sb_addr_i[RAM_ADDR_WIDTH-1:0]; // just clip higher bits ram_data_wdata = sb_wdata_i; ram_data_we = sb_we_i; ram_data_be = sb_be_i; end else begin $error("Writing to unmapped memory at %x", sb_addr_i); end end else begin // handle reads if (sb_addr_i >= ROM_BASE && sb_addr_i < ROM_BASE + ROM_LEN) begin select_rdata_d = ROM; end else if (sb_addr_i >= FLL_BASE && sb_addr_i < FLL_BASE + FLL_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= GPIO_BASE && sb_addr_i < GPIO_BASE + GPIO_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= UDMA_BASE && sb_addr_i < UDMA_BASE + UDMA_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= CNTRL_BASE && sb_addr_i < CNTRL_BASE + CNTRL_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= ADVTIMER_BASE && sb_addr_i < ADVTIMER_BASE + ADVTIMER_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= EVENT_BASE && sb_addr_i < EVENT_BASE + EVENT_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= TIMER_BASE && sb_addr_i < TIMER_BASE + TIMER_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= HWPE_BASE && sb_addr_i < HWPE_BASE + HWPE_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= STDOUT_BASE && sb_addr_i < STDOUT_BASE + STDOUT_LEN) begin select_rdata_d = UNMAP; end else if (sb_addr_i >= DEBUG_BASE && sb_addr_i < DEBUG_BASE + DEBUG_LEN) begin select_rdata_d = UNMAP; end else if ((sb_addr_i >= SRAM_BASE && sb_addr_i < SRAM_BASE + SRAM_LEN) || (sb_addr_i >= 0 && sb_addr_i < SRAM_LEN)) begin select_rdata_d = RAM; ram_data_req = sb_req_i; ram_data_addr = sb_addr_i[RAM_ADDR_WIDTH-1:0]; ram_data_wdata = sb_wdata_i; ram_data_we = sb_we_i; ram_data_be = sb_be_i; end else begin select_rdata_d = UNMAP; end end end else if (data_req_i) begin data_gnt_o = '1; data_rvalid_d = '1; if (data_we_i) begin // handle writes if (data_addr_i >= ROM_BASE && data_addr_i < ROM_BASE + ROM_LEN) begin end else if (data_addr_i >= FLL_BASE && data_addr_i < FLL_BASE + FLL_LEN) begin end else if (data_addr_i >= GPIO_BASE && data_addr_i < GPIO_BASE + GPIO_LEN) begin end else if (data_addr_i >= UDMA_BASE && data_addr_i < UDMA_BASE + UDMA_LEN) begin end else if (data_addr_i >= CNTRL_BASE && data_addr_i < CNTRL_BASE + CNTRL_LEN) begin if(data_wdata_i === 32'hF00D) tests_passed_o = 1'b1; else tests_failed_o = 1'b1; end else if (data_addr_i >= ADVTIMER_BASE && data_addr_i < ADVTIMER_BASE + ADVTIMER_LEN) begin end else if (data_addr_i >= EVENT_BASE && data_addr_i < EVENT_BASE + EVENT_LEN) begin end else if (data_addr_i >= TIMER_BASE && data_addr_i < TIMER_BASE + TIMER_LEN) begin end else if (data_addr_i >= HWPE_BASE && data_addr_i < HWPE_BASE + HWPE_LEN) begin end else if (data_addr_i >= STDOUT_BASE && data_addr_i < STDOUT_BASE + STDOUT_LEN) begin select_wdata_d = CORE; print_wdata = data_wdata_i; print_valid = '1; end else if (data_addr_i >= DEBUG_BASE && data_addr_i < DEBUG_BASE + DEBUG_LEN) begin select_wdata_d = CORE; dm_req = data_req_i; dm_addr = data_addr_i; dm_we = data_we_i; dm_be = data_be_i; dm_wdata = data_wdata_i; end else if ((data_addr_i >= SRAM_BASE && data_addr_i < SRAM_BASE + SRAM_LEN) || (data_addr_i >= 0 && data_addr_i < SRAM_LEN)) begin select_wdata_d = CORE; ram_data_req = data_req_i; ram_data_addr = data_addr_i[RAM_ADDR_WIDTH-1:0]; // just clip higher bits ram_data_wdata = data_wdata_i; ram_data_we = data_we_i; ram_data_be = data_be_i; end else begin end end else begin // handle reads if (data_addr_i >= ROM_BASE && data_addr_i < ROM_BASE + ROM_LEN) begin select_rdata_d = ROM; rom_req = data_req_i; rom_addr = data_addr_i - ROM_BASE; // TODO data_be_i end else if (data_addr_i >= FLL_BASE && data_addr_i < FLL_BASE + FLL_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= GPIO_BASE && data_addr_i < GPIO_BASE + GPIO_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= UDMA_BASE && data_addr_i < UDMA_BASE + UDMA_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= CNTRL_BASE && data_addr_i < CNTRL_BASE + CNTRL_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= ADVTIMER_BASE && data_addr_i < ADVTIMER_BASE + ADVTIMER_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= EVENT_BASE && data_addr_i < EVENT_BASE + EVENT_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= TIMER_BASE && data_addr_i < TIMER_BASE + TIMER_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= HWPE_BASE && data_addr_i < HWPE_BASE + HWPE_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= STDOUT_BASE && data_addr_i < STDOUT_BASE + STDOUT_LEN) begin select_rdata_d = UNMAP; end else if (data_addr_i >= DEBUG_BASE && data_addr_i < DEBUG_BASE + DEBUG_LEN) begin select_rdata_d = DEBUG; dm_req = data_req_i; dm_addr = data_addr_i; dm_we = data_we_i; dm_be = data_be_i; end else if ((data_addr_i >= SRAM_BASE && data_addr_i < SRAM_BASE + SRAM_LEN) || (data_addr_i >= 0 && data_addr_i < SRAM_LEN)) begin select_rdata_d = RAM; ram_data_req = data_req_i; ram_data_addr = data_addr_i[RAM_ADDR_WIDTH-1:0]; ram_data_we = data_we_i; ram_data_be = data_be_i; end else begin select_rdata_d = UNMAP; end end end else if (instr_req_i) begin instr_gnt_o = '1; instr_rvalid_d = '1; // handle reads if (instr_addr_i >= ROM_BASE && instr_addr_i < ROM_BASE + ROM_LEN) begin select_rdata_d = ROM; rom_req = instr_req_i; rom_addr = instr_addr_i - ROM_BASE - 32'h80; end else if (instr_addr_i >= FLL_BASE && instr_addr_i < FLL_BASE + FLL_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= GPIO_BASE && instr_addr_i < GPIO_BASE + GPIO_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= UDMA_BASE && instr_addr_i < UDMA_BASE + UDMA_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= CNTRL_BASE && instr_addr_i < CNTRL_BASE + CNTRL_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= ADVTIMER_BASE && instr_addr_i < ADVTIMER_BASE + ADVTIMER_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= EVENT_BASE && instr_addr_i < EVENT_BASE + EVENT_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= TIMER_BASE && instr_addr_i < TIMER_BASE + TIMER_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= HWPE_BASE && instr_addr_i < HWPE_BASE + HWPE_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= STDOUT_BASE && instr_addr_i < STDOUT_BASE + STDOUT_LEN) begin select_rdata_d = UNMAP; end else if (instr_addr_i >= DEBUG_BASE && instr_addr_i < DEBUG_BASE + DEBUG_LEN) begin select_rdata_d = DEBUG; dm_req = '1; dm_addr = instr_addr_i; dm_we = '0; dm_be = 4'b1111; end else if ((instr_addr_i >= SRAM_BASE && instr_addr_i < SRAM_BASE + SRAM_LEN) || (instr_addr_i >=0 && instr_addr_i < SRAM_LEN)) begin // handled separately select_rdata_d = RAM; end else begin select_rdata_d = UNMAP; end end end `ifndef VERILATOR // make sure we don't access any unmapped memory out_of_bounds_write: assert property (@(posedge clk_i) disable iff (!rst_ni) (data_req_i && data_gnt_o && data_we_i |-> (data_addr_i >= STDOUT_BASE && data_addr_i < STDOUT_BASE + STDOUT_LEN) || (data_addr_i >= DEBUG_BASE && data_addr_i < DEBUG_BASE + DEBUG_LEN) || (data_addr_i >= SRAM_BASE && data_addr_i < SRAM_BASE + SRAM_LEN) || (data_addr_i >= 0 && data_addr_i < SRAM_LEN))) else $error("out of bounds write to %08x with %08x", data_addr_i, data_wdata_i); out_of_bounds_read: assert property (@(posedge clk_i) disable iff (!rst_ni) (select_rdata_q != UNMAP)) else $error("out of bounds read"); `endif // make sure we select the proper read data always_comb begin: read_mux_sb_data_instr data_rdata_o = '0; sb_rdata_o = '0; instr_rdata_o = ram_instr_rdata; if(select_rdata_q == RAM) begin data_rdata_o = ram_data_rdata; sb_rdata_o = ram_data_rdata; end else if (select_rdata_q == DEBUG) begin data_rdata_o = dm_rdata; sb_rdata_o = dm_rdata; //TODO: not possible instr_rdata_o = dm_rdata; end else if (select_rdata_q == ROM) begin // either we got into a loop for jtag booting or we jumpt to the l2 // boot address (1c00_0080 === 0000_0080) to run a firmware directly if (JTAG_BOOT) begin data_rdata_o = 32'b00000000000000000000000001101111; //while(true) sb_rdata_o = 32'b00000000000000000000000001101111; instr_rdata_o = 32'b00000000000000000000000001101111; end else begin data_rdata_o = rom_rdata; //jal(5'b0, 21'h80); // jump to 0x0 + 0x80 sb_rdata_o = rom_rdata; //jal(5'b0, 21'h80); instr_rdata_o = rom_rdata; //jal(5'b0, 21'h80); end end else if (select_rdata_q == IDLE_READ) begin end end // print to stdout pseudo peripheral always_ff @(posedge clk_i, negedge rst_ni) begin: print_peripheral if(print_valid) begin if ($test$plusargs("verbose")) begin if (32 <= print_wdata && print_wdata < 128) $display("OUT: '%c'", print_wdata[7:0]); else $display("OUT: %3d", print_wdata); end else begin $write("%c", print_wdata[7:0]); `ifndef VERILATOR $fflush(); `endif end end end assign irq_id_o = TIMER_IRQ_ID; assign irq_o = irq_q; // Control timer. We need one to have some kind of timeout for tests that // get stuck in some loop. The riscv-tests also mandate that. Enable timer // interrupt by writing 1 to timer_irq_mask_q. Write initial value to // timer_cnt_q which gets counted down each cycle. When it transitions from // 1 to 0, and interrupt request (irq_q) is made (masked by timer_irq_mask_q). always_ff @(posedge clk_i, negedge rst_ni) begin: tb_timer if(~rst_ni) begin timer_irq_mask_q <= '0; timer_cnt_q <= '0; irq_q <= '0; end else begin // set timer irq mask if(timer_reg_valid) begin timer_irq_mask_q <= timer_wdata; // write timer value end else if(timer_val_valid) begin timer_cnt_q <= timer_wdata; end else begin if(timer_cnt_q > 0) timer_cnt_q <= timer_cnt_q - 1; if(timer_cnt_q == 1) irq_q <= 1'b1 && timer_irq_mask_q[TIMER_IRQ_ID]; if(irq_ack_i == 1'b1 && irq_id_i == TIMER_IRQ_ID) irq_q <= '0; end end end // show writes if requested always_ff @(posedge clk_i, negedge rst_ni) begin: verbose_writes if ($test$plusargs("verbose") && data_req_i && data_we_i) $display("write addr=0x%08x: data=0x%08x", data_addr_i, data_wdata_i); end // debug rom for booting directly to the firmware boot_rom boot_rom_i ( .clk_i ( clk_i ), .req_i ( rom_req ), .addr_i ( rom_addr ), .rdata_o( rom_rdata ) ); // instantiate the ram dp_ram #( .ADDR_WIDTH (RAM_ADDR_WIDTH), .INSTR_RDATA_WIDTH (INSTR_RDATA_WIDTH) ) dp_ram_i ( .clk_i ( clk_i ), .en_a_i ( ram_instr_req ), .addr_a_i ( ram_instr_addr[RAM_ADDR_WIDTH-1:0] ), .wdata_a_i ( '0 ), // Not writing so ignored .rdata_a_o ( ram_instr_rdata ), .we_a_i ( '0 ), .be_a_i ( 4'b1111 ), // Always want 32-bits .en_b_i ( ram_data_req ), .addr_b_i ( ram_data_addr ), .wdata_b_i ( ram_data_wdata ), .rdata_b_o ( ram_data_rdata ), .we_b_i ( ram_data_we ), .be_b_i ( ram_data_be ) ); // do the handshacking stuff by assuming we always react in one cycle assign dm_req_o = dm_req; assign dm_addr_o = dm_addr; assign dm_we_o = dm_we; assign dm_be_o = dm_be; assign dm_wdata_o = dm_wdata; assign dm_rdata = dm_rdata_i; assign dm_rvalid = dm_rvalid_i; // TODO: we dont' care about this assign dm_gnt = dm_gnt_i; // TODO: we don't care about this // sb and core rvalid assign data_rvalid_o = data_rvalid_q; assign sb_rvalid_o = sb_rvalid_q; assign instr_rvalid_o = instr_rvalid_q; always_ff @(posedge clk_i, negedge rst_ni) begin if (~rst_ni) begin select_rdata_q <= IDLE_READ; select_wdata_q <= IDLE_WRITE; data_rvalid_q <= '0; sb_rvalid_q <= '0; instr_rvalid_q <= '0; end else begin select_rdata_q <= select_rdata_d; select_wdata_q <= select_wdata_d; data_rvalid_q <= data_rvalid_d; sb_rvalid_q <= sb_rvalid_d; instr_rvalid_q <= instr_rvalid_d; end end endmodule // ram
Debug Unit plus RI5CY Testbench ===================== This testbench tests RI5CY together with a v0.13.1 compliant [debug unit](https://www.github.com/pulp-platform/riscv-dbg). There are several tests that can be run, but for now it is just `riscv test_compliance` of [riscv-openocd](https://www.github.com/riscv/riscv-openocd) (see in `pulpissimo.cfg`) and a not yet scripted run of gdb connecting to openocd, loading and running a hello world program (see `prog/test.c`). You need `riscv-openocd`. Running the testbench with vsim ---------------------- Point you environment variable `RISCV` to your RISC-V toolchain. Call `make vsim-run` to build the testbench and the program, and run it with vsim. Use `VSIM_FLAGS` to configure the simulator e.g. `make vsim-run VSIM_FLAGS="-gui -debugdb"`. Running the testbench with vcs ---------------------- Point you environment variable `RISCV` to your RISC-V toolchain. Call `make vcs-run`. Use `VCS_FLAGS` and `SIMV_FLAGS` to configure vcs e.g. `make vcs-run VCS_FLAGS="-debug_all"`. Running the testbench with [verilator](https://www.veripool.org/wiki/verilator) ---------------------- Point you environment variable `RISCV` to your RISC-V toolchain. Call `make veri-run`. Use `VERI_FLAGS` to configure verilator e.g. `make firmware-veri-run VERI_FLAGS="+firmware=path_to_firmware +vcd"` to use a custom firmware and dump to a vcd file. Options ---------------------- A few plusarg options are supported. * `+verbose` to show all memory read and writes and other miscellaneous information. * `+vcd` to produce a vcd file called `riscy_tb.vcd`. Verilator always produces a vcd file called `verilator_tb.vcd`. * `+firmware=path_to_firmware` to load a specific firmware. It is a bit tricky to build and link your own program. Look into the `prog` folder for an example. Example Run ----------------------- 1. `make veri-run` 3. (in new terminal) `export JTAG_VPI_PORT=port_name_from 1.` 2. (in new terminal) `openocd -f dm_compliance_test.cfg` 4. Now you can connect with gdb and interact with the testbench
// See LICENSE.SiFive for license details. //VCS coverage exclude_file import "DPI-C" function int jtag_tick ( input int port, output bit jtag_TCK, output bit jtag_TMS, output bit jtag_TDI, output bit jtag_TRSTn, input bit jtag_TDO ); module SimJTAG #( parameter TICK_DELAY = 50, parameter PORT = 0 )( input clock, input reset, input enable, input init_done, output jtag_TCK, output jtag_TMS, output jtag_TDI, output jtag_TRSTn, input jtag_TDO_data, input jtag_TDO_driven, output [31:0] exit ); reg [31:0] tickCounterReg; wire [31:0] tickCounterNxt; assign tickCounterNxt = (tickCounterReg == 0) ? TICK_DELAY : (tickCounterReg - 1); bit r_reset; wire [31:0] random_bits = $random; wire #0.1 __jtag_TDO = jtag_TDO_driven ? jtag_TDO_data : random_bits[0]; bit __jtag_TCK; bit __jtag_TMS; bit __jtag_TDI; bit __jtag_TRSTn; int __exit; reg init_done_sticky; assign #0.1 jtag_TCK = __jtag_TCK; assign #0.1 jtag_TMS = __jtag_TMS; assign #0.1 jtag_TDI = __jtag_TDI; assign #0.1 jtag_TRSTn = __jtag_TRSTn; assign #0.1 exit = __exit; always @(posedge clock) begin r_reset <= reset; if (reset || r_reset) begin __exit = 0; tickCounterReg <= TICK_DELAY; init_done_sticky <= 1'b0; end else begin init_done_sticky <= init_done | init_done_sticky; if (enable && init_done_sticky) begin tickCounterReg <= tickCounterNxt; if (tickCounterReg == 0) begin __exit = jtag_tick(PORT, __jtag_TCK, __jtag_TMS, __jtag_TDI, __jtag_TRSTn, __jtag_TDO); end end // if (enable && init_done_sticky) end // else: !if(reset || r_reset) end // always @ (posedge clock) endmodule
// Copyright 2020 ETH Zurich and University of Bologna. // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // Wrapper for a RI5CY testbench, containing RI5CY, Memory and stdout peripheral // Contributor: Robert Balas <[email protected]> module tb_test_env #( parameter int unsigned INSTR_RDATA_WIDTH = 32, parameter int unsigned RAM_ADDR_WIDTH = 20, parameter logic [31:0] BOOT_ADDR = 'h80, parameter bit JTAG_BOOT = 1, parameter int unsigned OPENOCD_PORT = 0, parameter bit A_EXTENSION = 0 ) ( input logic clk_i, input logic rst_ni, // currently we are not making use of those signals input logic fetch_enable_i, output logic tests_passed_o, output logic tests_failed_o); // defs from pulpissimo // localparam CLUSTER_ID = 6'd31; // localparam CORE_ID = 4'd0; // test defs localparam CLUSTER_ID = 6'd0; localparam CORE_ID = 4'd0; localparam CORE_MHARTID = {21'b0, CLUSTER_ID, 1'b0, CORE_ID}; localparam NrHarts = 1; localparam logic [NrHarts-1:0] SELECTABLE_HARTS = 1 << CORE_MHARTID; localparam HARTINFO = {8'h0, 4'h2, 3'b0, 1'b1, dm::DataCount, dm::DataAddr}; // signals connecting core to memory logic instr_req; logic instr_gnt; logic instr_rvalid; logic [31:0] instr_addr; logic [INSTR_RDATA_WIDTH-1:0] instr_rdata; logic data_req; logic data_gnt; logic data_rvalid; logic [31:0] data_addr; logic data_we; logic [3:0] data_be; logic [31:0] data_rdata; logic [31:0] data_wdata; // jtag openocd bridge signals logic sim_jtag_tck; logic sim_jtag_tms; logic sim_jtag_tdi; logic sim_jtag_trstn; logic sim_jtag_tdo; logic [31:0] sim_jtag_exit; logic sim_jtag_enable; // signals for debug unit logic debug_req_ready; dm::dmi_resp_t debug_resp; logic jtag_req_valid; dm::dmi_req_t jtag_dmi_req; logic jtag_resp_ready; logic jtag_resp_valid; logic [NrHarts-1:0] dm_debug_req; logic ndmreset, ndmreset_n; // debug unit slave interface logic dm_grant; logic dm_rvalid; logic dm_req; logic dm_we; logic [31:0] dm_addr; logic [31:0] dm_wdata; logic [31:0] dm_rdata; logic [3:0] dm_be; // debug unit master interface (system bus access) logic sb_req; logic [31:0] sb_addr; logic sb_we; logic [31:0] sb_wdata; logic [3:0] sb_be; logic sb_gnt; logic sb_rvalid; logic [31:0] sb_rdata; // irq signals (not used) logic irq; logic [0:4] irq_id_in; logic irq_ack; logic [0:4] irq_id_out; // make jtag bridge work assign sim_jtag_enable = JTAG_BOOT; // instantiate the core cv32e40p_core #( .PULP_XPULP ( 0 ), .PULP_CLUSTER ( 0 ), .FPU ( 0 ), .PULP_ZFINX ( 0 ), .NUM_MHPMCOUNTERS ( 1 ) ) riscv_core_i ( .clk_i ( clk_i ), .rst_ni ( ndmreset_n ), .pulp_clock_en_i ( '1 ), .scan_cg_en_i ( '0 ), .boot_addr_i ( BOOT_ADDR ), .mtvec_addr_i ( 32'h00000000 ), .dm_halt_addr_i ( 32'h1A110800 ), .hart_id_i ( CORE_MHARTID ), .dm_exception_addr_i ( 32'h00000000 ), .instr_addr_o ( instr_addr ), .instr_req_o ( instr_req ), .instr_rdata_i ( instr_rdata ), .instr_gnt_i ( instr_gnt ), .instr_rvalid_i ( instr_rvalid ), .data_addr_o ( data_addr ), .data_wdata_o ( data_wdata ), .data_we_o ( data_we ), .data_req_o ( data_req ), .data_be_o ( data_be ), .data_rdata_i ( data_rdata ), .data_gnt_i ( data_gnt ), .data_rvalid_i ( data_rvalid ), .apu_master_req_o ( ), .apu_master_ready_o ( ), .apu_master_gnt_i ( ), .apu_master_operands_o ( ), .apu_master_op_o ( ), .apu_master_type_o ( ), .apu_master_flags_o ( ), .apu_master_valid_i ( ), .apu_master_result_i ( ), .apu_master_flags_i ( ), .irq_i ( 32'b0 ), .irq_ack_o ( irq_ack ), .irq_id_o ( irq_id_out ), .debug_req_i ( dm_debug_req[CORE_MHARTID] ), .fetch_enable_i ( fetch_enable_i ), .core_sleep_o ( core_sleep_o ) ); // this handles read to RAM and memory mapped pseudo peripherals mm_ram #( .RAM_ADDR_WIDTH (RAM_ADDR_WIDTH), .INSTR_RDATA_WIDTH (INSTR_RDATA_WIDTH), .JTAG_BOOT(JTAG_BOOT) ) mm_ram_i ( .clk_i ( clk_i ), .rst_ni ( ndmreset_n ), // core instruction access .instr_req_i ( instr_req ), .instr_addr_i ( instr_addr ), .instr_rdata_o ( instr_rdata ), .instr_rvalid_o ( instr_rvalid ), .instr_gnt_o ( instr_gnt ), // core data access .data_req_i ( data_req ), .data_addr_i ( data_addr ), .data_we_i ( data_we ), .data_be_i ( data_be ), .data_wdata_i ( data_wdata ), .data_rdata_o ( data_rdata ), .data_rvalid_o ( data_rvalid ), .data_gnt_o ( data_gnt ), // system bus access from debug unit .sb_req_i ( sb_req ), .sb_addr_i ( sb_addr ), .sb_we_i ( sb_we ), .sb_be_i ( sb_be ), .sb_wdata_i ( sb_wdata ), .sb_rdata_o ( sb_rdata ), .sb_rvalid_o ( sb_rvalid ), .sb_gnt_o ( sb_gnt ), // access to debug unit .dm_req_o ( dm_req ), .dm_addr_o ( dm_addr ), .dm_we_o ( dm_we ), .dm_be_o ( dm_be ), .dm_wdata_o ( dm_wdata ), .dm_rdata_i ( dm_rdata ), .dm_rvalid_i ( dm_rvalid ), .dm_gnt_i ( dm_gnt ), .irq_id_i ( irq_id_out ), .irq_ack_i ( irq_ack ), .irq_id_o ( irq_id_in ), .irq_o ( irq ), .tests_passed_o ( tests_passed_o ), .tests_failed_o ( tests_failed_o ) ); // debug subsystem dmi_jtag #( .IdcodeValue ( 32'h249511C3 ) ) i_dmi_jtag ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .testmode_i ( 1'b0 ), .dmi_req_o ( jtag_dmi_req ), .dmi_req_valid_o ( jtag_req_valid ), .dmi_req_ready_i ( debug_req_ready ), .dmi_resp_i ( debug_resp ), .dmi_resp_ready_o ( jtag_resp_ready ), .dmi_resp_valid_i ( jtag_resp_valid ), .dmi_rst_no ( ), // not connected .tck_i ( sim_jtag_tck ), .tms_i ( sim_jtag_tms ), .trst_ni ( sim_jtag_trstn ), .td_i ( sim_jtag_tdi ), .td_o ( sim_jtag_tdo ), .tdo_oe_o ( ) ); dm_top #( .NrHarts ( NrHarts ), .BusWidth ( 32 ), .SelectableHarts ( SELECTABLE_HARTS ) ) i_dm_top ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .testmode_i ( 1'b0 ), .ndmreset_o ( ndmreset ), .dmactive_o ( ), // active debug session TODO .debug_req_o ( dm_debug_req ), .unavailable_i ( ~SELECTABLE_HARTS ), .hartinfo_i ( HARTINFO ), .slave_req_i ( dm_req ), .slave_we_i ( dm_we ), .slave_addr_i ( dm_addr ), .slave_be_i ( dm_be ), .slave_wdata_i ( dm_wdata ), .slave_rdata_o ( dm_rdata ), .master_req_o ( sb_req ), .master_add_o ( sb_addr ), .master_we_o ( sb_we ), .master_wdata_o ( sb_wdata ), .master_be_o ( sb_be ), .master_gnt_i ( sb_gnt ), .master_r_valid_i ( sb_rvalid ), .master_r_rdata_i ( sb_rdata ), .dmi_rst_ni ( rst_ni ), .dmi_req_valid_i ( jtag_req_valid ), .dmi_req_ready_o ( debug_req_ready ), .dmi_req_i ( jtag_dmi_req ), .dmi_resp_valid_o ( jtag_resp_valid ), .dmi_resp_ready_i ( jtag_resp_ready ), .dmi_resp_o ( debug_resp ) ); /////////////////////////////////////////////////////// // Bind RTL assertions to Debug Module /////////////////////////////////////////////////////// bind dm_top dm_top_sva #( .NrHarts ( NrHarts ), .BusWidth ( BusWidth ), .SelectableHarts ( SelectableHarts )) i_dm_top_sva (.*); bind dm_csrs dm_csrs_sva #( .NrHarts ( NrHarts ), .BusWidth ( BusWidth ), .SelectableHarts ( SelectableHarts )) i_dm_csrs_sva (.*); bind dm_sba dm_sba_sva #( .BusWidth ( BusWidth ), .ReadByteEnable ( ReadByteEnable )) i_dm_sba_sva (.*); // grant in the same cycle assign dm_gnt = dm_req; // valid read/write in the next cycle always_ff @(posedge clk_i or negedge rst_ni) begin : dm_valid_handler if(~rst_ni) begin dm_rvalid <= '0; end else begin dm_rvalid <= dm_gnt; end end // reset handling with ndmreset rstgen i_rstgen_main ( .clk_i ( clk_i ), .rst_ni ( rst_ni & (~ndmreset) ), .test_mode_i ( '0 ), .rst_no ( ndmreset_n ), .init_no ( ) // keep open ); // jtag calls from dpi SimJTAG #( .TICK_DELAY (1), .PORT(OPENOCD_PORT) ) i_sim_jtag ( .clock ( clk_i ), .reset ( ~rst_ni ), .enable ( sim_jtag_enable ), .init_done ( rst_ni ), .jtag_TCK ( sim_jtag_tck ), .jtag_TMS ( sim_jtag_tms ), .jtag_TDI ( sim_jtag_tdi ), .jtag_TRSTn ( sim_jtag_trstn ), .jtag_TDO_data ( sim_jtag_tdo ), .jtag_TDO_driven ( 1'b1 ), .exit ( sim_jtag_exit ) ); always_comb begin : jtag_exit_handler if (sim_jtag_exit) $finish(2); // print stats too end endmodule // tb_test_env
// Copyright 2017 Embecosm Limited <www.embecosm.com> // Copyright 2018 Robert Balas <[email protected]> // Copyright 2020 ETH Zurich and University of Bologna. // Copyright and related rights are licensed under the Solderpad Hardware // License, Version 0.51 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://solderpad.org/licenses/SHL-0.51. Unless required by applicable law // or agreed to in writing, software, hardware and materials distributed under // this License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // Top level wrapper for a RI5CY testbench // Contributor: Robert Balas <[email protected]> // Jeremy Bennett <[email protected]> module tb_top #( parameter int unsigned INSTR_RDATA_WIDTH = 32, parameter int unsigned RAM_ADDR_WIDTH = 22, parameter logic [31:0] BOOT_ADDR = 'h1A00_0180, parameter bit JTAG_BOOT = 1, parameter int unsigned OPENOCD_PORT = 9999 ); // comment to record execution trace //`define TRACE_EXECUTION const time CLK_PHASE_HI = 5ns; const time CLK_PHASE_LO = 5ns; const time CLK_PERIOD = CLK_PHASE_HI + CLK_PHASE_LO; const time STIM_APPLICATION_DEL = CLK_PERIOD * 0.1; const time RESP_ACQUISITION_DEL = CLK_PERIOD * 0.9; const time RESET_DEL = STIM_APPLICATION_DEL; const int RESET_WAIT_CYCLES = 4; // clock and reset for tb logic clk = 'b1; logic rst_n = 'b0; // testbench result logic tests_passed; logic tests_failed; // signals for ri5cy logic fetch_enable; // make the core start fetching instruction immediately assign fetch_enable = '1; // allow vcd dump initial begin: dump_vars if ($test$plusargs("vcd")) begin $dumpfile("riscy_tb.vcd"); $dumpvars(0, tb_top); end `ifdef QUESTA if ($test$plusargs("wlfdump")) begin $wlfdumpvars(0, tb_top); end `endif end // we either load the provided firmware or execute a small test program that // doesn't do more than an infinite loop with some I/O initial begin: load_prog automatic logic [1023:0] firmware; automatic int prog_size = 6; if($value$plusargs("firmware=%s", firmware)) begin if($test$plusargs("verbose")) $display("[TESTBENCH] %t: loading firmware %0s ...", $time, firmware); $readmemh(firmware, tb_test_env_i.mm_ram_i.dp_ram_i.mem); end else begin $display("No firmware specified"); end end // clock generation initial begin: clock_gen forever begin #CLK_PHASE_HI clk = 1'b0; #CLK_PHASE_LO clk = 1'b1; end end: clock_gen // reset generation initial begin: reset_gen rst_n = 1'b0; // wait a few cycles repeat (RESET_WAIT_CYCLES) begin @(posedge clk); //TODO: was posedge, see below end // start running #RESET_DEL rst_n = 1'b1; if($test$plusargs("verbose")) $display("reset deasserted", $time); end: reset_gen // set timing format initial begin: timing_format $timeformat(-9, 0, "ns", 9); end: timing_format // check if we succeded always_ff @(posedge clk, negedge rst_n) begin if (tests_passed) begin $display("Exit Success"); $finish; end if (tests_failed) begin $display("Exit FAILURE"); $finish; end end // wrapper for riscv, the memory system and stdout peripheral tb_test_env #( .INSTR_RDATA_WIDTH (INSTR_RDATA_WIDTH), .RAM_ADDR_WIDTH (RAM_ADDR_WIDTH), .BOOT_ADDR (BOOT_ADDR), .JTAG_BOOT (JTAG_BOOT), .OPENOCD_PORT (OPENOCD_PORT) ) tb_test_env_i( .clk_i ( clk ), .rst_ni ( rst_n ), .fetch_enable_i ( fetch_enable ), .tests_passed_o ( tests_passed ), .tests_failed_o ( tests_failed ) ); endmodule // tb_top