Search is not available for this dataset
content
stringlengths
0
376M
// Copyright 2016 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. /** * Clock and Reset Generator * * This module generates a single-phase clock and an active-low reset signal for a simulation * testbench. * * Parameter Description: * CLK_LOW_TIME Duration of the phase in which the clock is low. * CLK_HIGH_TIME Duration of the phase in which the clock is high. * RST_TIME Interval at the beginning of the simulation during which the reset is active. * * Port Description: * EndOfSim_SI Stops the simulation clock in the next period. * Clk_CO Single-phase clock. * Rst_RBO Active-low reset. */ //timeunit 1ns; module ClkRstGen // Parameters {{{ #( parameter CLK_LOW_TIME = 5ns, parameter CLK_HIGH_TIME = 5ns, parameter RST_TIME = 100ns ) // }}} // Ports {{{ ( input logic EndOfSim_SI, output logic Clk_CO, output logic Rst_RBO ); // }}} // Module-Wide Constants {{{ localparam time CLK_PERIOD = CLK_LOW_TIME + CLK_HIGH_TIME; // }}} // Clock Generation {{{ always begin Clk_CO = 0; if (Rst_RBO) begin // Reset is inactive. if (~EndOfSim_SI) begin Clk_CO = 1; #CLK_HIGH_TIME; Clk_CO = 0; #CLK_LOW_TIME; end else begin $stop(0); end end else begin // Reset is still active, wait until the next clock period. #CLK_PERIOD; end end // }}} // Reset Generation {{{ initial begin Rst_RBO = 0; #RST_TIME; Rst_RBO = 1; end // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
#!/usr/bin/env bash set -e readonly CI_DIR="$( cd $(dirname $0) ; pwd -P )" readonly ROOT_DIR="$( cd ${CI_DIR}/.. ; pwd -P )" readonly BEHAV_DIR="${ROOT_DIR}/behav" cd ${CI_DIR} git clone git@iis-git.ee.ethz.ch:pulp-platform/big.pulp.git -b master > /dev/null readonly BIGPULP_DIR="${CI_DIR}/big.pulp" export CF_MATH_PKG_PATH="${BIGPULP_DIR}/fe/ips/pkg/cfmath" cd ${BEHAV_DIR} make
// Copyright 2016 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. /** * AXI BRAM Logger * * Module that logs AXI accesses with timestamps. This module is built on top of `BramLogger`, and * all ports that are not the logged AXI inputs are documented there, along with other properties. * * Log Format: * - first word: 32-bit timestamp * - second word: lowest `AXI_LEN_BITW` bits: AxiLen_DI * all following bits: AxiId_DI * - third word (and fourth word for 64-bit addresses): AxiAddr_DI * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ import CfMath::ceil_div; module AxiBramLogger // Parameters {{{ #( // Width (in bits) of the logged AXI ID. Value must be in [1, 24]. parameter AXI_ID_BITW = 8, // Width (in bits) of the logged AXI address. Value must be either 32 or 64. parameter AXI_ADDR_BITW = 32, // Number of entries in the log. Value must be >= 1024, should be a multiple of 1024, and is // upper-bound by the available memory. parameter NUM_LOG_ENTRIES = 16384, // The following "parameters" must not be changed from their given value. They are solely // declared here because they define the width of some of the ports. parameter AXI_LEN_BITW = 8 ) // }}} // Ports {{{ ( input logic Clk_CI, input logic TimestampClk_CI, input logic Rst_RBI, // AXI Input input logic AxiValid_SI, input logic AxiReady_SI, input logic [AXI_ID_BITW -1:0] AxiId_DI, input logic [AXI_ADDR_BITW-1:0] AxiAddr_DI, input logic [AXI_LEN_BITW -1:0] AxiLen_DI, // Control Input input logic Clear_SI, input logic LogEn_SI, // Status Output output logic Full_SO, output logic Ready_SO, // Interface to Internal BRAM BramPort.Slave Bram_PS ); // }}} // Module-Wide Constants {{{ // Properties of the data entries in the log localparam integer META_BITW = ceil_div(AXI_LEN_BITW+AXI_ID_BITW, 32) * 32; localparam integer LOGGING_DATA_BITW = ceil_div(META_BITW+AXI_ADDR_BITW, 32) * 32; localparam integer AXI_LEN_LOW = 0; localparam integer AXI_LEN_HIGH = AXI_LEN_LOW + AXI_LEN_BITW - 1; localparam integer AXI_ID_LOW = AXI_LEN_HIGH + 1; localparam integer AXI_ID_HIGH = AXI_ID_LOW + AXI_ID_BITW - 1; localparam integer AXI_ADDR_LOW = META_BITW; localparam integer AXI_ADDR_HIGH = AXI_ADDR_LOW + AXI_ADDR_BITW - 1; // }}} // BRAM Logger Instantiation {{{ logic LogTrigger_S; assign LogTrigger_S = AxiValid_SI && AxiReady_SI; logic [LOGGING_DATA_BITW-1:0] LogData_D; always_comb begin LogData_D = '0; LogData_D[ AXI_LEN_HIGH: AXI_LEN_LOW] = AxiLen_DI; LogData_D[ AXI_ID_HIGH: AXI_ID_LOW] = AxiId_DI; LogData_D[AXI_ADDR_HIGH:AXI_ADDR_LOW] = AxiAddr_DI; end BramLogger #( .LOG_DATA_BITW (LOGGING_DATA_BITW), .NUM_LOG_ENTRIES (NUM_LOG_ENTRIES) ) bramLogger ( .Clk_CI (Clk_CI), .TimestampClk_CI (TimestampClk_CI), .Rst_RBI (Rst_RBI), .LogData_DI (LogData_D), .LogTrigger_SI (LogTrigger_S), .Clear_SI (Clear_SI), .LogEn_SI (LogEn_SI), .Full_SO (Full_SO), .Ready_SO (Ready_SO), .Bram_PS (Bram_PS) ); // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
// Copyright 2016 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. /** * AXI to AXI Lite Protocol Converter * * This module converts from AXI4 to AXI4 Lite by performing a simple ID reflection. It does not * buffer multiple outstanding transactions; instead, a transaction is only accepted from the AXI * master after the previous transaction has been completed by the AXI Lite slave. * * This module does NOT support bursts, because AXI Lite itself does not support bursts and * converting AXI4 bursts into separate AXI Lite transactions is fairly involved (different burst * types, alignment, etc.). If a burst is requested at the AXI4 slave interface, a slave error is * returned and an assertion fails. * * For compatibility with Xilinx AXI Lite slaves, the AW and W channels are applied simultaneously * at the output. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ module AxiToAxiLitePc // Parameters {{{ #( parameter AXI_ADDR_WIDTH = 32, parameter AXI_ID_WIDTH = 10 ) // }}} // Ports {{{ ( input logic Clk_CI, input logic Rst_RBI, AXI_BUS.Slave Axi_PS, AXI_LITE.Master AxiLite_PM ); // }}} // Signal Declarations {{{ logic [AXI_ID_WIDTH-1:0] ArId_DN, ArId_DP; logic [AXI_ADDR_WIDTH-1:0] AwAddr_DN, AwAddr_DP; logic [AXI_ID_WIDTH-1:0] AwId_DN, AwId_DP; logic AwValid_DN, AwValid_DP; enum logic [1:0] {RREADY, READ, RERR} StateRead_SP, StateRead_SN; enum logic [2:0] {WREADY, WRITE, WAITAWREADY, WAITWREADY, WRESP, WERRBEATS, WERRRESP} StateWrite_SP, StateWrite_SN; // }}} // FSM to Control Handshaking Outputs for Write Channel and AW Latching. {{{ always_comb begin // Default Assignments AwAddr_DN = AwAddr_DP; AwId_DN = AwId_DP; Axi_PS.aw_ready = 1'b0; Axi_PS.w_ready = 1'b0; Axi_PS.b_resp = 2'b00; Axi_PS.b_valid = 1'b0; AxiLite_PM.aw_valid = 1'b0; AxiLite_PM.w_valid = 1'b0; AxiLite_PM.b_ready = 1'b0; StateWrite_SN = StateWrite_SP; case (StateWrite_SP) WREADY: begin // Wait for aw_valid, latch address on encountering. if (Axi_PS.aw_valid) begin Axi_PS.aw_ready = 1'b1; AwId_DN = Axi_PS.aw_id; if (Axi_PS.aw_len != '0) begin // Burst length longer than 1 transfer, StateWrite_SN = WERRBEATS; // which is not supported. end else begin AwAddr_DN = Axi_PS.aw_addr; StateWrite_SN = WRITE; end end end WRITE: begin // Wait for w_valid, forward address and data on encountering. if (Axi_PS.w_valid) begin AxiLite_PM.aw_valid = 1'b1; AxiLite_PM.w_valid = 1'b1; if (AxiLite_PM.w_ready && AxiLite_PM.aw_ready) begin // Both AW and W channels fire. Axi_PS.w_ready = 1'b1; StateWrite_SN = WRESP; end else if (AxiLite_PM.w_ready) begin // Only the W channel fires, the AW channel waits. Axi_PS.w_ready = 1'b1; StateWrite_SN = WAITAWREADY; end else if (AxiLite_PM.aw_ready) begin // Only the AW channel fires, the W channel waits. StateWrite_SN = WAITWREADY; end end end WAITAWREADY: begin // Wait for AW channel (the W channel already fired). AxiLite_PM.aw_valid = 1'b1; if (AxiLite_PM.aw_ready) begin StateWrite_SN = WRESP; end end WAITWREADY: begin // Wait for W channel (the AW channel already fired). AxiLite_PM.w_valid = 1'b1; if (AxiLite_PM.w_ready) begin StateWrite_SN = WRESP; end end // Connect B channel handshake signals and wait for it to fire before accepting the next // transaction. WRESP: begin AxiLite_PM.b_ready = Axi_PS.b_ready; Axi_PS.b_valid = AxiLite_PM.b_valid; Axi_PS.b_resp = AxiLite_PM.b_resp; if (Axi_PS.b_ready && AxiLite_PM.b_valid) begin StateWrite_SN = WREADY; end end // Absorb write beats of the unsupported burst. WERRBEATS: begin Axi_PS.w_ready = 1'b1; if (Axi_PS.w_valid && Axi_PS.w_last) begin StateWrite_SN = WERRRESP; end end // Signal Slave Error on the B channel. WERRRESP: begin Axi_PS.b_resp = 2'b10; // SLVERR Axi_PS.b_valid = 1'b1; if (Axi_PS.b_ready) begin StateWrite_SN = WREADY; end end default: begin StateWrite_SN = WREADY; end endcase end // }}} // FSM to Control Handshaking Outputs for Read Channel and AR ID Latching. {{{ always_comb begin // Default Assignments ArId_DN = ArId_DP; Axi_PS.ar_ready = 1'b0; Axi_PS.r_resp = 2'b00; Axi_PS.r_last = 1'b0; Axi_PS.r_valid = 1'b0; AxiLite_PM.ar_valid = 1'b0; StateRead_SN = StateRead_SP; case (StateRead_SP) RREADY: begin // Wait for ar_valid, latch ID on encountering. if (Axi_PS.ar_valid) begin if (Axi_PS.ar_len != '0) begin // Burst length longer than 1 transfer, StateRead_SN = RERR; // which is not supported. ArId_DN = Axi_PS.ar_id; Axi_PS.ar_ready = 1'b1; end else begin AxiLite_PM.ar_valid = Axi_PS.ar_valid; if (AxiLite_PM.ar_ready) begin Axi_PS.ar_ready = 1'b1; ArId_DN = Axi_PS.ar_id; StateRead_SN = READ; end end end end READ: begin // Wait for r_valid, forward on encountering. if (AxiLite_PM.r_valid) begin Axi_PS.r_resp = AxiLite_PM.r_resp; Axi_PS.r_last = 1'b1; Axi_PS.r_valid = 1'b1; if (Axi_PS.r_ready) begin StateRead_SN = RREADY; end end end RERR: begin Axi_PS.r_resp = 2'b10; // SLVERR Axi_PS.r_last = 1'b1; Axi_PS.r_valid = 1'b1; if (Axi_PS.r_ready) begin StateRead_SN = RREADY; end end default: begin StateRead_SN = RREADY; end endcase end // }}} // Drive outputs of AXI Lite interface. {{{ assign AxiLite_PM.aw_addr = AwAddr_DP; assign AxiLite_PM.w_data = Axi_PS.w_data; assign AxiLite_PM.w_strb = Axi_PS.w_strb; assign AxiLite_PM.ar_addr = Axi_PS.ar_addr; assign AxiLite_PM.r_ready = Axi_PS.r_ready; // }}} // Drive outputs of AXI interface. {{{ assign Axi_PS.r_data = AxiLite_PM.r_data; assign Axi_PS.r_id = ArId_DP; assign Axi_PS.r_user = 'b0; assign Axi_PS.b_id = AwId_DP; assign Axi_PS.b_user = 'b0; // }}} // Flip-Flops {{{ always_ff @ (posedge Clk_CI) begin ArId_DP <= 'b0; AwAddr_DP <= 'b0; AwId_DP <= 'b0; AwValid_DP <= 'b0; StateRead_SP <= RREADY; StateWrite_SP <= WREADY; if (Rst_RBI) begin ArId_DP <= ArId_DN; AwAddr_DP <= AwAddr_DN; AwId_DP <= AwId_DN; AwValid_DP <= AwValid_DN; StateRead_SP <= StateRead_SN; StateWrite_SP <= StateWrite_SN; end end // }}} // Interface Assertions {{{ always @(posedge Clk_CI) begin if (Rst_RBI) begin assert (!(Axi_PS.aw_valid && Axi_PS.aw_len != '0)) else $error("Unsupported burst on AW channel!"); assert (!(Axi_PS.ar_valid && Axi_PS.ar_len != '0)) else $error("Unsupported burst on AR channel!"); end end // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
// Copyright 2016 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. /** * BRAM Data Width Converter * * This module performs data width conversion between a narrow master and a wide slave interface. * * Port Description: * FromMaster_PS Slave BRAM Port interface through which master control signals go to the BRAM. * ToSlave_PM Master BRAM Port interface at which the slave BRAM is connected. * * The data signal of the master interface must be narrower than that of the slave interface. The * reverse situation would require handshaking and buffering and is not supported by the simple BRAM * Port interface. * * Parameter Description: * ADDR_BITW The width (in bits) of the address signals. Both ports must have the same * address width. * MST_DATA_BITW The width (in bits) of the data signal coming from the master controller. * SLV_DATA_BITW The width (in bits) of the data signal of the slave BRAM. * * The value of all parameters must match the connected interfaces. DO NOT rely on the default * values for these parameters, but explicitly set the parameters so that they are correct for your * setup! If one or more values do not match, the behavior of this module is undefined. * * Compatibility Information: * ModelSim >= 10.0b * Vivado >= 2016.1 * * Earlier versions of the tools are either untested or known to fail for this module. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ import CfMath::ceil_div, CfMath::log2; module BramDwc // Parameters {{{ #( parameter integer ADDR_BITW = 32, parameter integer MST_DATA_BITW = 32, parameter integer SLV_DATA_BITW = 96 ) // }}} // Ports {{{ ( BramPort.Slave FromMaster_PS, BramPort.Master ToSlave_PM ); // }}} // Module-Wide Constants {{{ localparam integer MST_DATA_BYTEW = MST_DATA_BITW/8; localparam integer MST_ADDR_WORD_BITO = log2(MST_DATA_BYTEW); localparam integer MST_ADDR_WORD_BITW = ADDR_BITW - MST_ADDR_WORD_BITO; localparam integer SLV_DATA_BYTEW = SLV_DATA_BITW/8; localparam integer SLV_ADDR_WORD_BITO = log2(SLV_DATA_BYTEW); localparam integer SLV_ADDR_WORD_BITW = ADDR_BITW - SLV_ADDR_WORD_BITO; localparam integer PAR_IDX_MAX_VAL = ceil_div(SLV_DATA_BITW, MST_DATA_BITW) - 1; localparam integer PAR_IDX_BITW = log2(PAR_IDX_MAX_VAL+1); // }}} // Initial Assertions {{{ initial begin assert (SLV_DATA_BITW >= MST_DATA_BITW) else $fatal(1, "Downconversion of the data bitwidth from master to slave is not possible!"); assert (MST_DATA_BITW == FromMaster_PS.DATA_BITW) else $fatal(1, "Parameter for data width of master does not match connected interface!"); assert (SLV_DATA_BITW == ToSlave_PM.DATA_BITW) else $fatal(1, "Parameter for data width of slave does not match connected interface!"); assert ((ADDR_BITW == FromMaster_PS.ADDR_BITW) && (ADDR_BITW == ToSlave_PM.ADDR_BITW)) else $fatal(1, "Parameter for address width does not match connected interfaces!"); end // }}} // Register the Addr_S of master interface to make sure the address stays // stable for word selection on reads logic [ADDR_BITW-1:0] Addr_SN, Addr_SP; assign Addr_SN = FromMaster_PS.Addr_S; always_ff @ (posedge FromMaster_PS.Clk_C) begin if (FromMaster_PS.Rst_R == 1'b1) begin Addr_SP <= 'b0; end else if (FromMaster_PS.En_S == 1'b1) begin Addr_SP <= Addr_SN; end end // Pass clock, reset, and enable through. {{{ assign ToSlave_PM.Clk_C = FromMaster_PS.Clk_C; assign ToSlave_PM.Rst_R = FromMaster_PS.Rst_R; assign ToSlave_PM.En_S = FromMaster_PS.En_S; // }}} // Data Width Conversion {{{ logic [MST_ADDR_WORD_BITW-1:0] MstWordAddr_S, MstWordAddrReg_S; assign MstWordAddr_S = Addr_SN[(MST_ADDR_WORD_BITW-1)+MST_ADDR_WORD_BITO:MST_ADDR_WORD_BITO]; assign MstWordAddrReg_S = Addr_SP[(MST_ADDR_WORD_BITW-1)+MST_ADDR_WORD_BITO:MST_ADDR_WORD_BITO]; logic [SLV_ADDR_WORD_BITW-1:0] ToWordAddr_S; assign ToWordAddr_S = MstWordAddr_S / (PAR_IDX_MAX_VAL+1); always_comb begin ToSlave_PM.Addr_S = '0; ToSlave_PM.Addr_S[(SLV_ADDR_WORD_BITW-1)+SLV_ADDR_WORD_BITO:SLV_ADDR_WORD_BITO] = ToWordAddr_S; end logic [PAR_IDX_BITW-1:0] ParIdxRd_S, ParIdxWr_S; assign ParIdxWr_S = MstWordAddr_S % (PAR_IDX_MAX_VAL+1); assign ParIdxRd_S = MstWordAddrReg_S % (PAR_IDX_MAX_VAL+1); // based on address applied with En_S logic [PAR_IDX_MAX_VAL:0] [MST_DATA_BITW-1:0] Rd_D; genvar p; for (p = 0; p <= PAR_IDX_MAX_VAL; p++) begin localparam integer SLV_BYTE_LOW = MST_DATA_BYTEW*p; localparam integer SLV_BYTE_HIGH = SLV_BYTE_LOW + (MST_DATA_BYTEW-1); localparam integer SLV_BIT_LOW = MST_DATA_BITW*p; localparam integer SLV_BIT_HIGH = SLV_BIT_LOW + (MST_DATA_BITW-1); always_comb begin if (ParIdxWr_S == p) begin ToSlave_PM.WrEn_S[SLV_BYTE_HIGH:SLV_BYTE_LOW] = FromMaster_PS.WrEn_S; end else begin ToSlave_PM.WrEn_S[SLV_BYTE_HIGH:SLV_BYTE_LOW] = '0; end end assign Rd_D[p] = ToSlave_PM.Rd_D[SLV_BIT_HIGH:SLV_BIT_LOW]; assign ToSlave_PM.Wr_D[SLV_BIT_HIGH:SLV_BIT_LOW] = FromMaster_PS.Wr_D; end assign FromMaster_PS.Rd_D = Rd_D[ParIdxRd_S]; // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
// Copyright 2016 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. /** * BRAM Logger * * Module that logs timestamped events on a user-defined synchronous trigger and with user-defined * meta data to a BRAM array. * * Port Description: * * Clk_CI All logging and control operations are synchronous to this clock. * TimestampClk_CI The timestamp counter is synchronous to this clock. * Rst_RBI Synchronous active-low reset for control logic and registers. Does NOT reset * the cells of the internal BRAM. * * LogData_DI Meta data to be stored for each event. * LogTrigger_SI If this signal is high during a rising edge of `Clk_CI` (and the logger is * enabled), a log entry is added. * * Clear_SI Start signal to clear the internal BRAM. * LogEn_SI Enables logging. * * Full_SO Active if the BRAM is nearly or completely full. * Ready_SO Active if the logger is ready to log events. Inactive during clearing. * * Bram_PS Slave interface to access the internal BRAM (e.g., over AXI via an AXI BRAM * Controller). * * In the BRAM, events are stored consecutively in multiple words each. The first word of a log * entry is the 32-bit wide timestamp. All other words are defined by the user via `LogData_DI`. * * For the memory consumption by the internal BRAM, refer to the documentation of the employed BRAM * module. * * During clearing, the logging memory is traversed sequentially. Thus, clearing takes * `NUM_LOG_ENTRIES` clock cycles. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ import CfMath::ceil_div, CfMath::log2; module BramLogger // Parameters {{{ #( // Width (in bits) of one log data payload. Value should be a multiple of 32. parameter LOG_DATA_BITW = 32, // Number of entries in the log. Value must be >= 1024, should be a multiple of 1024, and is // upper-bound by the available memory. parameter NUM_LOG_ENTRIES = 16384 ) // }}} // Ports {{{ ( input logic Clk_CI, input logic TimestampClk_CI, input logic Rst_RBI, // Logging Input input logic [LOG_DATA_BITW-1:0] LogData_DI, input logic LogTrigger_SI, // Control Input input logic Clear_SI, input logic LogEn_SI, // Status Output output logic Full_SO, output logic Ready_SO, // Interface to Internal BRAM BramPort.Slave Bram_PS ); // }}} // Module-Wide Constants {{{ // Properties of the data entries in the log localparam integer TIMESTAMP_BITW = 32; localparam integer LOG_ENTRY_BITW = ceil_div(TIMESTAMP_BITW+LOG_DATA_BITW, 32) * 32; localparam integer LOG_ENTRY_BYTEW = LOG_ENTRY_BITW / 8; localparam integer TIMESTAMP_LOW = 0; localparam integer TIMESTAMP_HIGH = TIMESTAMP_LOW + TIMESTAMP_BITW - 1; localparam integer LOG_DATA_LOW = TIMESTAMP_HIGH + 1; localparam integer LOG_DATA_HIGH = LOG_DATA_LOW + LOG_DATA_BITW - 1; // Properties used when addressing the BRAM array localparam integer LOGGING_CNT_BITW = log2(NUM_LOG_ENTRIES); localparam integer LOGGING_CNT_MAX = NUM_LOG_ENTRIES-1; localparam integer LOGGING_ADDR_WORD_BITO = log2(LOG_ENTRY_BYTEW); localparam integer LOGGING_ADDR_BITW = LOGGING_CNT_BITW + LOGGING_ADDR_WORD_BITO; // }}} // Signal Declarations {{{ logic Rst_R; enum reg [1:0] {READY, CLEARING, FULL} State_SP, State_SN; reg [LOGGING_CNT_BITW -1:0] WrCntA_SP, WrCntA_SN; logic [LOG_ENTRY_BITW -1:0] WrA_D; logic [LOG_ENTRY_BYTEW -1:0] WrEnA_S; reg [TIMESTAMP_BITW-1:0] Timestamp_SP, Timestamp_SN; // }}} // Permanent Signal Assignments {{{ assign Rst_R = ~Rst_RBI; // }}} // Internal BRAM Interfaces {{{ BramPort #( .DATA_BITW(LOG_ENTRY_BITW), .ADDR_BITW(LOGGING_ADDR_BITW) ) BramLog_P (); assign BramLog_P.Clk_C = Clk_CI; assign BramLog_P.Rst_R = Rst_R; assign BramLog_P.En_S = WrEnA_S; always_comb begin BramLog_P.Addr_S = '0; BramLog_P.Addr_S[LOGGING_ADDR_BITW-1:0] = (WrCntA_SP << LOGGING_ADDR_WORD_BITO); end assign BramLog_P.Wr_D = WrA_D; assign BramLog_P.WrEn_S = WrEnA_S; BramPort #( .DATA_BITW(LOG_ENTRY_BITW), .ADDR_BITW(LOGGING_ADDR_BITW) ) BramDwc_P (); // }}} // Instantiation of True Dual-Port BRAM Array {{{ TdpBramArray #( .DATA_BITW(LOG_ENTRY_BITW), .NUM_ENTRIES(NUM_LOG_ENTRIES) ) bramArr ( .A_PS(BramLog_P), .B_PS(BramDwc_P) ); // }}} // Instantiation of Data Width Converter {{{ BramDwc #( .ADDR_BITW (Bram_PS.ADDR_BITW), .MST_DATA_BITW (32), .SLV_DATA_BITW (LOG_ENTRY_BITW) ) bramDwc ( .FromMaster_PS(Bram_PS), .ToSlave_PM (BramDwc_P) ); // }}} // Control FSM {{{ always_comb begin // Default Assignments Full_SO = 0; Ready_SO = 0; WrCntA_SN = WrCntA_SP; WrEnA_S = '0; State_SN = State_SP; case (State_SP) READY: begin Ready_SO = 1; if (LogEn_SI && LogTrigger_SI && ~Clear_SI) begin WrCntA_SN = WrCntA_SP + 1; WrEnA_S = '1; end // Raise "Full" output if BRAMs are nearly full (i.e., 1024 entries earlier). if (WrCntA_SP >= (LOGGING_CNT_MAX-1024)) begin Full_SO = 1; end if (WrCntA_SP == LOGGING_CNT_MAX) begin State_SN = FULL; end if (Clear_SI && WrCntA_SP != 0) begin WrCntA_SN = 0; State_SN = CLEARING; end end CLEARING: begin WrCntA_SN = WrCntA_SP + 1; WrEnA_S = '1; if (WrCntA_SP == LOGGING_CNT_MAX) begin WrCntA_SN = 0; State_SN = READY; end end FULL: begin Full_SO = 1; if (Clear_SI) begin WrCntA_SN = 0; State_SN = CLEARING; end end endcase end // }}} // Log Data Formatting {{{ always_comb begin WrA_D = '0; if (State_SP != CLEARING) begin WrA_D[TIMESTAMP_HIGH:TIMESTAMP_LOW] = Timestamp_SP; WrA_D[ LOG_DATA_HIGH: LOG_DATA_LOW] = LogData_DI; end end // }}} // Timestamp Counter {{{ always_comb begin Timestamp_SN = Timestamp_SP + 1; if (Timestamp_SP == {TIMESTAMP_BITW{1'b1}}) begin Timestamp_SN = 0; end end // }}} // Flip-Flops {{{ always_ff @ (posedge Clk_CI) begin State_SP <= READY; WrCntA_SP <= 0; if (Rst_RBI) begin State_SP <= State_SN; WrCntA_SP <= WrCntA_SN; end end always_ff @ (posedge TimestampClk_CI) begin Timestamp_SP <= 0; if (Rst_RBI) begin Timestamp_SP <= Timestamp_SN; end end // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
// Copyright 2016 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. /** * BRAM Port Interface * * This interface contains all signals required to connect a Block RAM. * * Parameter Description: * DATA_BITW Width of the data ports in bits. Must be a multiple of 8. * ADDR_BITW Width of the address port in bits. Must be a multiple of 8. * * Port Description: * Clk_C All operations on this interface are synchronous to this single-phase clock port. * Rst_R Synchronous reset for the output register/latch of the interface; does NOT reset the * BRAM. Note that this reset is active high. * En_S Enables read, write, and reset operations to through this interface. * Addr_S Byte-wise address for all operations on this interface. Note that the word address * offset varies with `DATA_BITW`! * Rd_D Data output for read operations on the BRAM. * Wr_D Data input for write operations on the BRAM. * WrEn_S Byte-wise write enable. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ interface BramPort #( parameter DATA_BITW = 32, parameter ADDR_BITW = 32 ); logic Clk_C; logic Rst_R; logic En_S; logic [ADDR_BITW-1:0] Addr_S; logic [DATA_BITW-1:0] Rd_D; logic [DATA_BITW-1:0] Wr_D; logic [(DATA_BITW/8)-1:0] WrEn_S; modport Slave ( input Clk_C, Rst_R, En_S, Addr_S, Wr_D, WrEn_S, output Rd_D ); modport Master ( input Rd_D, output Clk_C, Rst_R, En_S, Addr_S, Wr_D, WrEn_S ); endinterface // vim: nosmartindent autoindent
// Copyright 2014 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. /** * Inferable, Synchronous Dual-Port RAM * * This module is designed to work with both Xilinx and Altera tools by following the respective * guidelines: * - Xilinx UG901 Vivado Design Suite User Guide: Synthesis (p. 106) * - Altera Quartus II Handbook Volume 1: Design and Synthesis (p. 768) * * Current Maintainers: * - Michael Schaffner <schaffer@iis.ee.ethz.ch> */ // this automatically switches the behavioral description // pragma translate_off `define SIMULATION // pragma translate_on module SyncDpRam #( parameter ADDR_WIDTH = 10, parameter DATA_DEPTH = 1024, // usually 2**ADDR_WIDTH, but can be lower parameter DATA_WIDTH = 32, parameter OUT_REGS = 0, parameter SIM_INIT = 0 // for simulation only, will not be synthesized // 0: no init, 1: zero init, 2: random init // note: on verilator, 2 is not supported. define the VERILATOR macro to work around. )( input logic Clk_CI, input logic Rst_RBI, // port A input logic CSelA_SI, input logic WrEnA_SI, input logic [DATA_WIDTH-1:0] WrDataA_DI, input logic [ADDR_WIDTH-1:0] AddrA_DI, output logic [DATA_WIDTH-1:0] RdDataA_DO, // port B input logic CSelB_SI, input logic WrEnB_SI, input logic [DATA_WIDTH-1:0] WrDataB_DI, input logic [ADDR_WIDTH-1:0] AddrB_DI, output logic [DATA_WIDTH-1:0] RdDataB_DO ); //////////////////////////// // signals, localparams //////////////////////////// logic [DATA_WIDTH-1:0] RdDataA_DN; logic [DATA_WIDTH-1:0] RdDataA_DP; logic [DATA_WIDTH-1:0] RdDataB_DN; logic [DATA_WIDTH-1:0] RdDataB_DP; logic [DATA_WIDTH-1:0] Mem_DP [DATA_DEPTH-1:0]; //////////////////////////// // XILINX/ALTERA implementation //////////////////////////// `ifdef SIMULATION always_ff @(posedge Clk_CI) begin automatic logic [DATA_WIDTH-1:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif Mem_DP[k] = val; end end else begin if (CSelA_SI) begin if (WrEnA_SI) begin Mem_DP[AddrA_DI] <= WrDataA_DI; end else begin RdDataA_DN <= Mem_DP[AddrA_DI]; end end if (CSelB_SI) begin if (WrEnB_SI) begin Mem_DP[AddrB_DI] <= WrDataB_DI; end else begin RdDataB_DN <= Mem_DP[AddrB_DI]; end end end end `endif //////////////////////////// // XILINX/ALTERA implementation //////////////////////////// `ifndef SIMULATION always_ff @(posedge Clk_CI) begin if (CSelA_SI) begin if (WrEnA_SI) begin Mem_DP[AddrA_DI] <= WrDataA_DI; end else begin RdDataA_DN <= Mem_DP[AddrA_DI]; end end end always_ff @(posedge Clk_CI) begin if (CSelB_SI) begin if (WrEnB_SI) begin Mem_DP[AddrB_DI] <= WrDataB_DI; end else begin RdDataB_DN <= Mem_DP[AddrB_DI]; end end end `endif //////////////////////////// // optional output regs //////////////////////////// // output regs generate if (OUT_REGS>0) begin : g_outreg always_ff @(posedge Clk_CI or negedge Rst_RBI) begin if(Rst_RBI == 1'b0) begin RdDataA_DP <= 0; RdDataB_DP <= 0; end else begin RdDataA_DP <= RdDataA_DN; RdDataB_DP <= RdDataB_DN; end end end endgenerate // g_outreg // output reg bypass generate if (OUT_REGS==0) begin : g_oureg_byp assign RdDataA_DP = RdDataA_DN; assign RdDataB_DP = RdDataB_DN; end endgenerate// g_oureg_byp assign RdDataA_DO = RdDataA_DP; assign RdDataB_DO = RdDataB_DP; //////////////////////////// // assertions //////////////////////////// // pragma translate_off assert property (@(posedge Clk_CI) (longint'(2)**longint'(ADDR_WIDTH) >= longint'(DATA_DEPTH))) else $error("depth out of bounds"); assert property (@(posedge Clk_CI) (CSelA_SI & CSelB_SI & WrEnA_SI & WrEnB_SI) |-> (AddrA_DI != AddrB_DI)) else $error("A and B write to the same address"); // pragma translate_on endmodule // SyncDpRam
// Copyright 2014 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. /** * Inferable, Synchronous Single-Port RAM * * This module is designed to work with both Xilinx and Altera tools by following the respective * guidelines: * - Xilinx UG901 Vivado Design Suite User Guide: Synthesis (p. 106) * - Altera Quartus II Handbook Volume 1: Design and Synthesis (p. 768) * * Current Maintainers: * - Michael Schaffner <schaffer@iis.ee.ethz.ch> */ module SyncSpRam #( parameter ADDR_WIDTH = 10, parameter DATA_DEPTH = 1024, // usually 2**ADDR_WIDTH, but can be lower parameter DATA_WIDTH = 32, parameter OUT_REGS = 0, parameter SIM_INIT = 0 // for simulation only, will not be synthesized // 0: no init, 1: zero init, 2: random init // note: on verilator, 2 is not supported. define the VERILATOR macro to work around. )( input logic Clk_CI, input logic Rst_RBI, input logic CSel_SI, input logic WrEn_SI, input logic [ADDR_WIDTH-1:0] Addr_DI, input logic [DATA_WIDTH-1:0] WrData_DI, output logic [DATA_WIDTH-1:0] RdData_DO ); //////////////////////////// // signals, localparams //////////////////////////// logic [DATA_WIDTH-1:0] RdData_DN; logic [DATA_WIDTH-1:0] RdData_DP; logic [DATA_WIDTH-1:0] Mem_DP [DATA_DEPTH-1:0]; //////////////////////////// // XILINX/ALTERA implementation //////////////////////////// always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [DATA_WIDTH-1:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif Mem_DP[k] = val; end end else //pragma translate_on if (CSel_SI) begin if (WrEn_SI) begin Mem_DP[Addr_DI] <= WrData_DI; end else begin RdData_DN <= Mem_DP[Addr_DI]; end end end //////////////////////////// // optional output regs //////////////////////////// // output regs generate if (OUT_REGS>0) begin : g_outreg always_ff @(posedge Clk_CI or negedge Rst_RBI) begin if(Rst_RBI == 1'b0) begin RdData_DP <= 0; end else begin RdData_DP <= RdData_DN; end end end endgenerate // g_outreg // output reg bypass generate if (OUT_REGS==0) begin : g_oureg_byp assign RdData_DP = RdData_DN; end endgenerate// g_oureg_byp assign RdData_DO = RdData_DP; //////////////////////////// // assertions //////////////////////////// // pragma translate_off assert property (@(posedge Clk_CI) (longint'(2)**longint'(ADDR_WIDTH) >= longint'(DATA_DEPTH))) else $error("depth out of bounds"); // pragma translate_on endmodule // SyncSpRam
// Copyright 2014 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. /** * Inferable, Synchronous Single-Port N x 32bit RAM with Byte-Wise Enable * * This module contains an implementation for either Xilinx or Altera FPGAs. To synthesize for * Xilinx, define `FPGA_TARGET_XILINX`. To synthesize for Altera, define `FPGA_TARGET_ALTERA`. The * implementations follow the respective guidelines: * - Xilinx UG901 Vivado Design Suite User Guide: Synthesis (p. 106) * - Altera Quartus II Handbook Volume 1: Design and Synthesis (p. 768) * * Current Maintainers: * - Michael Schaffner <schaffer@iis.ee.ethz.ch> */ `ifndef FPGA_TARGET_ALTERA `define FPGA_TARGET_XILINX `endif module SyncSpRamBeNx32 #( parameter ADDR_WIDTH = 10, parameter DATA_DEPTH = 1024, // usually 2**ADDR_WIDTH, but can be lower parameter OUT_REGS = 0, // set to 1 to enable outregs parameter SIM_INIT = 0 // for simulation only, will not be synthesized // 0: no init, 1: zero init, 2: random init, 3: deadbeef init // note: on verilator, 2 is not supported. define the VERILATOR macro to work around. )( input logic Clk_CI, input logic Rst_RBI, input logic CSel_SI, input logic WrEn_SI, input logic [3:0] BEn_SI, input logic [31:0] WrData_DI, input logic [ADDR_WIDTH-1:0] Addr_DI, output logic [31:0] RdData_DO ); //////////////////////////// // signals, localparams //////////////////////////// // needs to be consistent with the Altera implemenation below localparam DATA_BYTES = 4; logic [DATA_BYTES*8-1:0] RdData_DN; logic [DATA_BYTES*8-1:0] RdData_DP; //////////////////////////// // XILINX implementation //////////////////////////// `ifdef FPGA_TARGET_XILINX logic [DATA_BYTES*8-1:0] Mem_DP[DATA_DEPTH-1:0]; always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [31:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif else val = 32'hdeadbeef; Mem_DP[k] = val; end end else //pragma translate_on if(CSel_SI) begin if(WrEn_SI) begin if(BEn_SI[0]) Mem_DP[Addr_DI][7:0] <= WrData_DI[7:0]; if(BEn_SI[1]) Mem_DP[Addr_DI][15:8] <= WrData_DI[15:8]; if(BEn_SI[2]) Mem_DP[Addr_DI][23:16] <= WrData_DI[23:16]; if(BEn_SI[3]) Mem_DP[Addr_DI][31:24] <= WrData_DI[31:24]; end RdData_DN <= Mem_DP[Addr_DI]; end end `endif //////////////////////////// // ALTERA implementation //////////////////////////// `ifdef FPGA_TARGET_ALTERA logic [DATA_BYTES-1:0][7:0] Mem_DP[0:DATA_DEPTH-1]; always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [31:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif else val = 32'hdeadbeef; Mem_DP[k] = val; end end else //pragma translate_on if(CSel_SI) begin if(WrEn_SI) begin // needs to be static, otherwise Altera wont infer it if(BEn_SI[0]) Mem_DP[Addr_DI][0] <= WrData_DI[7:0]; if(BEn_SI[1]) Mem_DP[Addr_DI][1] <= WrData_DI[15:8]; if(BEn_SI[2]) Mem_DP[Addr_DI][2] <= WrData_DI[23:16]; if(BEn_SI[3]) Mem_DP[Addr_DI][3] <= WrData_DI[31:24]; end RdData_DN <= Mem_DP[Addr_DI]; end end `endif //////////////////////////// // optional output regs //////////////////////////// // output regs generate if (OUT_REGS>0) begin : g_outreg always_ff @(posedge Clk_CI or negedge Rst_RBI) begin if(Rst_RBI == 1'b0) begin RdData_DP <= 0; end else begin RdData_DP <= RdData_DN; end end end endgenerate // g_outreg // output reg bypass generate if (OUT_REGS==0) begin : g_oureg_byp assign RdData_DP = RdData_DN; end endgenerate// g_oureg_byp assign RdData_DO = RdData_DP; //////////////////////////// // assertions //////////////////////////// // pragma translate_off assert property (@(posedge Clk_CI) (longint'(2)**longint'(ADDR_WIDTH) >= longint'(DATA_DEPTH))) else $error("depth out of bounds"); // pragma translate_on `ifndef FPGA_TARGET_XILINX `ifndef FPGA_TARGET_ALTERA "FPGA target not defined, define FPGA_TARGET_XILINX or FPGA_TARGET_ALTERA." `endif `endif endmodule // SyncSpRamBeNx32
// Copyright 2014 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. /** * Inferable, Synchronous Single-Port N x 64bit RAM with Byte-Wise Enable * * This module contains an implementation for either Xilinx or Altera FPGAs. To synthesize for * Xilinx, define `FPGA_TARGET_XILINX`. To synthesize for Altera, define `FPGA_TARGET_ALTERA`. The * implementations follow the respective guidelines: * - Xilinx UG901 Vivado Design Suite User Guide: Synthesis (p. 106) * - Altera Quartus II Handbook Volume 1: Design and Synthesis (p. 768) * * Current Maintainers: * - Michael Schaffner <schaffer@iis.ee.ethz.ch> */ `ifndef FPGA_TARGET_ALTERA `define FPGA_TARGET_XILINX `endif module SyncSpRamBeNx64 #( parameter ADDR_WIDTH = 10, parameter DATA_DEPTH = 1024, // usually 2**ADDR_WIDTH, but can be lower parameter OUT_REGS = 0, // set to 1 to enable outregs parameter SIM_INIT = 0 // for simulation only, will not be synthesized // 0: no init, 1: zero init, 2: random init, 3: deadbeef init // note: on verilator, 2 is not supported. define the VERILATOR macro to work around. )( input logic Clk_CI, input logic Rst_RBI, input logic CSel_SI, input logic WrEn_SI, input logic [7:0] BEn_SI, input logic [63:0] WrData_DI, input logic [ADDR_WIDTH-1:0] Addr_DI, output logic [63:0] RdData_DO ); //////////////////////////// // signals, localparams //////////////////////////// // needs to be consistent with the Altera implemenation below localparam DATA_BYTES = 8; logic [DATA_BYTES*8-1:0] RdData_DN; logic [DATA_BYTES*8-1:0] RdData_DP; //////////////////////////// // XILINX implementation //////////////////////////// `ifdef FPGA_TARGET_XILINX logic [DATA_BYTES*8-1:0] Mem_DP[DATA_DEPTH-1:0]; always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [63:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif else val = 64'hdeadbeefdeadbeef; Mem_DP[k] = val; end end else //pragma translate_on if(CSel_SI) begin if(WrEn_SI) begin if(BEn_SI[0]) Mem_DP[Addr_DI][7:0] <= WrData_DI[7:0]; if(BEn_SI[1]) Mem_DP[Addr_DI][15:8] <= WrData_DI[15:8]; if(BEn_SI[2]) Mem_DP[Addr_DI][23:16] <= WrData_DI[23:16]; if(BEn_SI[3]) Mem_DP[Addr_DI][31:24] <= WrData_DI[31:24]; if(BEn_SI[4]) Mem_DP[Addr_DI][39:32] <= WrData_DI[39:32]; if(BEn_SI[5]) Mem_DP[Addr_DI][47:40] <= WrData_DI[47:40]; if(BEn_SI[6]) Mem_DP[Addr_DI][55:48] <= WrData_DI[55:48]; if(BEn_SI[7]) Mem_DP[Addr_DI][63:56] <= WrData_DI[63:56]; end RdData_DN <= Mem_DP[Addr_DI]; end end `endif //////////////////////////// // ALTERA implementation //////////////////////////// `ifdef FPGA_TARGET_ALTERA logic [DATA_BYTES-1:0][7:0] Mem_DP[0:DATA_DEPTH-1]; always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [63:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif else val = 64'hdeadbeefdeadbeef; Mem_DP[k] = val; end end else //pragma translate_on if(CSel_SI) begin if(WrEn_SI) begin // needs to be static, otherwise Altera wont infer it if(BEn_SI[0]) Mem_DP[Addr_DI][0] <= WrData_DI[7:0]; if(BEn_SI[1]) Mem_DP[Addr_DI][1] <= WrData_DI[15:8]; if(BEn_SI[2]) Mem_DP[Addr_DI][2] <= WrData_DI[23:16]; if(BEn_SI[3]) Mem_DP[Addr_DI][3] <= WrData_DI[31:24]; if(BEn_SI[4]) Mem_DP[Addr_DI][4] <= WrData_DI[39:32]; if(BEn_SI[5]) Mem_DP[Addr_DI][5] <= WrData_DI[47:40]; if(BEn_SI[6]) Mem_DP[Addr_DI][6] <= WrData_DI[55:48]; if(BEn_SI[7]) Mem_DP[Addr_DI][7] <= WrData_DI[63:56]; end RdData_DN <= Mem_DP[Addr_DI]; end end `endif //////////////////////////// // optional output regs //////////////////////////// // output regs generate if (OUT_REGS>0) begin : g_outreg always_ff @(posedge Clk_CI or negedge Rst_RBI) begin if(Rst_RBI == 1'b0) begin RdData_DP <= 0; end else begin RdData_DP <= RdData_DN; end end end endgenerate // g_outreg // output reg bypass generate if (OUT_REGS==0) begin : g_oureg_byp assign RdData_DP = RdData_DN; end endgenerate// g_oureg_byp assign RdData_DO = RdData_DP; //////////////////////////// // assertions //////////////////////////// // pragma translate_off assert property (@(posedge Clk_CI) (longint'(2)**longint'(ADDR_WIDTH) >= longint'(DATA_DEPTH))) else $error("depth out of bounds"); // pragma translate_on `ifndef FPGA_TARGET_XILINX `ifndef FPGA_TARGET_ALTERA $error("FPGA target not defined, define FPGA_TARGET_XILINX or FPGA_TARGET_ALTERA."); `endif `endif endmodule // SyncSpRamBeNx64
// Copyright 2014 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. /** * Inferable, Synchronous Two-Port RAM * * This RAM has a dedicated read and a dedicated write port. When reading and writing from and to * the same address in a single clock cycle, the read port returns the data before the write. * * This module is designed to work with both Xilinx and Altera tools by following the respective * guidelines: * - Xilinx UG901 Vivado Design Suite User Guide: Synthesis (p. 106) * - Altera Quartus II Handbook Volume 1: Design and Synthesis (p. 768) * * Current Maintainers: * - Michael Schaffner <schaffer@iis.ee.ethz.ch> */ module SyncTpRam #( parameter ADDR_WIDTH = 10, parameter DATA_DEPTH = 1024, // usually 2**ADDR_WIDTH, but can be lower parameter DATA_WIDTH = 32, parameter OUT_REGS = 0, parameter SIM_INIT = 0 // for simulation only, will not be synthesized // 0: no init, 1: zero init, 2: random init // note: on verilator, 2 is not supported. define the VERILATOR macro to work around. )( input logic Clk_CI, input logic Rst_RBI, input logic WrEn_SI, input logic [ADDR_WIDTH-1:0] WrAddr_DI, input logic [DATA_WIDTH-1:0] WrData_DI, input logic RdEn_SI, input logic [ADDR_WIDTH-1:0] RdAddr_DI, output logic [DATA_WIDTH-1:0] RdData_DO ); //////////////////////////// // signals, localparams //////////////////////////// logic [DATA_WIDTH-1:0] RdData_DN; logic [DATA_WIDTH-1:0] RdData_DP; logic [DATA_WIDTH-1:0] Mem_DP [DATA_DEPTH-1:0]; //////////////////////////// // XILINX/ALTERA implementation //////////////////////////// always_ff @(posedge Clk_CI) begin //pragma translate_off automatic logic [DATA_WIDTH-1:0] val; if(Rst_RBI == 1'b0 && SIM_INIT>0) begin for(int k=0; k<DATA_DEPTH;k++) begin if(SIM_INIT==1) val = '0; `ifndef VERILATOR else if(SIM_INIT==2) void'(randomize(val)); `endif Mem_DP[k] = val; end end else begin //pragma translate_on if (RdEn_SI) begin RdData_DN <= Mem_DP[RdAddr_DI]; end if (WrEn_SI) begin Mem_DP[WrAddr_DI] <= WrData_DI; end //pragma translate_off `ifndef VERILATOR end `endif //pragma translate_on end //////////////////////////// // optional output regs //////////////////////////// // output regs generate if (OUT_REGS>0) begin : g_outreg always_ff @(posedge Clk_CI or negedge Rst_RBI) begin if(Rst_RBI == 1'b0) begin RdData_DP <= 0; end else begin RdData_DP <= RdData_DN; end end end endgenerate // g_outreg // output reg bypass generate if (OUT_REGS==0) begin : g_oureg_byp assign RdData_DP = RdData_DN; end endgenerate// g_oureg_byp assign RdData_DO = RdData_DP; //////////////////////////// // assertions //////////////////////////// // pragma translate_off assert property (@(posedge Clk_CI) (longint'(2)**longint'(ADDR_WIDTH) >= longint'(DATA_DEPTH))) else $error("depth out of bounds"); // pragma translate_on endmodule // SyncTpRam
// Copyright 2016 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. /** * True Dual-Port BRAM Array for Xilinx 7 Series Devices * * This module contains a two-dimensional array of Xilinx' 7 Series True Dual-Port BRAM cells. The * array is * NUM_PAR_BRAMS = ceil(DATA_BITW/32) * BRAMs wide and * NUM_SER_BRAMS = ceil(NUM_ENTRIES/1024) * BRAMs deep, as each BRAM is 32 bit wide and 1024 entries deep. * * This module is addressed byte-wise! Be careful when addressing a BRAM array that has more than * one BRAM in parallel (i.e., when `DATA_BITW > 32`): the * WORD_OFFSET = ceil(log2(DATA_BITW/8)) * least-significant bits of the address are used to address the bytes within a word. The reason * for byte-wise addressing is to enable instances with a width that is a power of two (and >= 32) * to directly connect to a Xilinx AXI 4 BRAM Controller. If you want to connect a BRAM that does * not fulfill the direct connection criterion, use the Data Width Converter `BramDwc`. * * Even though addressing is byte-wise, accesses that are not aligned to words are not supported. * * Both ports can be operated independently and asynchronously; the behavior on access collisions is * specified in the Xilinx Block Memory Generator Product Guide (PG058). * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ import CfMath::ceil_div, CfMath::log2; module TdpBramArray // Parameters {{{ #( // Width (in bits) of the read/write data ports. Should be a multiple of 32 (for optimal // resource usage) and is upper-bound by the available memory resources. parameter DATA_BITW = 96, // Number of entries (each entry is `DATA_BITW` bits wide) in the BRAM array. Should be // a multiple of 1024 (for optimal resource usage) and is upper-bound by the available memory // resources. parameter NUM_ENTRIES = 8192 ) // }}} // Ports {{{ ( BramPort.Slave A_PS, BramPort.Slave B_PS ); // }}} // Module-Wide Constants {{{ // Properties of the employed BRAM cells localparam integer BRAM_BITW = 32; localparam integer BRAM_BYTEW = BRAM_BITW / 8; localparam integer NUM_BRAM_WORDS = 1024; // Properties of the resulting memory array localparam integer NUM_PAR_BRAMS = ceil_div(DATA_BITW, BRAM_BITW); localparam integer NUM_SER_BRAMS = ceil_div(NUM_ENTRIES, NUM_BRAM_WORDS); localparam integer ARR_BITW = BRAM_BITW * NUM_PAR_BRAMS; localparam integer ARR_BYTEW = BRAM_BYTEW * NUM_PAR_BRAMS; localparam integer NUM_ARR_WORDS = NUM_BRAM_WORDS * NUM_SER_BRAMS; // Offset (in bits) of words in the external addresses localparam integer ADDR_WORD_BITO = log2(ARR_BYTEW); localparam integer WORD_ADDR_BITW = log2(NUM_ARR_WORDS); localparam integer SER_IDX_BITW = log2(NUM_SER_BRAMS); localparam integer WORD_IDX_BITW = log2(NUM_BRAM_WORDS); // }}} // Signal Declarations {{{ // Output signals after multiplexing of parallel BRAM cells logic [NUM_SER_BRAMS-1:0] [ARR_BITW -1:0] ARd_D, BRd_D; // Word part of external address logic [WORD_ADDR_BITW -1:0] WordAddrA_S, WordAddrB_S; // Serial index of BRAM cell in array logic [SER_IDX_BITW -1:0] SerIdxA_S, SerIdxB_S; logic SerIdxAOverflow_S, SerIdxBOverflow_S; // Word index in BRAM cell logic [WORD_IDX_BITW -1:0] WordIdxA_S, WordIdxB_S; // }}} // Resolve (Linear) Address to Serial (BRAM), Word Index and Address of RAMs {{{ assign WordAddrA_S = A_PS.Addr_S[ADDR_WORD_BITO+(WORD_ADDR_BITW-1):ADDR_WORD_BITO]; assign WordAddrB_S = B_PS.Addr_S[ADDR_WORD_BITO+(WORD_ADDR_BITW-1):ADDR_WORD_BITO]; always_comb begin SerIdxAOverflow_S = 0; SerIdxA_S = WordAddrA_S / NUM_BRAM_WORDS; if (SerIdxA_S >= NUM_SER_BRAMS) begin SerIdxAOverflow_S = 1; SerIdxA_S = 0; end end always_comb begin SerIdxBOverflow_S = 0; SerIdxB_S = WordAddrB_S / NUM_BRAM_WORDS; if (SerIdxB_S >= NUM_SER_BRAMS) begin SerIdxBOverflow_S = 1; SerIdxB_S = 0; end end assign WordIdxA_S = WordAddrA_S % NUM_BRAM_WORDS; assign WordIdxB_S = WordAddrB_S % NUM_BRAM_WORDS; always @ (posedge A_PS.Clk_C) begin if (A_PS.Rst_R == 0) begin assert (~SerIdxAOverflow_S) else $warning("Serial index on port A out of bounds!"); assert (WordIdxA_S < NUM_BRAM_WORDS) else $error("Word index on port A out of bounds!"); end end always @ (posedge B_PS.Clk_C) begin if (B_PS.Rst_R == 0) begin assert (~SerIdxBOverflow_S) else $warning("Serial index on port B out of bounds!"); assert (WordIdxB_S < NUM_BRAM_WORDS) else $error("Word index on port B out of bounds!"); end end // }}} // BRAM Instantiation, Signal Resolution, and Port Assignment {{{ genvar s, p; for (s = 0; s < NUM_SER_BRAMS; s++) begin for (p = 0; p < NUM_PAR_BRAMS; p++) begin // Instance-Specific Constants {{{ localparam integer WORD_BIT_LOW = BRAM_BITW *p; localparam integer WORD_BIT_HIGH = WORD_BIT_LOW + (BRAM_BITW -1); localparam integer WORD_BYTE_LOW = BRAM_BYTEW*p; localparam integer WORD_BYTE_HIGH = WORD_BYTE_LOW + (BRAM_BYTEW-1); // }}} // Write-Enable Resolution {{{ logic [BRAM_BYTEW-1:0] WrEnA_S, WrEnB_S; always_comb begin WrEnA_S = '0; WrEnB_S = '0; if (SerIdxA_S == s && ~SerIdxAOverflow_S) begin WrEnA_S = A_PS.WrEn_S[WORD_BYTE_HIGH:WORD_BYTE_LOW]; end if (SerIdxB_S == s && ~SerIdxBOverflow_S) begin WrEnB_S = B_PS.WrEn_S[WORD_BYTE_HIGH:WORD_BYTE_LOW]; end end // }}} // BRAM_TDP_MACRO Parameters and Initial Values {{{ // BRAM_TDP_MACRO: True Dual Port RAM // Virtex-7 // Xilinx HDL Language Template, version 2016.1 BRAM_TDP_MACRO #( // Target BRAM: {"18Kb", "36Kb"} .BRAM_SIZE("36Kb"), // Target Device: {"7SERIES"} .DEVICE("7SERIES"), // Optional Port A/B Output Registers: {0, 1} .DOA_REG(0), .DOB_REG(0), // Initial Value of Port A/B Output .INIT_A(36'h000000000), .INIT_B(36'h000000000), // RAM Initialization File .INIT_FILE("NONE"), // Width of Port A/B Output: 1..36 (19..36 only if BRAM_SIZE="36Kb") .READ_WIDTH_A(BRAM_BITW), .READ_WIDTH_B(BRAM_BITW), // Enable Collision Check in Simulation: {"ALL", "WARNING_ONLY", "GENERATE_X_ONLY", "NONE"} .SIM_COLLISION_CHECK ("ALL"), // Set/Reset Value of Port A/B Output .SRVAL_A(36'h00000000), .SRVAL_B(36'h00000000), // Write Mode of Port A/B {"WRITE_FIRST", "READ_FIRST", "NO_CHANGE"} .WRITE_MODE_A("WRITE_FIRST"), .WRITE_MODE_B("WRITE_FIRST"), // Width of Port A/B Input: 1..36 (19..36 only if BRAM_SIZE="36Kb") .WRITE_WIDTH_A(BRAM_BITW), .WRITE_WIDTH_B(BRAM_BITW), // Initialization of Data Bits in Lower 16 Kibit {{{ .INIT_00(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_01(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_02(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_03(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_04(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_05(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_06(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_07(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_08(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_09(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_0F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_10(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_11(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_12(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_13(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_14(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_15(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_16(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_17(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_18(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_19(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_1F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_20(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_21(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_22(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_23(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_24(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_25(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_26(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_27(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_28(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_29(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_2F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_30(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_31(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_32(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_33(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_34(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_35(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_36(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_37(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_38(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_39(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_3F(256'h0000000000000000000000000000000000000000000000000000000000000000), // }}} // Initialization of Data Bits in Higher 16 Kibit {{{ // The next set of INIT_xx are valid when configured as 36Kb .INIT_40(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_41(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_42(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_43(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_44(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_45(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_46(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_47(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_48(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_49(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_4F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_50(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_51(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_52(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_53(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_54(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_55(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_56(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_57(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_58(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_59(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_5F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_60(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_61(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_62(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_63(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_64(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_65(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_66(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_67(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_68(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_69(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_6F(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_70(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_71(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_72(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_73(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_74(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_75(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_76(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_77(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_78(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_79(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INIT_7F(256'h0000000000000000000000000000000000000000000000000000000000000000), // }}} // Initialization of Parity Bits in Lower 16 Kibit {{{ // The next set of INITP_xx are for the parity bits .INITP_00(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_01(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_02(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_03(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_04(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_05(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_06(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_07(256'h0000000000000000000000000000000000000000000000000000000000000000), // }}} // Initialization of Parity Bits in Higher 16 Kibit {{{ // The next set of INITP_xx are valid when configured as 36Kb .INITP_08(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_09(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0A(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0B(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0C(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0D(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0E(256'h0000000000000000000000000000000000000000000000000000000000000000), .INITP_0F(256'h0000000000000000000000000000000000000000000000000000000000000000) // }}} ) // }}} // BRAM_TDP_MACRO Instantation {{{ BRAM_TDP_MACRO_inst ( // Port A {{{ .CLKA (A_PS.Clk_C ), // 1-bit inp: clock .RSTA (A_PS.Rst_R ), // 1-bit inp: reset (active high) .ENA (A_PS.En_S ), // 1-bit inp: enable .REGCEA (1'b0 ), // 1-bit inp: output register enable .ADDRA (WordIdxA_S ), // 10-bit inp: word-wise address .DOA (ARd_D[s] [WORD_BIT_HIGH:WORD_BIT_LOW] ), // 32-bit oup: data output .DIA (A_PS.Wr_D[WORD_BIT_HIGH:WORD_BIT_LOW] ), // 32-bit inp: data input .WEA (WrEnA_S ), // 4-bit inp: byte-wise write enable // }}} // Port B {{{ .CLKB (B_PS.Clk_C ), // 1-bit inp: clock .RSTB (B_PS.Rst_R ), // 1-bit inp: reset (active high) .ENB (B_PS.En_S ), // 1-bit inp: enable .REGCEB (1'b0 ), // 1-bit inp: output register enable .ADDRB (WordIdxB_S ), // 10-bit inp: word-wise address .DOB (BRd_D[s] [WORD_BIT_HIGH:WORD_BIT_LOW] ), // 32-bit oup: data output .DIB (B_PS.Wr_D[WORD_BIT_HIGH:WORD_BIT_LOW] ), // 32-bit inp: data input .WEB (WrEnB_S ) // 4-bit inp: byte-wise write enable // }}} ); // }}} end end // }}} // Output Multiplexer {{{ assign A_PS.Rd_D = ARd_D[SerIdxA_S]; assign B_PS.Rd_D = BRd_D[SerIdxB_S]; // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
/*.jou /*.log /vivado.* /vivado_pid*.str /.Xil/*
VER = 2016.1 VIVADO_SOURCE_CMDS = -source scripts/setup.tcl -source scripts/synthesize.tcl CF_MATH_PKG_PATH = ../../../../ips/pkg/cfmath nogui: pkgdeps synth_nogui gui: pkgdeps synth_gui pkgdeps: @if [ ! -e $(CF_MATH_PKG_PATH)/CfMath.sv ]; then \ echo "Error: Dependency 'CfMath.sv' not found, please specify 'CF_MATH_PKG_PATH'!"; \ exit 1; \ fi; \ ln -t deps/ -sf ../$(CF_MATH_PKG_PATH)/CfMath.sv synth_nogui: @vivado-${VER} vivado -mode batch $(VIVADO_SOURCE_CMDS) synth_gui: @vivado-${VER} vivado -mode gui $(VIVADO_SOURCE_CMDS) clean: @rm -f *.jou *.log vivado_*.str @rm -rf vivado.*
# BRAM Data Width Converter Synthesis Testbench ## Running Tests This module depends on the `CfMath` package. You have to specify the path to this package when running tests. If this module is not used as part of the `big.pulp` project, specify the correct path to the package in `CF_MATH_PKG_PATH`, e.g., CF_MATH_PKG_PATH=../../../../../fe/ips/pkg/cfmath make ## TODO - Post-synthesis simulation
/CfMath.sv
// Copyright 2016 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. /** * BRAM Data Width Converter * * This module performs data width conversion between a narrow master and a wide slave interface. * * Port Description: * FromMaster_PS Slave BRAM Port interface through which master control signals go to the BRAM. * ToSlave_PM Master BRAM Port interface at which the slave BRAM is connected. * * The data signal of the master interface must be narrower than that of the slave interface. The * reverse situation would require handshaking and buffering and is not supported by the simple BRAM * Port interface. * * Parameter Description: * ADDR_BITW The width (in bits) of the address signals. Both ports must have the same * address width. * MST_DATA_BITW The width (in bits) of the data signal coming from the master controller. * SLV_DATA_BITW The width (in bits) of the data signal of the slave BRAM. * * The value of all parameters must match the connected interfaces. DO NOT rely on the default * values for these parameters, but explicitly set the parameters so that they are correct for your * setup! If one or more values do not match, the behavior of this module is undefined. * * Compatibility Information: * ModelSim >= 10.0b * Vivado >= 2016.1 * * Earlier versions of the tools are either untested or known to fail for this module. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ import CfMath::ceil_div, CfMath::log2; module BramDwc // Parameters {{{ #( parameter integer ADDR_BITW = 32, parameter integer MST_DATA_BITW = 32, parameter integer SLV_DATA_BITW = 96 ) // }}} // Ports {{{ ( BramPort.Slave FromMaster_PS, BramPort.Master ToSlave_PM ); // }}} // Module-Wide Constants {{{ localparam integer MST_DATA_BYTEW = MST_DATA_BITW/8; localparam integer MST_ADDR_WORD_BITO = log2(MST_DATA_BYTEW); localparam integer MST_ADDR_WORD_BITW = ADDR_BITW - MST_ADDR_WORD_BITO; localparam integer SLV_DATA_BYTEW = SLV_DATA_BITW/8; localparam integer SLV_ADDR_WORD_BITO = log2(SLV_DATA_BYTEW); localparam integer SLV_ADDR_WORD_BITW = ADDR_BITW - SLV_ADDR_WORD_BITO; localparam integer PAR_IDX_MAX_VAL = ceil_div(SLV_DATA_BITW, MST_DATA_BITW) - 1; localparam integer PAR_IDX_BITW = log2(PAR_IDX_MAX_VAL+1); // }}} // Initial Assertions {{{ initial begin assert (SLV_DATA_BITW >= MST_DATA_BITW) else $fatal(1, "Downconversion of the data bitwidth from master to slave is not possible!"); assert (MST_DATA_BITW == FromMaster_PS.DATA_BITW) else $fatal(1, "Parameter for data width of master does not match connected interface!"); assert (SLV_DATA_BITW == ToSlave_PM.DATA_BITW) else $fatal(1, "Parameter for data width of slave does not match connected interface!"); assert ((ADDR_BITW == FromMaster_PS.ADDR_BITW) && (ADDR_BITW == ToSlave_PM.ADDR_BITW)) else $fatal(1, "Parameter for address width does not match connected interfaces!"); end // }}} // Register the Addr_S of master interface to make sure the address stays // stable for word selection on reads logic [ADDR_BITW-1:0] Addr_SN, Addr_SP; assign Addr_SN = FromMaster_PS.Addr_S; always_ff @ (posedge FromMaster_PS.Clk_C) begin if (FromMaster_PS.Rst_R == 1'b1) begin Addr_SP <= 'b0; end else if (FromMaster_PS.En_S == 1'b1) begin Addr_SP <= Addr_SN; end end // Pass clock, reset, and enable through. {{{ assign ToSlave_PM.Clk_C = FromMaster_PS.Clk_C; assign ToSlave_PM.Rst_R = FromMaster_PS.Rst_R; assign ToSlave_PM.En_S = FromMaster_PS.En_S; // }}} // Data Width Conversion {{{ logic [MST_ADDR_WORD_BITW-1:0] MstWordAddr_S, MstWordAddrReg_S; assign MstWordAddr_S = Addr_SN[(MST_ADDR_WORD_BITW-1)+MST_ADDR_WORD_BITO:MST_ADDR_WORD_BITO]; assign MstWordAddrReg_S = Addr_SP[(MST_ADDR_WORD_BITW-1)+MST_ADDR_WORD_BITO:MST_ADDR_WORD_BITO]; logic [SLV_ADDR_WORD_BITW-1:0] ToWordAddr_S; assign ToWordAddr_S = MstWordAddr_S / (PAR_IDX_MAX_VAL+1); always_comb begin ToSlave_PM.Addr_S = '0; ToSlave_PM.Addr_S[(SLV_ADDR_WORD_BITW-1)+SLV_ADDR_WORD_BITO:SLV_ADDR_WORD_BITO] = ToWordAddr_S; end logic [PAR_IDX_BITW-1:0] ParIdxRd_S, ParIdxWr_S; assign ParIdxWr_S = MstWordAddr_S % (PAR_IDX_MAX_VAL+1); assign ParIdxRd_S = MstWordAddrReg_S % (PAR_IDX_MAX_VAL+1); // based on address applied with En_S logic [PAR_IDX_MAX_VAL:0] [MST_DATA_BITW-1:0] Rd_D; genvar p; for (p = 0; p <= PAR_IDX_MAX_VAL; p++) begin localparam integer SLV_BYTE_LOW = MST_DATA_BYTEW*p; localparam integer SLV_BYTE_HIGH = SLV_BYTE_LOW + (MST_DATA_BYTEW-1); localparam integer SLV_BIT_LOW = MST_DATA_BITW*p; localparam integer SLV_BIT_HIGH = SLV_BIT_LOW + (MST_DATA_BITW-1); always_comb begin if (ParIdxWr_S == p) begin ToSlave_PM.WrEn_S[SLV_BYTE_HIGH:SLV_BYTE_LOW] = FromMaster_PS.WrEn_S; end else begin ToSlave_PM.WrEn_S[SLV_BYTE_HIGH:SLV_BYTE_LOW] = '0; end end assign Rd_D[p] = ToSlave_PM.Rd_D[SLV_BIT_HIGH:SLV_BIT_LOW]; assign ToSlave_PM.Wr_D[SLV_BIT_HIGH:SLV_BIT_LOW] = FromMaster_PS.Wr_D; end assign FromMaster_PS.Rd_D = Rd_D[ParIdxRd_S]; // }}} endmodule // vim: nosmartindent autoindent foldmethod=marker
// Copyright 2016 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. /** * BRAM Port Interface * * This interface contains all signals required to connect a Block RAM. * * Parameter Description: * DATA_BITW Width of the data ports in bits. Must be a multiple of 8. * ADDR_BITW Width of the address port in bits. Must be a multiple of 8. * * Port Description: * Clk_C All operations on this interface are synchronous to this single-phase clock port. * Rst_R Synchronous reset for the output register/latch of the interface; does NOT reset the * BRAM. Note that this reset is active high. * En_S Enables read, write, and reset operations to through this interface. * Addr_S Byte-wise address for all operations on this interface. Note that the word address * offset varies with `DATA_BITW`! * Rd_D Data output for read operations on the BRAM. * Wr_D Data input for write operations on the BRAM. * WrEn_S Byte-wise write enable. * * Current Maintainers: * - Andreas Kurth <akurth@iis.ee.ethz.ch> * - Pirmin Vogel <vogelpi@iis.ee.ethz.ch> */ interface BramPort #( parameter DATA_BITW = 32, parameter ADDR_BITW = 32 ); logic Clk_C; logic Rst_R; logic En_S; logic [ADDR_BITW-1:0] Addr_S; logic [DATA_BITW-1:0] Rd_D; logic [DATA_BITW-1:0] Wr_D; logic [(DATA_BITW/8)-1:0] WrEn_S; modport Slave ( input Clk_C, Rst_R, En_S, Addr_S, Wr_D, WrEn_S, output Rd_D ); modport Master ( input Rd_D, output Clk_C, Rst_R, En_S, Addr_S, Wr_D, WrEn_S ); endinterface // vim: nosmartindent autoindent
# Create project. create_project vivado . -force -part xc7vx485tffg1157-1 # Downgrade warning about "ignoring assertions" to information. set_msg_config -id {[Synth 8-2898]} -new_severity "info" # Add source files to project. add_files -norecurse -scan_for_includes [glob ./deps/*] add_files -norecurse -scan_for_includes [glob ./src/*] # Define top-level module. set_property top Top [current_fileset] # Update compile order (must do if in batch mode). update_compile_order -fileset [current_fileset]
synth_design -name synth_1
`timescale 1ns / 1ps module Top; localparam integer ADDR_BITW = 32; localparam integer MST_DATA_BITW = 32; localparam integer SLV_DATA_BITW = 96; BramPort #( .DATA_BITW(MST_DATA_BITW), .ADDR_BITW(ADDR_BITW) ) fromMaster (); BramPort #( .DATA_BITW(SLV_DATA_BITW), .ADDR_BITW(ADDR_BITW) ) toSlave (); BramDwc #( .ADDR_BITW (ADDR_BITW), .MST_DATA_BITW (MST_DATA_BITW), .SLV_DATA_BITW (SLV_DATA_BITW) ) dwc ( .FromMaster_PS (fromMaster), .ToSlave_PM (toSlave) ); assign fromMaster.Clk_C = '0; assign fromMaster.Rst_R = '0; assign fromMaster.En_S = '0; assign fromMaster.Addr_S = '0; assign fromMaster.Wr_D = '0; assign fromMaster.WrEn_S = '0; assign toSlave.Rd_D = '0; endmodule // vim: nosmartindent autoindent
/*.jou /*.log /vivado.* /vivado_pid*.str /.Xil/*
VER = 2016.1 VIVADO_SOURCE_CMDS = -source scripts/setup.tcl -source scripts/synthesize.tcl CF_MATH_PKG_PATH = ../../../../ips/pkg/cfmath nogui: pkgdeps synth_nogui gui: pkgdeps synth_gui pkgdeps: @if [ ! -e $(CF_MATH_PKG_PATH)/CfMath.sv ]; then \ echo "Error: Dependency 'CfMath.sv' not found, please specify 'CF_MATH_PKG_PATH'!"; \ exit 1; \ fi; \ ln -t deps/ -sf ../$(CF_MATH_PKG_PATH)/CfMath.sv synth_nogui: @vivado-${VER} vivado -mode batch $(VIVADO_SOURCE_CMDS) synth_gui: @vivado-${VER} vivado -mode gui $(VIVADO_SOURCE_CMDS) clean: @rm -f *.jou *.log vivado_*.str @rm -rf vivado.*
# Create project. create_project vivado . -force -part xc7vx485tffg1157-1 # Downgrade warning about "ignoring assertions" to information. set_msg_config -id {[Synth 8-2898]} -new_severity "info" # Add source files to project. add_files -norecurse -scan_for_includes [glob ./deps/*] add_files -norecurse -scan_for_includes [glob ./src/*] # Define top-level module. set_property top Top [current_fileset] # Update compile order (must do if in batch mode). update_compile_order -fileset [current_fileset]
synth_design -name synth_1
run_hw_ila [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}] -trigger_now wait_on_hw_ila [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}] #display_hw_ila_data [upload_hw_ila_data [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}]] write_hw_ila_data -csv_file -force ila_report.csv [upload_hw_ila_data hw_ila_1] puts "CSV written"
#!/usr/bin/env python # Small utility to upload a file to an embedded Linux system that provides a shell # via its serial port. import sys, time, csv, os import subprocess from getopt import GetoptError, getopt as GetOpt def usage(): print('\nUsage: %s [OPTIONS]\n' % sys.argv[0]) print('\t-s, --source=<local file> Path to local file') print('\t-d, --destination=<remote file> Path to remote file') print('\t --telnet=<host> Upload via telnet instead of serial') print('\t-p, --port=<port> Serial port to use [/dev/ttyUSB0] or telnet port [23]') print('\t-b, --baudrate=<baud> Serial port baud rate [115200]') print('\t-t, --time=<seconds> Time to wait between echo commands [0.1]') print('\t --login=<username> Login name for telnet') print('\t --pass=<passwd> Password for telnet') print('\t-q, --quiet Supress status messages') print('\t-h, --help Show help') print('') sys.exit(1) def LoadTargetSignals(): with open('target_signals.csv') as f: rawdata = csv.reader(f, delimiter=',') data = list(rawdata) signals = [data[i][0] for i in range(1, len(data))] values = [data[i][1] for i in range(1, len(data))] conditions = [data[i][2] for i in range(1, len(data))] #print(signals[0], values[0]) return signals, values, conditions def LoadTargetSignalStatus(signals, values, conditions): with open('ila_report.csv') as f: rawdata = csv.reader(f, delimiter=',') data = list(rawdata) #find target index indexCol = [] for i in range(len(signals)): signalFound = False for j in range(len(data[0])): temp = ''.join(signals[i]) #print(type(temp), type(data[0][0])) #print(temp, data[0][j], '\n') if data[0][j] == temp: indexCol.append(j) signalFound = True print('Matched found! Index:', indexCol[i]) if signalFound == False: indexCol.append('NA') print(signals[i], 'Signal not found!') #search for signal status triggeredStatus = [False] * len(indexCol) for i in range(2, len(data)): isTriggered = False for j in range(len(indexCol)): #print(type(data[i][indexCol[j]]), type(values[j])) #print('a'+data[i][indexCol[j]]+'b'+values[j]) if conditions[j] == '=': if data[i][indexCol[j]] == values[j].strip(): print('Target triggered!') triggeredStatus[j] = True if conditions[j] == '!=': #print(data[i][indexCol[j]], values[j].strip()) if data[i][indexCol[j]] != values[j].strip(): print('Target triggered!') triggeredStatus[j] = True return triggeredStatus def SignalTriggeredPercentage(signalTriggeredStatus): n_signals = len(signalTriggeredStatus) n_triggered = signalTriggeredStatus.count(True) percentage = (n_triggered * 100) / n_signals return percentage def main(): host = None port = None baudrate = 115200 login = None passwd = None source = None destination = None time = None quiet = False signals, values, conditions = LoadTargetSignals() #print(signals) #print(values) #print(conditions) #signalTriggeredStatus = LoadTargetSignalStatus(signals, values, conditions) #triggeredPercent = SignalTriggeredPercentage(signalTriggeredStatus) #print('% Triggered Signals:', triggeredPercent) #os.system("tclsh ila_setup.tcl") #import subprocess #p = subprocess.Popen( #"tclsh /home/monir/research/hw-testing/cva6_mod_2_v2/corev_apu/fpga/ila_setup.tcl", #shell=True, #stdin=subprocess.PIPE, #stdout=subprocess.PIPE, #stderr=subprocess.PIPE, #universal_newlines = True) #stdout, stderr = p.communicate() #print(stdout) #print(stderr) import tkinter #r = tkinter.Tcl() #r.eval('run_hw_ila [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}] -trigger_now') #r.eval('wait_on_hw_ila [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}]') #display_hw_ila_data [upload_hw_ila_data [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}]] #r.eval('write_hw_ila_data -csv_file -force ila_report.csv [upload_hw_ila_data hw_ila_1]') fd = open('ila_capture.tcl') script = fd.read() fd.close() tcl = tkinter.Tcl() tcl.eval(script) print('ILA Setup Completed!') try: opts, args = GetOpt(sys.argv[1:],'p:b:s:d:t:qh', ['port=', 'baudrate=', 'source=', 'destination=', 'time=', 'quiet', 'help', 'telnet=', 'login=', 'pass=']) except (GetoptError, e): print("Usage error:", e) usage() for opt, arg in opts: if opt in ('--telnet',): host = arg elif opt in ('--login',): login = arg elif opt in ('--pass',): passwd = arg elif opt in ('-p', '--port'): port = arg elif opt in ('-b', '--baudrate'): baudrate = arg elif opt in ('-s', '--source'): source = arg elif opt in ('-d', '--destination'): destination = arg elif opt in ('-t', '--time'): time = float(arg) elif opt in ('-q', '--quiet'): quiet = True elif opt in ('-h', '--help'): usage() try: global serial import serial if not port: port = '/dev/ttyUSB0' sftp = serial.Serial(port, baudrate) sftp.write(source) while True: rxData = sftp.read(1) if rxData == 'b': print('Execute ILA') #fd = open('ila_capture.tcl') #script = fd.read() #fd.close() #tcl = tkinter.Tcl() #tcl.eval(script) #print('ILA captured!') signalTriggeredStatus = LoadTargetSignalStatus(signals, values, conditions) triggeredPercent = SignalTriggeredPercentage(signalTriggeredStatus) print('% Triggered Signals:', triggeredPercent) sftp.write(triggeredPercent) elif rxData == 's': break rxData = '' sftp.close() except Exception as e: print("ERROR:", e) if __name__ == '__main__': main()
Sample in Buffer,Sample in Window,TRIGGER,aes/cipher_key[127:0],aes/plain_text[127:0],aes/cipherkey_valid_in,aes/data_valid_in,aes/valid_out Radix - UNSIGNED,UNSIGNED,UNSIGNED,HEX,HEX,HEX,HEX,HEX 0,0,1,00000000666655550000000022221111,000000006c6b6a690000000064434241,1,1,1
package require csv package require struct::queue proc readCSV {channel {header 1} {symbol ,}} { set quote 0 set data [split [read $channel nonewline] \n] set line_count [llength $data] if {$line_count != 0} { for {append k 0} {$k < $line_count} {incr k} { set line [lindex $data $k] set quote [expr {$quote + [regexp -all \" $line]}] if {$quote % 2 == 0} { set quote 0 append row_temp $line set row_temp [split $row_temp $symbol] set col_count [llength $row_temp] for {set i 0} {$i < $col_count} {incr i} { set section [lindex $row_temp $i] set quote [expr {$quote + [regexp -all \" $section]}] if {$quote % 2 == 0} { append cell_temp $section if {[regexp {"(.*)"} $cell_temp x y]} { set cell_temp $y } lappend cell $cell_temp unset cell_temp set quote 0 } else { append cell_temp $section, } } lappend final [regsub -all {""} $cell \"] unset cell unset row_temp } else { append row_temp $line\n } } } # generate array if needed, or return $final here set row [llength $final] set column [llength [lindex $final 0]] if {$header == 1} { for {set i 0} {$i < $row} {incr i} { for {set j 0} {$j < $column} {incr j} { set csvData([lindex [lindex $final 0] $j],$i) [ lindex [lindex $final $i] $j] } } } else { for {set i 0} {$i < $row} {incr i} { for {set j 0} {$j < $column} {incr j} { set csvData($i,$j) [lindex [lindex $final $i] $j] } } } return [array get csvData] } set csv [open target_signals.csv {RDWR}] array set csvData [readCSV $csv 0] #puts $csvData(1,2) set n [array size csvData] set n [expr $n /4] #puts $n set condition "" for { set i 1} {$i < $n} {incr i} { if {$csvData($i,2) == "="} { set condition "eq$csvData($i,3)'u$csvData($i,1)" #puts $condition } if {$csvData($i,2) == "!="} { set condition "neq$csvData($i,3)'u$csvData($i,1)" #puts $condition } set_property TRIGGER_COMPARE_VALUE $condition [get_hw_probes $csvData($i,0) -of_objects [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}]] } set_property CONTROL.TRIGGER_CONDITION OR [get_hw_ilas -of_objects [get_hw_devices xc7k325t_0] -filter {CELL_NAME=~"u_ila_0"}]
import tkinter fd = open('tcltest.tcl') script = fd.read() fd.close() tcl = tkinter.Tcl() tcl.eval(script) print('Test') import subprocess p = subprocess.Popen( "tclsh tcltest.tcl", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() print(stdout) print(stderr)
signal,value,condition,length aes/valid_out,1,=,1 aes/data_valid_in,1,=,1
puts "Hello from TCL script"
#!/usr/bin/env python # Small utility to upload a file to an embedded Linux system that provides a shell # via its serial port. import sys, time, csv from getopt import GetoptError, getopt as GetOpt class SerialFTP: IO_TIME = .1 BYTES_PER_LINE = 20 def __init__(self, port=None, baudrate=None, time=None, quiet=None): self.quiet = quiet if time is not None: self.IO_TIME = time self.s = serial.Serial(port=port, baudrate=baudrate) #self.s.open() already_open = self.s.isOpen() if not already_open: self.s.open() def put(self, source, destination): data = open(source, 'rb').read() print('Data', data, 'Data') data_size = len(data) i = 0 j = 0 # Create/zero the file self.write('\necho -ne > %s\n' % destination) # Loop through all the bytes in the source file and append them to # the destination file BYTES_PER_LINE bytes at a time while i < data_size: j = 0 dpart = '' while j < self.BYTES_PER_LINE and i < data_size: dpart += '\\x%.2X' % int(data[i]) j+=1 i+=1 self.write('\necho -ne "%s" >> %s\n' % (dpart, destination)) # Show upload status if not self.quiet: print("%d \ %d" % (i, data_size)) return i def putStr(self, source, destination): data = source.encode('ascii') print('Data', data, 'Data') data_size = len(data) i = 0 j = 0 # Create/zero the file self.write('\necho -ne > %s\n' % destination) # Loop through all the bytes in the source file and append them to # the destination file BYTES_PER_LINE bytes at a time while i < data_size: j = 0 dpart = '' while j < self.BYTES_PER_LINE and i < data_size: dpart += '\\x%.2X' % int(data[i]) j+=1 i+=1 self.write('\necho -ne "%s" >> %s\n' % (dpart, destination)) # Show upload status if not self.quiet: print("%d \ %d" % (i, data_size)) return i def write(self, data): self.s.write(data.encode()) if data.endswith('\n'): # Have to give the target system time for disk/flash I/O time.sleep(self.IO_TIME) def close(self): self.s.close() class TelnetFTP(SerialFTP): def __init__(self, host, port, login=None, passwd=None, time=None, quiet=None): self.quiet = quiet if time is not None: self.IO_TIME = time self.s = telnetlib.Telnet(host, port, timeout=10) # We're not interested in matching input, just interested # in consuming it, until it stops DONT_MATCH = "\xff\xff\xff" if login: print(self.s.read_until(DONT_MATCH, 0.5)) self.s.write(login + "\n") print(self.s.read_until(DONT_MATCH, 0.5)) self.s.write(passwd + "\n") # Skip shell banner print(self.s.read_until(DONT_MATCH, self.IO_TIME)) def usage(): print('\nUsage: %s [OPTIONS]\n' % sys.argv[0]) print('\t-s, --source=<local file> Path to local file') print('\t-d, --destination=<remote file> Path to remote file') print('\t --telnet=<host> Upload via telnet instead of serial') print('\t-p, --port=<port> Serial port to use [/dev/ttyUSB0] or telnet port [23]') print('\t-b, --baudrate=<baud> Serial port baud rate [115200]') print('\t-t, --time=<seconds> Time to wait between echo commands [0.1]') print('\t --login=<username> Login name for telnet') print('\t --pass=<passwd> Password for telnet') print('\t-q, --quiet Supress status messages') print('\t-h, --help Show help') print('') sys.exit(1) def LoadTargetSignals(): with open('target_signals.csv') as f: rawdata = csv.reader(f, delimiter=',') data = list(rawdata) signals = [data[i][0] for i in range(len(data))] values = [data[i][1] for i in range(len(data))] #print(signals[0], values[0]) return signals, values def LoadTargetSignalStatus(signals, values): with open('ila_report.csv') as f: rawdata = csv.reader(f, delimiter=',') data = list(rawdata) #find target index indexCol = [] for i in range(len(signals)): signalFound = False for j in range(len(data[0])): temp = ''.join(signals[i]) #print(type(temp), type(data[0][0])) #print(temp, data[0][j], '\n') if data[0][j] == temp: indexCol.append(j) signalFound = True print('Matched found! Index:', indexCol[i], '\n') if signalFound == False: indexCol.append('NA') print(signals[i], 'not found!') #search for signal status triggeredStatus = [False] * len(indexCol) for i in range(1, len(data)): isTriggered = False for j in range(len(indexCol)): #print(type(data[i][indexCol[j]]), type(values[j])) #print('a'+data[i][indexCol[j]]+'b'+values[j]) if data[i][indexCol[j]] == values[j].strip(): print('Target triggered!') triggeredStatus[j] = True return triggeredStatus def SignalTriggeredPercentage(signalTriggeredStatus): n_signals = len(signalTriggeredStatus) n_triggered = signalTriggeredStatus.count(True) percentage = (n_triggered * 100) / n_signals return percentage def main(): host = None port = None baudrate = 115200 login = None passwd = None source = None destination = None time = None quiet = False signals, values = LoadTargetSignals() #print(signals) signalTriggeredStatus = LoadTargetSignalStatus(signals, values) triggeredPercent = SignalTriggeredPercentage(signalTriggeredStatus) print('% Triggered Signals:', triggeredPercent) try: opts, args = GetOpt(sys.argv[1:],'p:b:s:d:t:qh', ['port=', 'baudrate=', 'source=', 'destination=', 'time=', 'quiet', 'help', 'telnet=', 'login=', 'pass=']) except (GetoptError, e): print("Usage error:", e) usage() for opt, arg in opts: if opt in ('--telnet',): host = arg elif opt in ('--login',): login = arg elif opt in ('--pass',): passwd = arg elif opt in ('-p', '--port'): port = arg elif opt in ('-b', '--baudrate'): baudrate = arg elif opt in ('-s', '--source'): source = arg elif opt in ('-d', '--destination'): destination = arg elif opt in ('-t', '--time'): time = float(arg) elif opt in ('-q', '--quiet'): quiet = True elif opt in ('-h', '--help'): usage() if not source or not destination: print('Usage error: must specify -s and -d options') usage() try: if host: global telnetlib import telnetlib if not port: port = 23 print(host, port, time, quiet) sftp = TelnetFTP(host=host, port=port, login=login, passwd=passwd, time=time, quiet=quiet) else: global serial import serial if not port: port = '/dev/ttyUSB0' sftp = SerialFTP(port=port, baudrate=baudrate, time=time, quiet=quiet) if source == 'self': print('source = self') source = str(int(triggeredPercent)) #print(source) size = sftp.putStr(source, destination) else: size = sftp.put(source, destination) sftp.close() print('Uploaded %d bytes from %s to %s' % (size, source, destination)) except Exception as e: print("ERROR:", e) if __name__ == '__main__': main()
// See LICENSE.Berkeley for license details. // Author: Abraham Gonzalez, UC Berkeley // Date: 24.02.2020 // Description: Traced Instruction and Port (using in Rocket Chip based systems) package traced_instr_pkg; typedef struct packed { logic clock; logic reset; logic valid; logic [63:0] iaddr; logic [31:0] insn; logic [1:0] priv; logic exception; logic interrupt; logic [63:0] cause; logic [63:0] tval; } traced_instr_t; typedef traced_instr_t [ariane_pkg::NR_COMMIT_PORTS-1:0] trace_port_t; endpackage
// 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. // // Author: Michael Schaffner <schaffner@iis.ee.ethz.ch>, ETH Zurich // Date: 19.03.2017 // Description: Ariane Top-level wrapper to break out SV structs to logic vectors. module ariane_verilog_wrap import ariane_pkg::*; #( parameter int unsigned RASDepth = 2, parameter int unsigned BTBEntries = 32, parameter int unsigned BHTEntries = 128, // debug module base address parameter logic [63:0] DmBaseAddress = 64'h0, // swap endianess in l15 adapter parameter bit SwapEndianess = 1, // PMA configuration // idempotent region parameter int unsigned NrNonIdempotentRules = 1, parameter logic [NrMaxRules*64-1:0] NonIdempotentAddrBase = 64'h00C0000000, parameter logic [NrMaxRules*64-1:0] NonIdempotentLength = 64'hFFFFFFFFFF, // executable regions parameter int unsigned NrExecuteRegionRules = 0, parameter logic [NrMaxRules*64-1:0] ExecuteRegionAddrBase = '0, parameter logic [NrMaxRules*64-1:0] ExecuteRegionLength = '0, // cacheable regions parameter int unsigned NrCachedRegionRules = 0, parameter logic [NrMaxRules*64-1:0] CachedRegionAddrBase = '0, parameter logic [NrMaxRules*64-1:0] CachedRegionLength = '0, // PMP parameter int unsigned NrPMPEntries = 8 ) ( input clk_i, input reset_l, // this is an openpiton-specific name, do not change (hier. paths in TB use this) output spc_grst_l, // this is an openpiton-specific name, do not change (hier. paths in TB use this) // Core ID, Cluster ID and boot address are considered more or less static input [riscv::VLEN-1:0] boot_addr_i, // reset boot address input [riscv::XLEN-1:0] hart_id_i, // hart id in a multicore environment (reflected in a CSR) // Interrupt inputs input [1:0] irq_i, // level sensitive IR lines, mip & sip (async) input ipi_i, // inter-processor interrupts (async) // Timer facilities input time_irq_i, // timer interrupt in (async) input debug_req_i, // debug request (async) `ifdef PITON_ARIANE // L15 (memory side) output [$size(wt_cache_pkg::l15_req_t)-1:0] l15_req_o, input [$size(wt_cache_pkg::l15_rtrn_t)-1:0] l15_rtrn_i `else // AXI (memory side) output [$size(ariane_axi::req_t)-1:0] axi_req_o, input [$size(ariane_axi::resp_t)-1:0] axi_resp_i `endif ); // assign bitvector to packed struct and vice versa `ifdef PITON_ARIANE // L15 (memory side) wt_cache_pkg::l15_req_t l15_req; wt_cache_pkg::l15_rtrn_t l15_rtrn; assign l15_req_o = l15_req; assign l15_rtrn = l15_rtrn_i; `else ariane_axi::req_t axi_req; ariane_axi::resp_t axi_resp; assign axi_req_o = axi_req; assign axi_resp = axi_resp_i; `endif ///////////////////////////// // Core wakeup mechanism ///////////////////////////// // // this is a workaround since interrupts are not fully supported yet. // // the logic below catches the initial wake up interrupt that enables the cores. // logic wake_up_d, wake_up_q; // logic rst_n; // assign wake_up_d = wake_up_q || ((l15_rtrn.l15_returntype == wt_cache_pkg::L15_INT_RET) && l15_rtrn.l15_val); // always_ff @(posedge clk_i or negedge reset_l) begin : p_regs // if(~reset_l) begin // wake_up_q <= 0; // end else begin // wake_up_q <= wake_up_d; // end // end // // reset gate this // assign rst_n = wake_up_q & reset_l; // this is a workaround, // we basically wait for 32k cycles such that the SRAMs in openpiton can initialize // 128KB..8K cycles // 256KB..16K cycles // etc, so this should be enough for 512k per tile logic [15:0] wake_up_cnt_d, wake_up_cnt_q; logic rst_n; assign wake_up_cnt_d = (wake_up_cnt_q[$high(wake_up_cnt_q)]) ? wake_up_cnt_q : wake_up_cnt_q + 1; always_ff @(posedge clk_i or negedge reset_l) begin : p_regs if(~reset_l) begin wake_up_cnt_q <= 0; end else begin wake_up_cnt_q <= wake_up_cnt_d; end end // reset gate this assign rst_n = wake_up_cnt_q[$high(wake_up_cnt_q)] & reset_l; ///////////////////////////// // synchronizers ///////////////////////////// logic [1:0] irq; logic ipi, time_irq, debug_req; // reset synchronization synchronizer i_sync ( .clk ( clk_i ), .presyncdata ( rst_n ), .syncdata ( spc_grst_l ) ); // interrupts for (genvar k=0; k<$size(irq_i); k++) begin synchronizer i_irq_sync ( .clk ( clk_i ), .presyncdata ( irq_i[k] ), .syncdata ( irq[k] ) ); end synchronizer i_ipi_sync ( .clk ( clk_i ), .presyncdata ( ipi_i ), .syncdata ( ipi ) ); synchronizer i_timer_sync ( .clk ( clk_i ), .presyncdata ( time_irq_i ), .syncdata ( time_irq ) ); synchronizer i_debug_sync ( .clk ( clk_i ), .presyncdata ( debug_req_i ), .syncdata ( debug_req ) ); ///////////////////////////// // ariane instance ///////////////////////////// localparam ariane_pkg::ariane_cfg_t ArianeOpenPitonCfg = '{ RASDepth: RASDepth, BTBEntries: BTBEntries, BHTEntries: BHTEntries, // idempotent region NrNonIdempotentRules: NrNonIdempotentRules, NonIdempotentAddrBase: NonIdempotentAddrBase, NonIdempotentLength: NonIdempotentLength, NrExecuteRegionRules: NrExecuteRegionRules, ExecuteRegionAddrBase: ExecuteRegionAddrBase, ExecuteRegionLength: ExecuteRegionLength, // cached region NrCachedRegionRules: NrCachedRegionRules, CachedRegionAddrBase: CachedRegionAddrBase, CachedRegionLength: CachedRegionLength, // cache config Axi64BitCompliant: 1'b0, SwapEndianess: SwapEndianess, // debug DmBaseAddress: DmBaseAddress, NrPMPEntries: NrPMPEntries }; ariane #( .ArianeCfg ( ArianeOpenPitonCfg ) ) ariane ( .clk_i ( clk_i ), .rst_ni ( spc_grst_l ), .boot_addr_i ,// constant .hart_id_i ,// constant .irq_i ( irq ), .ipi_i ( ipi ), .time_irq_i ( time_irq ), .debug_req_i ( debug_req ), `ifdef PITON_ARIANE .l15_req_o ( l15_req ), .l15_rtrn_i ( l15_rtrn ) `else .axi_req_o ( axi_req ), .axi_resp_i ( axi_resp ) `endif ); endmodule // ariane_verilog_wrap
// 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. // // Author: Michael Schaffner <schaffner@iis.ee.ethz.ch>, ETH Zurich // Date: 14.11.2018 // Description: Ariane chipset for OpenPiton that includes two bootroms // (linux, baremetal, both with DTB), debug module, clint and plic. // // Note that direct system bus accesses are not yet possible due to a missing // AXI-lite br_master <-> NOC converter module. // // The address bases for the individual peripherals are defined in the // devices.xml file in OpenPiton, and should be set to // // Debug 0xfff1000000 <length 0x1000> // Boot Rom 0xfff1010000 <length 0x10000> // CLINT 0xfff1020000 <length 0xc0000> // PLIC 0xfff1100000 <length 0x4000000> // module riscv_peripherals #( parameter int unsigned DataWidth = 64, parameter int unsigned NumHarts = 1, parameter int unsigned NumSources = 1, parameter int unsigned PlicMaxPriority = 7, parameter bit SwapEndianess = 0, parameter logic [63:0] DmBase = 64'hfff1000000, parameter logic [63:0] RomBase = 64'hfff1010000, parameter logic [63:0] ClintBase = 64'hfff1020000, parameter logic [63:0] PlicBase = 64'hfff1100000 ) ( input clk_i, input rst_ni, input testmode_i, // connections to OpenPiton NoC filters // Debug/JTAG input [DataWidth-1:0] buf_ariane_debug_noc2_data_i, input buf_ariane_debug_noc2_valid_i, output ariane_debug_buf_noc2_ready_o, output [DataWidth-1:0] ariane_debug_buf_noc3_data_o, output ariane_debug_buf_noc3_valid_o, input buf_ariane_debug_noc3_ready_i, // Bootrom input [DataWidth-1:0] buf_ariane_bootrom_noc2_data_i, input buf_ariane_bootrom_noc2_valid_i, output ariane_bootrom_buf_noc2_ready_o, output [DataWidth-1:0] ariane_bootrom_buf_noc3_data_o, output ariane_bootrom_buf_noc3_valid_o, input buf_ariane_bootrom_noc3_ready_i, // CLINT input [DataWidth-1:0] buf_ariane_clint_noc2_data_i, input buf_ariane_clint_noc2_valid_i, output ariane_clint_buf_noc2_ready_o, output [DataWidth-1:0] ariane_clint_buf_noc3_data_o, output ariane_clint_buf_noc3_valid_o, input buf_ariane_clint_noc3_ready_i, // PLIC input [DataWidth-1:0] buf_ariane_plic_noc2_data_i, input buf_ariane_plic_noc2_valid_i, output ariane_plic_buf_noc2_ready_o, output [DataWidth-1:0] ariane_plic_buf_noc3_data_o, output ariane_plic_buf_noc3_valid_o, input buf_ariane_plic_noc3_ready_i, // This selects either the BM or linux bootrom input ariane_boot_sel_i, // Debug sigs to cores output ndmreset_o, // non-debug module reset output dmactive_o, // debug module is active output [NumHarts-1:0] debug_req_o, // async debug request input [NumHarts-1:0] unavailable_i, // communicate whether the hart is unavailable (e.g.: power down) // JTAG input tck_i, input tms_i, input trst_ni, input td_i, output td_o, output tdo_oe_o, // CLINT input rtc_i, // Real-time clock in (usually 32.768 kHz) output [NumHarts-1:0] timer_irq_o, // Timer interrupts output [NumHarts-1:0] ipi_o, // software interrupt (a.k.a inter-process-interrupt) // PLIC input [NumSources-1:0] irq_sources_i, input [NumSources-1:0] irq_le_i, // 0:level 1:edge output [NumHarts-1:0][1:0] irq_o // level sensitive IR lines, mip & sip (async) ); localparam int unsigned AxiIdWidth = 1; localparam int unsigned AxiAddrWidth = 64; localparam int unsigned AxiDataWidth = 64; localparam int unsigned AxiUserWidth = 1; ///////////////////////////// // Debug module and JTAG ///////////////////////////// logic debug_req_valid; logic debug_req_ready; logic debug_resp_valid; logic debug_resp_ready; dm::dmi_req_t debug_req; dm::dmi_resp_t debug_resp; `ifdef RISCV_FESVR_SIM initial begin $display("[INFO] instantiating FESVR DTM in simulation."); end // SiFive's SimDTM Module // Converts to DPI calls logic [31:0] sim_exit; // TODO: wire this up in the testbench logic [1:0] debug_req_bits_op; assign dmi_req.op = dm::dtm_op_t'(debug_req_bits_op); SimDTM i_SimDTM ( .clk ( clk_i ), .reset ( ~rst_ni ), .debug_req_valid ( debug_req_valid ), .debug_req_ready ( debug_req_ready ), .debug_req_bits_addr ( debug_req.addr ), .debug_req_bits_op ( debug_req_bits_op ), .debug_req_bits_data ( debug_req.data ), .debug_resp_valid ( debug_resp_valid ), .debug_resp_ready ( debug_resp_ready ), .debug_resp_bits_resp ( debug_resp.resp ), .debug_resp_bits_data ( debug_resp.data ), .exit ( sim_exit ) ); `else // RISCV_FESVR_SIM logic tck, tms, trst_n, tdi, tdo, tdo_oe; dmi_jtag i_dmi_jtag ( .clk_i , .rst_ni , .testmode_i , .dmi_req_o ( debug_req ), .dmi_req_valid_o ( debug_req_valid ), .dmi_req_ready_i ( debug_req_ready ), .dmi_resp_i ( debug_resp ), .dmi_resp_ready_o ( debug_resp_ready ), .dmi_resp_valid_i ( debug_resp_valid ), .dmi_rst_no ( ), // not connected .tck_i ( tck ), .tms_i ( tms ), .trst_ni ( trst_n ), .td_i ( tdi ), .td_o ( tdo ), .tdo_oe_o ( tdo_oe ) ); `ifdef RISCV_JTAG_SIM initial begin $display("[INFO] instantiating JTAG DTM in simulation."); end // SiFive's SimJTAG Module // Converts to DPI calls logic [31:0] sim_exit; // TODO: wire this up in the testbench SimJTAG i_SimJTAG ( .clock ( clk_i ), .reset ( ~rst_ni ), .enable ( jtag_enable[0] ), .init_done ( init_done ), .jtag_TCK ( tck ), .jtag_TMS ( tms ), .jtag_TDI ( trst_n ), .jtag_TRSTn ( td ), .jtag_TDO_data ( td ), .jtag_TDO_driven ( tdo_oe ), .exit ( sim_exit ) ); assign td_o = 1'b0 ; assign tdo_oe_o = 1'b0 ; `else // RISCV_JTAG_SIM assign tck = tck_i ; assign tms = tms_i ; assign trst_n = trst_ni ; assign tdi = td_i ; assign td_o = tdo ; assign tdo_oe_o = tdo_oe ; `endif // RISCV_JTAG_SIM `endif // RISCV_FESVR_SIM logic dm_slave_req; logic dm_slave_we; logic [64-1:0] dm_slave_addr; logic [64/8-1:0] dm_slave_be; logic [64-1:0] dm_slave_wdata; logic [64-1:0] dm_slave_rdata; logic dm_master_req; logic [64-1:0] dm_master_add; logic dm_master_we; logic [64-1:0] dm_master_wdata; logic [64/8-1:0] dm_master_be; logic dm_master_gnt; logic dm_master_r_valid; logic [64-1:0] dm_master_r_rdata; // debug module dm_top #( .NrHarts ( NumHarts ), .BusWidth ( AxiDataWidth ), .SelectableHarts ( {NumHarts{1'b1}} ) ) i_dm_top ( .clk_i , .rst_ni , // PoR .testmode_i , .ndmreset_o , .dmactive_o , // active debug session .debug_req_o , .unavailable_i , .hartinfo_i ( {NumHarts{ariane_pkg::DebugHartInfo}} ), .slave_req_i ( dm_slave_req ), .slave_we_i ( dm_slave_we ), .slave_addr_i ( dm_slave_addr ), .slave_be_i ( dm_slave_be ), .slave_wdata_i ( dm_slave_wdata ), .slave_rdata_o ( dm_slave_rdata ), .master_req_o ( dm_master_req ), .master_add_o ( dm_master_add ), .master_we_o ( dm_master_we ), .master_wdata_o ( dm_master_wdata ), .master_be_o ( dm_master_be ), .master_gnt_i ( dm_master_gnt ), .master_r_valid_i ( dm_master_r_valid ), .master_r_rdata_i ( dm_master_r_rdata ), .dmi_rst_ni ( rst_ni ), .dmi_req_valid_i ( debug_req_valid ), .dmi_req_ready_o ( debug_req_ready ), .dmi_req_i ( debug_req ), .dmi_resp_valid_o ( debug_resp_valid ), .dmi_resp_ready_i ( debug_resp_ready ), .dmi_resp_o ( debug_resp ) ); AXI_BUS #( .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_ID_WIDTH ( AxiIdWidth ), .AXI_USER_WIDTH ( AxiUserWidth ) ) dm_master(); axi2mem #( .AXI_ID_WIDTH ( AxiIdWidth ), .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_USER_WIDTH ( AxiUserWidth ) ) i_dm_axi2mem ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .slave ( dm_master ), .req_o ( dm_slave_req ), .we_o ( dm_slave_we ), .addr_o ( dm_slave_addr ), .be_o ( dm_slave_be ), .data_o ( dm_slave_wdata ), .data_i ( dm_slave_rdata ) ); noc_axilite_bridge #( .SLAVE_RESP_BYTEWIDTH ( 8 ), .SWAP_ENDIANESS ( SwapEndianess ) ) i_debug_axilite_bridge ( .clk ( clk_i ), .rst ( ~rst_ni ), // to/from NOC .splitter_bridge_val ( buf_ariane_debug_noc2_valid_i ), .splitter_bridge_data ( buf_ariane_debug_noc2_data_i ), .bridge_splitter_rdy ( ariane_debug_buf_noc2_ready_o ), .bridge_splitter_val ( ariane_debug_buf_noc3_valid_o ), .bridge_splitter_data ( ariane_debug_buf_noc3_data_o ), .splitter_bridge_rdy ( buf_ariane_debug_noc3_ready_i ), //axi lite signals //write address channel .m_axi_awaddr ( dm_master.aw_addr ), .m_axi_awvalid ( dm_master.aw_valid ), .m_axi_awready ( dm_master.aw_ready ), //write data channel .m_axi_wdata ( dm_master.w_data ), .m_axi_wstrb ( dm_master.w_strb ), .m_axi_wvalid ( dm_master.w_valid ), .m_axi_wready ( dm_master.w_ready ), //read address channel .m_axi_araddr ( dm_master.ar_addr ), .m_axi_arvalid ( dm_master.ar_valid ), .m_axi_arready ( dm_master.ar_ready ), //read data channel .m_axi_rdata ( dm_master.r_data ), .m_axi_rresp ( dm_master.r_resp ), .m_axi_rvalid ( dm_master.r_valid ), .m_axi_rready ( dm_master.r_ready ), //write response channel .m_axi_bresp ( dm_master.b_resp ), .m_axi_bvalid ( dm_master.b_valid ), .m_axi_bready ( dm_master.b_ready ), // non-axi-lite signals .w_reqbuf_size ( ), .r_reqbuf_size ( ) ); // tie off system bus accesses (not supported yet due to // missing AXI-lite br_master <-> NOC converter) assign dm_master_gnt = '0; assign dm_master_r_valid = '0; assign dm_master_r_rdata = '0; // tie off signals not used by AXI-lite assign dm_master.aw_id = '0; assign dm_master.aw_len = '0; assign dm_master.aw_size = 3'b11;// 8byte assign dm_master.aw_burst = '0; assign dm_master.aw_lock = '0; assign dm_master.aw_cache = '0; assign dm_master.aw_prot = '0; assign dm_master.aw_qos = '0; assign dm_master.aw_region = '0; assign dm_master.aw_atop = '0; assign dm_master.w_last = 1'b1; assign dm_master.ar_id = '0; assign dm_master.ar_len = '0; assign dm_master.ar_size = 3'b11;// 8byte assign dm_master.ar_burst = '0; assign dm_master.ar_lock = '0; assign dm_master.ar_cache = '0; assign dm_master.ar_prot = '0; assign dm_master.ar_qos = '0; assign dm_master.ar_region = '0; ///////////////////////////// // Bootrom ///////////////////////////// logic rom_req; logic [AxiAddrWidth-1:0] rom_addr; logic [AxiDataWidth-1:0] rom_rdata, rom_rdata_bm, rom_rdata_linux; AXI_BUS #( .AXI_ID_WIDTH ( AxiIdWidth ), .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_USER_WIDTH ( AxiUserWidth ) ) br_master(); axi2mem #( .AXI_ID_WIDTH ( AxiIdWidth ), .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_USER_WIDTH ( AxiUserWidth ) ) i_axi2rom ( .clk_i , .rst_ni , .slave ( br_master ), .req_o ( rom_req ), .we_o ( ), .addr_o ( rom_addr ), .be_o ( ), .data_o ( ), .data_i ( rom_rdata ) ); bootrom i_bootrom_bm ( .clk_i , .req_i ( rom_req ), .addr_i ( rom_addr ), .rdata_o ( rom_rdata_bm ) ); bootrom_linux i_bootrom_linux ( .clk_i , .req_i ( rom_req ), .addr_i ( rom_addr ), .rdata_o ( rom_rdata_linux ) ); // we want to run in baremetal mode when using pitonstream assign rom_rdata = (ariane_boot_sel_i) ? rom_rdata_bm : rom_rdata_linux; noc_axilite_bridge #( .SLAVE_RESP_BYTEWIDTH ( 8 ), .SWAP_ENDIANESS ( SwapEndianess ) ) i_bootrom_axilite_bridge ( .clk ( clk_i ), .rst ( ~rst_ni ), // to/from NOC .splitter_bridge_val ( buf_ariane_bootrom_noc2_valid_i ), .splitter_bridge_data ( buf_ariane_bootrom_noc2_data_i ), .bridge_splitter_rdy ( ariane_bootrom_buf_noc2_ready_o ), .bridge_splitter_val ( ariane_bootrom_buf_noc3_valid_o ), .bridge_splitter_data ( ariane_bootrom_buf_noc3_data_o ), .splitter_bridge_rdy ( buf_ariane_bootrom_noc3_ready_i ), //axi lite signals //write address channel .m_axi_awaddr ( br_master.aw_addr ), .m_axi_awvalid ( br_master.aw_valid ), .m_axi_awready ( br_master.aw_ready ), //write data channel .m_axi_wdata ( br_master.w_data ), .m_axi_wstrb ( br_master.w_strb ), .m_axi_wvalid ( br_master.w_valid ), .m_axi_wready ( br_master.w_ready ), //read address channel .m_axi_araddr ( br_master.ar_addr ), .m_axi_arvalid ( br_master.ar_valid ), .m_axi_arready ( br_master.ar_ready ), //read data channel .m_axi_rdata ( br_master.r_data ), .m_axi_rresp ( br_master.r_resp ), .m_axi_rvalid ( br_master.r_valid ), .m_axi_rready ( br_master.r_ready ), //write response channel .m_axi_bresp ( br_master.b_resp ), .m_axi_bvalid ( br_master.b_valid ), .m_axi_bready ( br_master.b_ready ), // non-axi-lite signals .w_reqbuf_size ( ), .r_reqbuf_size ( ) ); // tie off signals not used by AXI-lite assign br_master.aw_id = '0; assign br_master.aw_len = '0; assign br_master.aw_size = 3'b11;// 8byte assign br_master.aw_burst = '0; assign br_master.aw_lock = '0; assign br_master.aw_cache = '0; assign br_master.aw_prot = '0; assign br_master.aw_qos = '0; assign br_master.aw_region = '0; assign br_master.aw_atop = '0; assign br_master.w_last = 1'b1; assign br_master.ar_id = '0; assign br_master.ar_len = '0; assign br_master.ar_size = 3'b11;// 8byte assign br_master.ar_burst = '0; assign br_master.ar_lock = '0; assign br_master.ar_cache = '0; assign br_master.ar_prot = '0; assign br_master.ar_qos = '0; assign br_master.ar_region = '0; ///////////////////////////// // CLINT ///////////////////////////// ariane_axi::req_t clint_axi_req; ariane_axi::resp_t clint_axi_resp; clint #( .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_ID_WIDTH ( AxiIdWidth ), .NR_CORES ( NumHarts ) ) i_clint ( .clk_i , .rst_ni , .testmode_i , .axi_req_i ( clint_axi_req ), .axi_resp_o ( clint_axi_resp ), .rtc_i , .timer_irq_o , .ipi_o ); noc_axilite_bridge #( .SLAVE_RESP_BYTEWIDTH ( 8 ), .SWAP_ENDIANESS ( SwapEndianess ) ) i_clint_axilite_bridge ( .clk ( clk_i ), .rst ( ~rst_ni ), // to/from NOC .splitter_bridge_val ( buf_ariane_clint_noc2_valid_i ), .splitter_bridge_data ( buf_ariane_clint_noc2_data_i ), .bridge_splitter_rdy ( ariane_clint_buf_noc2_ready_o ), .bridge_splitter_val ( ariane_clint_buf_noc3_valid_o ), .bridge_splitter_data ( ariane_clint_buf_noc3_data_o ), .splitter_bridge_rdy ( buf_ariane_clint_noc3_ready_i ), //axi lite signals //write address channel .m_axi_awaddr ( clint_axi_req.aw.addr ), .m_axi_awvalid ( clint_axi_req.aw_valid ), .m_axi_awready ( clint_axi_resp.aw_ready ), //write data channel .m_axi_wdata ( clint_axi_req.w.data ), .m_axi_wstrb ( clint_axi_req.w.strb ), .m_axi_wvalid ( clint_axi_req.w_valid ), .m_axi_wready ( clint_axi_resp.w_ready ), //read address channel .m_axi_araddr ( clint_axi_req.ar.addr ), .m_axi_arvalid ( clint_axi_req.ar_valid ), .m_axi_arready ( clint_axi_resp.ar_ready ), //read data channel .m_axi_rdata ( clint_axi_resp.r.data ), .m_axi_rresp ( clint_axi_resp.r.resp ), .m_axi_rvalid ( clint_axi_resp.r_valid ), .m_axi_rready ( clint_axi_req.r_ready ), //write response channel .m_axi_bresp ( clint_axi_resp.b.resp ), .m_axi_bvalid ( clint_axi_resp.b_valid ), .m_axi_bready ( clint_axi_req.b_ready ), // non-axi-lite signals .w_reqbuf_size ( ), .r_reqbuf_size ( ) ); // tie off signals not used by AXI-lite assign clint_axi_req.aw.id = '0; assign clint_axi_req.aw.len = '0; assign clint_axi_req.aw.size = 3'b11;// 8byte assign clint_axi_req.aw.burst = '0; assign clint_axi_req.aw.lock = '0; assign clint_axi_req.aw.cache = '0; assign clint_axi_req.aw.prot = '0; assign clint_axi_req.aw.qos = '0; assign clint_axi_req.aw.region = '0; assign clint_axi_req.aw.atop = '0; assign clint_axi_req.w.last = 1'b1; assign clint_axi_req.ar.id = '0; assign clint_axi_req.ar.len = '0; assign clint_axi_req.ar.size = 3'b11;// 8byte assign clint_axi_req.ar.burst = '0; assign clint_axi_req.ar.lock = '0; assign clint_axi_req.ar.cache = '0; assign clint_axi_req.ar.prot = '0; assign clint_axi_req.ar.qos = '0; assign clint_axi_req.ar.region = '0; ///////////////////////////// // PLIC ///////////////////////////// AXI_BUS #( .AXI_ID_WIDTH ( AxiIdWidth ), .AXI_ADDR_WIDTH ( AxiAddrWidth ), .AXI_DATA_WIDTH ( AxiDataWidth ), .AXI_USER_WIDTH ( AxiUserWidth ) ) plic_master(); noc_axilite_bridge #( // this enables variable width accesses // note that the accesses are still 64bit, but the // write-enables are generated according to the access size .SLAVE_RESP_BYTEWIDTH ( 0 ), .SWAP_ENDIANESS ( SwapEndianess ), // this disables shifting of unaligned read data .ALIGN_RDATA ( 0 ) ) i_plic_axilite_bridge ( .clk ( clk_i ), .rst ( ~rst_ni ), // to/from NOC .splitter_bridge_val ( buf_ariane_plic_noc2_valid_i ), .splitter_bridge_data ( buf_ariane_plic_noc2_data_i ), .bridge_splitter_rdy ( ariane_plic_buf_noc2_ready_o ), .bridge_splitter_val ( ariane_plic_buf_noc3_valid_o ), .bridge_splitter_data ( ariane_plic_buf_noc3_data_o ), .splitter_bridge_rdy ( buf_ariane_plic_noc3_ready_i ), //axi lite signals //write address channel .m_axi_awaddr ( plic_master.aw_addr ), .m_axi_awvalid ( plic_master.aw_valid ), .m_axi_awready ( plic_master.aw_ready ), //write data channel .m_axi_wdata ( plic_master.w_data ), .m_axi_wstrb ( plic_master.w_strb ), .m_axi_wvalid ( plic_master.w_valid ), .m_axi_wready ( plic_master.w_ready ), //read address channel .m_axi_araddr ( plic_master.ar_addr ), .m_axi_arvalid ( plic_master.ar_valid ), .m_axi_arready ( plic_master.ar_ready ), //read data channel .m_axi_rdata ( plic_master.r_data ), .m_axi_rresp ( plic_master.r_resp ), .m_axi_rvalid ( plic_master.r_valid ), .m_axi_rready ( plic_master.r_ready ), //write response channel .m_axi_bresp ( plic_master.b_resp ), .m_axi_bvalid ( plic_master.b_valid ), .m_axi_bready ( plic_master.b_ready ), // non-axi-lite signals .w_reqbuf_size ( plic_master.aw_size ), .r_reqbuf_size ( plic_master.ar_size ) ); // tie off signals not used by AXI-lite assign plic_master.aw_id = '0; assign plic_master.aw_len = '0; assign plic_master.aw_burst = '0; assign plic_master.aw_lock = '0; assign plic_master.aw_cache = '0; assign plic_master.aw_prot = '0; assign plic_master.aw_qos = '0; assign plic_master.aw_region = '0; assign plic_master.aw_atop = '0; assign plic_master.w_last = 1'b1; assign plic_master.ar_id = '0; assign plic_master.ar_len = '0; assign plic_master.ar_burst = '0; assign plic_master.ar_lock = '0; assign plic_master.ar_cache = '0; assign plic_master.ar_prot = '0; assign plic_master.ar_qos = '0; assign plic_master.ar_region = '0; reg_intf::reg_intf_resp_d32 plic_resp; reg_intf::reg_intf_req_a32_d32 plic_req; enum logic [2:0] {Idle, WriteSecond, ReadSecond, WriteResp, ReadResp} state_d, state_q; logic [31:0] rword_d, rword_q; // register read data assign rword_d = (plic_req.valid && !plic_req.write) ? plic_resp.rdata : rword_q; assign plic_master.r_data = {plic_resp.rdata, rword_q}; always_ff @(posedge clk_i or negedge rst_ni) begin : p_plic_regs if (!rst_ni) begin state_q <= Idle; rword_q <= '0; end else begin state_q <= state_d; rword_q <= rword_d; end end // this is a simplified AXI statemachine, since the // W and AW requests always arrive at the same time here always_comb begin : p_plic_if automatic logic [31:0] waddr, raddr; // subtract the base offset (truncated to 32 bits) waddr = plic_master.aw_addr[31:0] - 32'(PlicBase) + 32'hc000000; raddr = plic_master.ar_addr[31:0] - 32'(PlicBase) + 32'hc000000; // AXI-lite plic_master.aw_ready = plic_resp.ready; plic_master.w_ready = plic_resp.ready; plic_master.ar_ready = plic_resp.ready; plic_master.r_valid = 1'b0; plic_master.r_resp = '0; plic_master.b_valid = 1'b0; plic_master.b_resp = '0; // PLIC plic_req.valid = 1'b0; plic_req.wstrb = '0; plic_req.write = 1'b0; plic_req.wdata = plic_master.w_data[31:0]; plic_req.addr = waddr; // default state_d = state_q; unique case (state_q) Idle: begin if (plic_master.w_valid && plic_master.aw_valid && plic_resp.ready) begin plic_req.valid = 1'b1; plic_req.write = plic_master.w_strb[3:0]; plic_req.wstrb = '1; // this is a 64bit write, need to write second 32bit chunk in second cycle if (plic_master.aw_size == 3'b11) begin state_d = WriteSecond; end else begin state_d = WriteResp; end end else if (plic_master.ar_valid && plic_resp.ready) begin plic_req.valid = 1'b1; plic_req.addr = raddr; // this is a 64bit read, need to read second 32bit chunk in second cycle if (plic_master.ar_size == 3'b11) begin state_d = ReadSecond; end else begin state_d = ReadResp; end end end // write high word WriteSecond: begin plic_master.aw_ready = 1'b0; plic_master.w_ready = 1'b0; plic_master.ar_ready = 1'b0; plic_req.addr = waddr + 32'h4; plic_req.wdata = plic_master.w_data[63:32]; if (plic_resp.ready && plic_master.b_ready) begin plic_req.valid = 1'b1; plic_req.write = 1'b1; plic_req.wstrb = '1; plic_master.b_valid = 1'b1; state_d = Idle; end end // read high word ReadSecond: begin plic_master.aw_ready = 1'b0; plic_master.w_ready = 1'b0; plic_master.ar_ready = 1'b0; plic_req.addr = raddr + 32'h4; if (plic_resp.ready && plic_master.r_ready) begin plic_req.valid = 1'b1; plic_master.r_valid = 1'b1; state_d = Idle; end end WriteResp: begin plic_master.aw_ready = 1'b0; plic_master.w_ready = 1'b0; plic_master.ar_ready = 1'b0; if (plic_master.b_ready) begin plic_master.b_valid = 1'b1; state_d = Idle; end end ReadResp: begin plic_master.aw_ready = 1'b0; plic_master.w_ready = 1'b0; plic_master.ar_ready = 1'b0; if (plic_master.r_ready) begin plic_master.r_valid = 1'b1; state_d = Idle; end end default: state_d = Idle; endcase end plic_top #( .N_SOURCE ( NumSources ), .N_TARGET ( 2*NumHarts ), .MAX_PRIO ( PlicMaxPriority ) ) i_plic ( .clk_i, .rst_ni, .req_i ( plic_req ), .resp_o ( plic_resp ), .le_i ( irq_le_i ), // 0:level 1:edge .irq_sources_i, // already synchronized .eip_targets_o ( irq_o ) ); endmodule // riscv_peripherals
*.elf *.img *.dtb *.sv
*.elf *.img *.dtb *.sv *.h
.section .text.start, "ax", @progbits .globl _start _start: # bootrom.sv need to be functional in 64 and 32 bits, # li s0, DRAM_BASE creates instructions not compatible with both # versions. That's why we have replaced it by li and slli instructions # to generates code compatible with both versions. li s0, 1 slli s0, s0, 31 csrr a0, mhartid la a1, _dtb jr s0 .section .text.hang, "ax", @progbits .globl _hang _hang: csrr a0, mhartid la a1, _dtb 1: wfi j 1b .section .rodata.dtb, "a", @progbits .globl _dtb .align 5, 0 _dtb: .incbin "ariane.dtb"
#!/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 RomSize = $size; const logic [RomSize-1:0][63:0] 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 assign rdata_o = (addr_q < RomSize) ? mem[addr_q] : '0; 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))
SECTIONS { ROM_BASE = 0x10000; /* ... but actually position independent */ . = ROM_BASE; .text.start : { *(.text.start) } . = ROM_BASE + 0x40; .text.hang : { *(.text.hang) } . = ROM_BASE + 0x80; .rodata.dtb : { *(.rodata.dtb) } }
bootrom_img = bootrom.img bootrom.sv RISCV_GCC?=riscv64-unknown-elf-gcc RISCV_OBJCOPY?=riscv64-unknown-elf-objcopy DTB=ariane.dtb PYTHON=python all: $(bootrom_img) %.img: %.bin dd if=$< of=$@ bs=128 %.bin: %.elf $(RISCV_OBJCOPY) -O binary $< $@ %.elf: %.S linker.ld $(DTB) $(RISCV_GCC) -Tlinker.ld -march=rv32i -mabi=ilp32 $< -nostdlib -static -Wl,--no-gc-sections -o $@ %.dtb: %.dts dtc -I dts $< -O dtb -o $@ %.sv: %.img $(PYTHON) ./gen_rom.py $< clean: rm -f $(bootrom_img) $(DTB)
*.bin *.elf *.img *.dtb *.sv
#!/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 RomSize = $size; const logic [RomSize-1:0][63:0] 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 assign rdata_o = (addr_q < RomSize) ? mem[addr_q] : '0; 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))
ENTRY(main) SECTIONS { ROM_BASE = 0x10000; /* ... but actually position independent */ . = ROM_BASE; .text.init : { *(.text.init) } .text : ALIGN(0x100) { _TEXT_START_ = .; *(.text) _TEXT_END_ = .; } .data : ALIGN(0x100) { _DATA_START_ = .; *(.data) _DATA_END_ = .; } PROVIDE(_data = ADDR(.data)); PROVIDE(_data_lma = LOADADDR(.data)); PROVIDE(_edata = .); .bss : ALIGN(0x100) { _BSS_START_ = .; *(.bss) _BSS_END_ = .; } .rodata : ALIGN(0x100) { _RODATA_START_ = .; *(.rodata) *(.dtb*) *(.rodata*) _RODATA_END_ = .; } }
UART_FREQ ?= 30000000 MAX_HARTS ?= 1 CROSSCOMPILE ?= riscv64-unknown-elf- CC = ${CROSSCOMPILE}gcc PYTHON=python CFLAGS = -DMAX_HARTS=$(MAX_HARTS) -DUART_FREQ=$(UART_FREQ) -Os -ggdb -march=rv64imac -mabi=lp64 -Wall -mcmodel=medany -mexplicit-relocs CCASFLAGS = -mcmodel=medany -mexplicit-relocs LDFLAGS = -nostdlib -nodefaultlibs -nostartfiles INCLUDES = -I./ -I./src SRCS_C = src/main.c src/uart.c src/spi.c src/sd.c src/gpt.c SRCS_ASM = startup.S OBJS_C = $(SRCS_C:.c=.o) OBJS_S = $(SRCS_ASM:.S=.o) MAIN = bootrom_linux.elf MAIN_BIN = $(MAIN:.elf=.bin) MAIN_IMG = $(MAIN:.elf=.img) MAIN_SV = $(MAIN:.elf=.sv) #.PHONY: clean $(MAIN): ariane.dtb $(OBJS_C) $(OBJS_S) linker.lds $(CC) $(CFLAGS) $(LDFLAGS) $(INCLUDES) -Tlinker.lds $(OBJS_S) $(OBJS_C) -o $(MAIN) @echo "LD >= $(MAIN)" %.img: %.bin dd if=$< of=$@ bs=128 %.bin: %.elf $(CROSSCOMPILE)objcopy -O binary $< $@ %.o: %.c @echo "MAX_HARTS = $(MAX_HARTS)" @$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@ @echo "CC <= $<" %.o: %.S @echo "MAX_HARTS = $(MAX_HARTS)" @$(CC) $(CFLAGS) $(CCASFLAGS) $(INCLUDES) -c $< -o $@ @echo "CC <= $<" %.dtb: %.dts dtc -I dts $< -O dtb -o $@ %.sv: %.img $(PYTHON) ./gen_rom.py $< @echo "PYTHON >= $(MAIN_SV)" clean: $(RM) $(OBJS_C) $(OBJS_S) $(MAIN) $(MAIN_BIN) $(MAIN_IMG) *.dtb all: $(MAIN) $(MAIN_BIN) $(MAIN_IMG) $(MAIN_SV) @echo "zero stage bootloader has been compiled!" # DO NOT DELETE THIS LINE -- make depend needs it
#define DRAM_BASE 0x80000000 #define DRAM_SIZE 0x4000000
# First Stage Bootloader for Ariane ## How-To prepare SD card The bootloader requires a GPT partition table so you first have to create one with gdisk. ```bash $ sudo fdisk -l # search for the corresponding disk label (e.g. /dev/sdb) $ sudo sgdisk --clear --new=1:2048:67583 --new=2 --typecode=1:3000 --typecode=2:8300 /dev/sdb # create a new gpt partition table and two partitions: 1st partition: 32mb (ONIE boot), second partition: rest (Linux root) ``` Now you have to make the linux kernel with the [ariane-sdk](https://github.com/pulp-platform/ariane-sdk): ```bash $ cd /path/to/ariane-sdk $ make bbl.bin # make the linux kernel with the ariane-sdk repository ``` Then the bbl+linux kernel image can get copied to the sd card with `dd`. __Careful:__ use the same disk label that you found before with `fdisk -l` but with a 1 in the end, e.g. `/dev/sdb` -> `/dev/sdb1`. ```bash $ sudo dd if=bbl.bin of=/dev/sdb1 status=progress oflag=sync bs=1M ``` ## Features - uart - spi - sd card reading - GPT partitions ## TODO - file systems (fat16/fat32) - elf loader - zeroing of the `.bss` section of the second stage boot loader
# start sequence of the bootloader # # #include <smp.h> #define DRAM_BASE 0x80000000 .section .text.init .option norvc .globl _prog_start _prog_start: smp_pause(s1, s2) li sp, 0x84000000 call main smp_resume(s1, s2) csrr a0, mhartid la a1, _dtb li s1, DRAM_BASE jr s1 .section .dtb .globl _dtb .align 4, 0 _dtb: .incbin "ariane.dtb"
#include "gpt.h" #include "sd.h" #include "uart.h" #include <stddef.h> int gpt_find_boot_partition(uint8_t* dest, uint32_t size) { int ret = init_sd(); if (ret != 0) { print_uart("could not initialize sd... exiting\r\n"); return -1; } print_uart("sd initialized!\r\n"); // load LBA1 size_t block_size = 512; uint8_t lba1_buf[block_size]; int res = sd_copy(lba1_buf, 1, 1); if (res != 0) { print_uart("SD card failed!\r\n"); print_uart("sd copy return value: "); print_uart_addr(res); print_uart("\r\n"); return -2; } gpt_pth_t *lba1 = (gpt_pth_t *)lba1_buf; print_uart("gpt partition table header:"); print_uart("\r\n\tsignature:\t"); print_uart_addr(lba1->signature); print_uart("\r\n\trevision:\t"); print_uart_int(lba1->revision); print_uart("\r\n\tsize:\t\t"); print_uart_int(lba1->header_size); print_uart("\r\n\tcrc_header:\t"); print_uart_int(lba1->crc_header); print_uart("\r\n\treserved:\t"); print_uart_int(lba1->reserved); print_uart("\r\n\tcurrent lba:\t"); print_uart_addr(lba1->current_lba); print_uart("\r\n\tbackup lda:\t"); print_uart_addr(lba1->backup_lba); print_uart("\r\n\tpartition entries lba: \t"); print_uart_addr(lba1->partition_entries_lba); print_uart("\r\n\tnumber partition entries:\t"); print_uart_int(lba1->nr_partition_entries); print_uart("\r\n\tsize partition entries: \t"); print_uart_int(lba1->size_partition_entry); print_uart("\r\n"); uint8_t lba2_buf[block_size]; res = sd_copy(lba2_buf, lba1->partition_entries_lba, 1); if (res != 0) { print_uart("SD card failed!\r\n"); print_uart("sd copy return value: "); print_uart_addr(res); print_uart("\r\n"); return -2; } for (int i = 0; i < 4; i++) { partition_entries_t *part_entry = (partition_entries_t *)(lba2_buf + (i * 128)); print_uart("gpt partition entry "); print_uart_byte(i); print_uart("\r\n\tpartition type guid:\t"); for (int j = 0; j < 16; j++) print_uart_byte(part_entry->partition_type_guid[j]); print_uart("\r\n\tpartition guid: \t"); for (int j = 0; j < 16; j++) print_uart_byte(part_entry->partition_guid[j]); print_uart("\r\n\tfirst lba:\t"); print_uart_addr(part_entry->first_lba); print_uart("\r\n\tlast lba:\t"); print_uart_addr(part_entry->last_lba); print_uart("\r\n\tattributes:\t"); print_uart_addr(part_entry->attributes); print_uart("\r\n\tname:\t"); for (int j = 0; j < 72; j++) print_uart_byte(part_entry->name[j]); print_uart("\r\n"); } partition_entries_t *boot = (partition_entries_t *)(lba2_buf); print_uart("copying boot image "); print_uart("\r\n"); res = sd_copy(dest, boot->first_lba, boot->last_lba - boot->first_lba + 1); if (res != 0) { print_uart("SD card failed!\r\n"); print_uart("sd copy return value: "); print_uart_addr(res); print_uart("\r\n"); return -2; } print_uart(" done!\r\n"); return 0; }
#pragma once #include <stdint.h> // LBA 0: Protective MBR // ignored here // Partition Table Header (LBA 1) typedef struct gpt_pth { uint64_t signature; uint32_t revision; uint32_t header_size; //! little endian, usually 0x5c = 92 uint32_t crc_header; uint32_t reserved; //! must be 0 uint64_t current_lba; uint64_t backup_lba; uint64_t first_usable_lba; uint64_t last_usable_lba; uint8_t disk_guid[16]; uint64_t partition_entries_lba; uint32_t nr_partition_entries; uint32_t size_partition_entry; //! usually 0x80 = 128 uint32_t crc_partition_entry; } gpt_pth_t; // Partition Entries (LBA 2-33) typedef struct partition_entries { uint8_t partition_type_guid[16]; uint8_t partition_guid[16]; uint64_t first_lba; uint64_t last_lba; //! inclusive uint64_t attributes; uint8_t name[72]; //! utf16 encoded } partition_entries_t; // Find boot partition and load it to the destination int gpt_find_boot_partition(uint8_t* dest, uint32_t size);
#include "uart.h" #include "spi.h" #include "sd.h" #include "gpt.h" #include "info.h" int main() { init_uart(UART_FREQ, 115200); print_uart(info); print_uart("sd initialized!\r\n"); int res = gpt_find_boot_partition((uint8_t *)0x80000000UL, 2 * 16384); return 0; } void handle_trap(void) { // print_uart("trap\r\n"); }
#include "sd.h" #include "uart.h" #ifndef PITON_SD_BASE_ADDR #define PITON_SD_BASE_ADDR 0xf000000000L #endif #ifndef PITON_SD_LENGTH #define PITON_SD_LENGTH 0xff0300000L #endif int init_sd() { print_uart("initializing SD... \r\n"); return 0; } int sd_copy(void *dst, uint32_t src_lba, uint32_t size) { char buf[100]; uint64_t raw_addr = PITON_SD_BASE_ADDR; raw_addr += ((uint64_t)src_lba) << 9; uint32_t num_chars = 0; uint64_t * addr = (uint64_t *)raw_addr; volatile uint64_t * p = (uint64_t *)dst; for (uint32_t blk = 0; blk < size; blk++) { if(blk % 100 == 0) { for(uint32_t k=0; k<num_chars; k++) { print_uart("\b"); } num_chars =print_uart("copying block "); num_chars+=print_uart_dec(blk, 1); num_chars+=print_uart(" of "); num_chars+=print_uart_dec(size, 1); num_chars+=print_uart(" blocks ("); num_chars+=print_uart_dec((blk*100)/size, 1); num_chars+=print_uart(" %)"); } for (uint32_t offset = 0; offset < 64; offset++) { *(p++) = *(addr++); } } print_uart("\r\n"); return 0; }
#pragma once #include <stdint.h> #define SD_CMD_STOP_TRANSMISSION 12 #define SD_CMD_READ_BLOCK_MULTIPLE 18 #define SD_DATA_TOKEN 0xfe #define SD_COPY_ERROR_CMD18 -1 #define SD_COPY_ERROR_CMD18_CRC -2 // errors #define SD_INIT_ERROR_CMD0 -1 #define SD_INIT_ERROR_CMD8 -2 #define SD_INIT_ERROR_ACMD41 -3 int init_sd(); void put_sdcard_spi_mode(); int sd_copy(void *dst, uint32_t src_lba, uint32_t size);
#pragma once // The hart that non-SMP tests should run on #ifndef NONSMP_HART #define NONSMP_HART 0 #endif // The maximum number of HARTs this code supports //#define CLINT_CTRL_ADDR 0xFFF1020000 // Barrier on the cacheline above the stack pointer #define SMP_BARRIER_ADDR (0x84000000 + 64) #ifndef MAX_HARTS #define MAX_HARTS 2 #endif //#define CLINT_END_HART_IPI CLINT_CTRL_ADDR + (MAX_HARTS * 4) /* If your test needs to temporarily block multiple-threads, do this: * smp_pause(reg1, reg2) * ... single-threaded work ... * smp_resume(reg1, reg2) * ... multi-threaded work ... */ #define smp_pause(reg1, reg2) \ li reg1, NONSMP_HART; \ csrr reg2, mhartid; \ bne reg1, reg2, 42f #define smp_resume(reg1, reg2) \ 42:; \ li reg1, SMP_BARRIER_ADDR; \ lw reg2, 0(reg1); \ csrr reg1, mhartid; \ bne reg1, reg2, 42b; \ li reg1, SMP_BARRIER_ADDR; \ addi reg2, reg2, 1; \ amoswap.w reg1, reg2, (reg1);\ 43:; \ li reg1, SMP_BARRIER_ADDR; \ lw reg2, 0(reg1); \ li reg1, MAX_HARTS; \ bne reg1, reg2, 43b
#include "spi.h" #include "uart.h" void write_reg(uintptr_t addr, uint32_t value) { volatile uint32_t *loc_addr = (volatile uint32_t *)addr; *loc_addr = value; } uint32_t read_reg(uintptr_t addr) { return *(volatile uint32_t *)addr; } void spi_init() { print_uart("init SPI\r\n"); // reset the axi quadspi core write_reg(SPI_RESET_REG, 0x0a); for (int i = 0; i < 10; i++) { __asm__ volatile( "nop"); } write_reg(SPI_CONTROL_REG, 0x104); uint32_t status = read_reg(SPI_STATUS_REG); print_uart("status: 0x"); print_uart_addr(status); print_uart("\r\n"); // clear all fifos write_reg(SPI_CONTROL_REG, 0x166); status = read_reg(SPI_STATUS_REG); print_uart("status: 0x"); print_uart_addr(status); print_uart("\r\n"); write_reg(SPI_CONTROL_REG, 0x06); print_uart("SPI initialized!\r\n"); } uint8_t spi_txrx(uint8_t byte) { // enable slave select write_reg(SPI_SLAVE_SELECT_REG, 0xfffffffe); write_reg(SPI_TRANSMIT_REG, byte); for (int i = 0; i < 100; i++) { __asm__ volatile( "nop"); } // enable spi control master flag write_reg(SPI_CONTROL_REG, 0x106); while ((read_reg(SPI_STATUS_REG) & 0x1) == 0x1) ; uint32_t result = read_reg(SPI_RECEIVE_REG); if ((read_reg(SPI_STATUS_REG) & 0x1) != 0x1) { print_uart("rx fifo not empty?? "); print_uart_addr(read_reg(SPI_STATUS_REG)); print_uart("\r\n"); } // disable slave select write_reg(SPI_SLAVE_SELECT_REG, 0xffffffff); // disable spi control master flag write_reg(SPI_CONTROL_REG, 0x06); return result; } int spi_write_bytes(uint8_t *bytes, uint32_t len, uint8_t *ret) { uint32_t status; if (len > 256) // FIFO maxdepth 256 return -1; // enable slave select write_reg(SPI_SLAVE_SELECT_REG, 0xfffffffe); for (int i = 0; i < len; i++) { write_reg(SPI_TRANSMIT_REG, bytes[i] & 0xff); } for (int i = 0; i < 50; i++) { __asm__ volatile( "nop"); } // enable spi control master flag write_reg(SPI_CONTROL_REG, 0x106); do { status = read_reg(SPI_STATUS_REG); } while ((status & 0x1) == 0x1); for (int i = 0; i < len;) { status = read_reg(SPI_STATUS_REG); if ((status & 0x1) != 0x1) // recieve fifo not empty { ret[i++] = read_reg(SPI_RECEIVE_REG); } } // disable slave select write_reg(SPI_SLAVE_SELECT_REG, 0xffffffff); // disable spi control master flag write_reg(SPI_CONTROL_REG, 0x06); return 0; }
#pragma once #include <stdint.h> #define SPI_BASE 0x20000000 #define SPI_RESET_REG SPI_BASE + 0x40 #define SPI_CONTROL_REG SPI_BASE + 0x60 #define SPI_STATUS_REG SPI_BASE + 0x64 #define SPI_TRANSMIT_REG SPI_BASE + 0x68 #define SPI_RECEIVE_REG SPI_BASE + 0x6C #define SPI_SLAVE_SELECT_REG SPI_BASE + 0x70 #define SPI_TRANSMIT_OCCUPANCY SPI_BASE + 0x74 #define SPI_RECEIVE_OCCUPANCY SPI_BASE + 0x78 #define SPI_INTERRUPT_GLOBAL_ENABLE_REG SPI_BASE + 0x1c #define SPI_INTERRUPT_STATUS_REG SPI_BASE + 0x20 #define SPI_INTERRUPT_ENABLE_REG SPI_BASE + 0x28 void spi_init(); uint8_t spi_txrx(uint8_t byte); // return -1 if something went wrong int spi_write_bytes(uint8_t *bytes, uint32_t len, uint8_t *ret);
#include "uart.h" void write_reg_u8(uintptr_t addr, uint8_t value) { volatile uint8_t *loc_addr = (volatile uint8_t *)addr; *loc_addr = value; } uint8_t read_reg_u8(uintptr_t addr) { return *(volatile uint8_t *)addr; } int is_transmit_empty() { return read_reg_u8(UART_LINE_STATUS) & 0x20; } void write_serial(char a) { while (is_transmit_empty() == 0) {}; write_reg_u8(UART_THR, a); } void init_uart(uint32_t freq, uint32_t baud) { uint32_t divisor = freq / (baud << 4); write_reg_u8(UART_INTERRUPT_ENABLE, 0x00); // Disable all interrupts write_reg_u8(UART_LINE_CONTROL, 0x80); // Enable DLAB (set baud rate divisor) write_reg_u8(UART_DLAB_LSB, divisor); // divisor (lo byte) write_reg_u8(UART_DLAB_MSB, (divisor >> 8) & 0xFF); // divisor (hi byte) write_reg_u8(UART_LINE_CONTROL, 0x03); // 8 bits, no parity, one stop bit write_reg_u8(UART_MODEM_CONTROL, 0x20); // Autoflow mode } // returns number of characters printed int print_uart(const char *str) { int num = 0; const char *cur = &str[0]; while (*cur != '\0') { write_serial((uint8_t)*cur); ++cur; ++num; } return num; } uint8_t bin_to_hex_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; void bin_to_hex(uint8_t inp, uint8_t res[2]) { res[1] = bin_to_hex_table[inp & 0xf]; res[0] = bin_to_hex_table[(inp >> 4) & 0xf]; return; } int print_uart_dec(uint32_t val, uint32_t digits) { int num = 0; int i; uint32_t k = 1000000000; for (i = 9; i > -1; i--) { uint32_t cur = val / k; val -= cur * k; k /= 10; if(cur || (i<digits)) { digits = i; uint8_t dec; dec = bin_to_hex_table[cur & 0xf]; write_serial(dec); num++; } } return num; } int print_uart_int(uint32_t addr) { int i; for (i = 3; i > -1; i--) { uint8_t cur = (addr >> (i * 8)) & 0xff; uint8_t hex[2]; bin_to_hex(cur, hex); write_serial(hex[0]); write_serial(hex[1]); } return 8; } int print_uart_addr(uint64_t addr) { int i; for (i = 7; i > -1; i--) { uint8_t cur = (addr >> (i * 8)) & 0xff; uint8_t hex[2]; bin_to_hex(cur, hex); write_serial(hex[0]); write_serial(hex[1]); } return 16; } int print_uart_byte(uint8_t byte) { uint8_t hex[2]; bin_to_hex(byte, hex); write_serial(hex[0]); write_serial(hex[1]); return 2; }
#pragma once #include <stdint.h> #define UART_BASE 0xFFF0C2C000 #define UART_RBR UART_BASE + 0 #define UART_THR UART_BASE + 0 #define UART_INTERRUPT_ENABLE UART_BASE + 1 #define UART_INTERRUPT_IDENT UART_BASE + 2 #define UART_FIFO_CONTROL UART_BASE + 2 #define UART_LINE_CONTROL UART_BASE + 3 #define UART_MODEM_CONTROL UART_BASE + 4 #define UART_LINE_STATUS UART_BASE + 5 #define UART_MODEM_STATUS UART_BASE + 6 #define UART_DLAB_LSB UART_BASE + 0 #define UART_DLAB_MSB UART_BASE + 1 void init_uart(); int print_uart(const char* str); int print_uart_dec(uint32_t val, uint32_t digits); int print_uart_int(uint32_t addr); int print_uart_addr(uint64_t addr); int print_uart_byte(uint8_t byte);
gitdir: ../../.git/modules/corev_apu/register_interface
.* !.git* /build /Bender.lock /Bender.local *.out __pycache__
package: name: register_interface authors: ["Fabian Schuiki <fschuiki@iis.ee.ethz.ch>", "Florian Zaruba <zarubaf@iis.ee.ethz.ch>"] dependencies: axi: { git: "https://github.com/pulp-platform/axi.git", version: 0.29.1 } common_cells: { git: "https://github.com/pulp-platform/common_cells.git", version: 1.21.0 } export_include_dirs: - include sources: # Level 0 - src/reg_intf.sv - vendor/lowrisc_opentitan/src/prim_subreg_arb.sv - vendor/lowrisc_opentitan/src/prim_subreg_ext.sv # Level 1 - src/apb_to_reg.sv - src/axi_to_reg.sv - src/periph_to_reg.sv - src/reg_cdc.sv - src/reg_demux.sv - src/reg_mux.sv - src/reg_to_mem.sv - src/reg_uniform.sv - vendor/lowrisc_opentitan/src/prim_subreg_shadow.sv - vendor/lowrisc_opentitan/src/prim_subreg.sv # Level 2 - src/axi_lite_to_reg.sv - target: test files: - src/reg_test.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 ## 0.3.1 - 2021-06-24 ### Fixed - Align AXI version in ips_list.yml with Bender.yml ## 0.3.0 - 2021-06-09 ### Changed - Rebased register_interface specific change of reggen tool on lowRISC upstream master - Bump AXI version ## 0.2.2 - 2021-04-20 ### Added - Add `periph_to_reg`. ### Changed - Bump AXI version ## 0.2.1 - 2021-02-03 ### Changed - Update `axi` to `0.23.0` - Update `common_cells` to `1.21.0` ### Added - Add ipapprox description ## 0.2.0 - 2020-12-30 ### Fixed - Fix bug in AXI-Lite to register interface conversion - Fix minor style problems (`verible-lint`) ## Removed - Remove `reg_intf_pkg.sv`. Type definitions are provided by `typedef.svh`. ### Added - Add `reggen` tool from lowrisc. - Add `typedef` and `assign` macros. - Add `reg_cdc`. - Add `reg_demux`. - Add `reg_mux`. - Add `reg_to_mem`. - AXI to reg interface. - Open source release. ### Changed - Updated AXI dependency ## 0.1.3 - 2018-06-02 ### Fixed - Add `axi_lite_to_reg.sv` to list of source files. ## 0.1.2 - 2018-03-23 ### Fixed - Remove time unit from test package. Fixes delay annotation issues. ## 0.1.1 - 2018-03-23 ### Fixed - Add a clock port to the `REG_BUS` interface. This fixes the test driver. ## 0.1.0 - 2018-03-23 ### Added - Add register bus interfaces. - Add uniform register. - Add AXI-Lite to register bus adapter. - Add test package with testbench utilities.
axi/axi: commit: v0.29.1 domain: [cluster, soc] common_cells: commit: v1.21.0 domain: [cluster, soc]
SOLDERPAD HARDWARE LICENSE version 0.51 This license is based closely on the Apache License Version 2.0, but is not approved or endorsed by the Apache Foundation. A copy of the non-modified Apache License 2.0 can be found at http://www.apache.org/licenses/LICENSE-2.0. As this license is not currently OSI or FSF approved, the Licensor permits any Work licensed under this License, at the option of the Licensee, to be treated as licensed under the Apache License Version 2.0 (which is so approved). This License is licensed under the terms of this License and in particular clause 7 below (Disclaimer of Warranties) applies in relation to its use. 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 Rights owner or entity authorized by the Rights 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. "Rights" means copyright and any similar right including design right (whether registered or unregistered), semiconductor topography (mask) rights and database rights (but excluding Patents and Trademarks). "Source" form shall mean the preferred form for making modifications, including but not limited to source code, net lists, board layouts, CAD files, 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, the instantiation of a hardware design and conversions to other media types, including intermediate forms such as bytecodes, FPGA bitstreams, artwork and semiconductor topographies (mask works). "Work" shall mean the work of authorship, whether in Source form or other Object form, made available under the License, as indicated by a Rights 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) or physically connect to or interoperate with the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any design or 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 Rights owner or by an individual or Legal Entity authorized to submit on behalf of the Rights 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 Rights 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 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 license under the Rights to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form and do anything in relation to the Work as if the Rights did not exist. 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: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and 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 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
# Generic Register Interface This repository contains a simple register interface definition as well as protocol adapters from APB, AXI-Lite, and AXI to said interface. Furthermore, it allows to generate a uniform register interface. ## Read Timing ![Read Timing](docs/timing_read.png) ## Write Timing ![Write Timing](docs/timing_write.png) ## Register File Generator We re-use lowrisc's register file generator to generate arbitrary configuration registers from an `hjson` description. See the the [tool's description](https://docs.opentitan.org/doc/rm/register_tool/) for further usage details. We use the [vendor tool](https://docs.opentitan.org/doc/rm/vendor_in_tool/) `util/vendor.py` to get the sources and apply our custom patches on top. ./util/vendor.py vendor/lowrisc_opentitan.vendor.hjson --update to re-vendor.
register_interface: vlog_opts: - -L common_cells_lib - -L axi_lib incdirs: - include - ../axi/axi/include - ../common_cells/include files: # Level 0 - src/reg_intf.sv # Level 1 - src/apb_to_reg.sv - src/axi_to_reg.sv - src/periph_to_reg.sv - src/reg_cdc.sv - src/reg_demux.sv - src/reg_mux.sv - src/reg_to_mem.sv - src/reg_uniform.sv # Level 2 - src/axi_lite_to_reg.sv reggen_primitives: vlog_opts: - -L common_cells_lib - -L axi_lib incdirs: - include - ../axi/axi/include - ../common_cells/include files: - vendor/lowrisc_opentitan/src/prim_subreg.sv - vendor/lowrisc_opentitan/src/prim_subreg_arb.sv - vendor/lowrisc_opentitan/src/prim_subreg_ext.sv - vendor/lowrisc_opentitan/src/prim_subreg_shadow.sv register_interface_test: vlog_opts: - -L common_cells_lib - -L axi_lib incdirs: - include files: - src/reg_test.sv flags: - skip_synthesis
{ "problemMatcher": [ { "owner": "verible-lint-matcher", "pattern": [ { "regexp": "^(.+):(\\d+):(\\d+):\\s(.+)$", "file": 1, "line": 2, "column": 3, "message": 4 } ] } ] }
# Copyright 2020 ETH Zurich and University of Bologna. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # Run all lint checks name: lint on: [push, pull_request] jobs: ################ # Verible Lint # ################ verilog: name: Verilog Sources # This job runs on Linux (fixed ubuntu version) runs-on: ubuntu-18.04 env: VERIBLE_VERSION: 0.0-807-g10e7c71 steps: - uses: actions/checkout@v2 - name: Install Verible run: | set -e mkdir -p build/verible cd build/verible curl -Ls -o verible.tar.gz https://github.com/google/verible/releases/download/v$VERIBLE_VERSION/verible-v$VERIBLE_VERSION-Ubuntu-18.04-bionic-x86_64.tar.gz sudo mkdir -p /tools/verible && sudo chmod 777 /tools/verible tar -C /tools/verible -xf verible.tar.gz --strip-components=1 echo "PATH=$PATH:/tools/verible/bin" >> $GITHUB_ENV # Run linter in hw/ip subdir - name: Run Lint run: | echo "::add-matcher::.github/verible-lint-matcher.json" find . -name "*sv" | xargs verible-verilog-lint --waiver_files lint/verible.waiver echo "::remove-matcher owner=verible-lint-matcher::" ##################### # Vendor Up-to-Date # ##################### # Check that all vendored sources are up-to-date. check-vendor: name: Vendor Up-to-Date runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: 3.x - name: Install requirements run: pip install hjson - name: Re-vendor and diff run: | find . \ -name '*.vendor.hjson' \ | xargs -n1 util/vendor.py --verbose \ && git diff --exit-code
{signal: [ {name: 'clk', wave: 'p.|....'}, {name: 'write', wave: 'x0|...x'}, {name: 'rdata', wave: 'x.|..2x', data: ["data"]}, {name: 'wdata', wave: 'x.|....'}, {name: 'wstrb', wave: 'x.|....'}, {name: 'error', wave: 'x.|..2x', data: ["error"]}, {name: 'valid', wave: '01|...0'}, {name: 'ready', wave: 'x0|..1x'}, ]} {signal: [ {name: 'clk', wave: 'p.|....'}, {name: 'write', wave: 'x1|...x'}, {name: 'rdata', wave: 'x.|....'}, {name: 'wdata', wave: 'x2|...x', data: ["data"]}, {name: 'wstrb', wave: 'x2|...x', data: ["strb"]}, {name: 'error', wave: 'x.|..2x', data: ["error"]}, {name: 'valid', wave: '01|...0'}, {name: 'ready', wave: 'x0|..1x'}, ]}
// Copyright (c) 2020 ETH Zurich, 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. // Florian Zaruba <zarubaf@iis.ee.ethz.ch> /// Macros to define register bus request/response structs. `ifndef REGISTER_INTERFACE_ASSIGN_SVH_ `define REGISTER_INTERFACE_ASSIGN_SVH_ `define REG_BUS_ASSIGN_TO_REQ(lhs, rhs) \ assign lhs = '{ \ addr: rhs.addr, \ write: rhs.write, \ wdata: rhs.wdata, \ wstrb: rhs.wstrb, \ valid: rhs.valid \ }; `define REG_BUS_ASSIGN_FROM_REQ(lhs, rhs) \ assign lhs.addr = rhs.addr; \ assign lhs.write = rhs.write; \ assign lhs.wdata = rhs.wdata; \ assign lhs.wstrb = rhs.wstrb; \ assign lhs.valid = rhs.valid; \ `define REG_BUS_ASSIGN_TO_RSP(lhs, rhs) \ assign lhs = '{ \ rdata: rhs.rdata, \ error: rhs.error, \ ready: rhs.ready \ }; `define REG_BUS_ASSIGN_FROM_RSP(lhs, rhs) \ assign lhs.rdata = rhs.rdata; \ assign lhs.error = rhs.error; \ assign lhs.ready = rhs.ready; `endif
// Copyright (c) 2020 ETH Zurich, 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. // Florian Zaruba <zarubaf@iis.ee.ethz.ch> /// Macros to define register bus request/response structs. `ifndef REGISTER_INTERFACE_TYPEDEF_SVH_ `define REGISTER_INTERFACE_TYPEDEF_SVH_ `define REG_BUS_TYPEDEF_REQ(req_t, addr_t, data_t, strb_t) \ typedef struct packed { \ addr_t addr; \ logic write; \ data_t wdata; \ strb_t wstrb; \ logic valid; \ } req_t; `define REG_BUS_TYPEDEF_RSP(rsp_t, data_t) \ typedef struct packed { \ data_t rdata; \ logic error; \ logic ready; \ } rsp_t; `define REG_BUS_TYPEDEF_ALL(name, addr_t, data_t, strb_t) \ `REG_BUS_TYPEDEF_REQ(name``_req_t, addr_t, data_t, strb_t) \ `REG_BUS_TYPEDEF_RSP(name``_rsp_t, data_t) `endif
# Copyright 2020 ETH Zurich and University of Bologna. # Solderpad Hardware License, Version 0.51, see LICENSE for details. # SPDX-License-Identifier: SHL-0.51 # # waiver file for register_interface lint waive --rule=explicit-parameter-storage-type --location="src/prim_subreg.sv" waive --rule=explicit-parameter-storage-type --location="src/prim_subreg_arb.sv" waive --rule=explicit-parameter-storage-type --location="src/prim_subreg_shadow.sv" waive --rule=interface-name-style --location="src/reg_intf.sv"
// 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. // // Florian Zaruba <zarubaf@iis.ee.ethz.ch> module apb_to_reg ( input logic clk_i, input logic rst_ni, input logic penable_i, input logic pwrite_i, input logic [31:0] paddr_i, input logic psel_i, input logic [31:0] pwdata_i, output logic [31:0] prdata_o, output logic pready_o, output logic pslverr_o, REG_BUS.out reg_o ); always_comb begin reg_o.addr = paddr_i; reg_o.write = pwrite_i; reg_o.wdata = pwdata_i; reg_o.wstrb = '1; reg_o.valid = psel_i & penable_i; pready_o = reg_o.ready; pslverr_o = reg_o.error; prdata_o = reg_o.rdata; end endmodule
// Copyright 2018-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. // // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> // Florian Zaruba <zarubaf@iis.ee.ethz.ch> /// A protocol converter from AXI4-Lite to a register interface. module axi_lite_to_reg #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1, /// Buffer depth (how many outstanding transactions do we allow) parameter int BUFFER_DEPTH = 2, /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. parameter bit DECOUPLE_W = 1, /// AXI-Lite request struct type. parameter type axi_lite_req_t = logic, /// AXI-Lite response struct type. parameter type axi_lite_rsp_t = logic, /// Regbus request struct type. parameter type reg_req_t = logic, /// Regbus response struct type. parameter type reg_rsp_t = logic ) ( input logic clk_i , input logic rst_ni , input axi_lite_req_t axi_lite_req_i, output axi_lite_rsp_t axi_lite_rsp_o, output reg_req_t reg_req_o , input reg_rsp_t reg_rsp_i ); `ifndef SYNTHESIS initial begin assert(BUFFER_DEPTH > 0); assert(ADDR_WIDTH > 0); assert(DATA_WIDTH > 0); end `endif typedef struct packed { logic [ADDR_WIDTH-1:0] addr; logic [DATA_WIDTH-1:0] data; logic [DATA_WIDTH/8-1:0] strb; // byte-wise strobe } write_t; typedef struct packed { logic [ADDR_WIDTH-1:0] addr; logic write; } req_t; typedef struct packed { logic [DATA_WIDTH-1:0] data; logic error; } resp_t; logic write_fifo_full, write_fifo_empty; write_t write_fifo_in, write_fifo_out; logic write_fifo_push, write_fifo_pop; logic write_resp_fifo_full, write_resp_fifo_empty; logic write_resp_fifo_in, write_resp_fifo_out; logic write_resp_fifo_push, write_resp_fifo_pop; logic read_fifo_full, read_fifo_empty; logic [ADDR_WIDTH-1:0] read_fifo_in, read_fifo_out; logic read_fifo_push, read_fifo_pop; logic read_resp_fifo_full, read_resp_fifo_empty; resp_t read_resp_fifo_in, read_resp_fifo_out; logic read_resp_fifo_push, read_resp_fifo_pop; req_t read_req, write_req, arb_req; logic read_valid, write_valid; logic read_ready, write_ready; // Combine AW/W Channel fifo_v3 #( .FALL_THROUGH ( !DECOUPLE_W ), .DEPTH ( BUFFER_DEPTH ), .dtype ( write_t ) ) i_fifo_write_req ( .clk_i, .rst_ni, .flush_i ( 1'b0 ), .testmode_i ( 1'b0 ), .full_o ( write_fifo_full ), .empty_o ( write_fifo_empty ), .usage_o ( /* open */ ), .data_i ( write_fifo_in ), .push_i ( write_fifo_push ), .data_o ( write_fifo_out ), .pop_i ( write_fifo_pop ) ); assign axi_lite_rsp_o.aw_ready = write_fifo_push; assign axi_lite_rsp_o.w_ready = write_fifo_push; assign write_fifo_push = axi_lite_req_i.aw_valid & axi_lite_req_i.w_valid & ~write_fifo_full; assign write_fifo_in.addr = axi_lite_req_i.aw.addr; assign write_fifo_in.data = axi_lite_req_i.w.data; assign write_fifo_in.strb = axi_lite_req_i.w.strb; assign write_fifo_pop = write_valid & write_ready; // B Channel fifo_v3 #( .DEPTH ( BUFFER_DEPTH ), .dtype ( logic ) ) i_fifo_write_resp ( .clk_i, .rst_ni, .flush_i ( 1'b0 ), .testmode_i ( 1'b0 ), .full_o ( write_resp_fifo_full ), .empty_o ( write_resp_fifo_empty ), .usage_o ( /* open */ ), .data_i ( write_resp_fifo_in ), .push_i ( write_resp_fifo_push ), .data_o ( write_resp_fifo_out ), .pop_i ( write_resp_fifo_pop ) ); assign axi_lite_rsp_o.b_valid = ~write_resp_fifo_empty; assign axi_lite_rsp_o.b.resp = write_resp_fifo_out ? axi_pkg::RESP_SLVERR : axi_pkg::RESP_OKAY; assign write_resp_fifo_in = reg_rsp_i.error; assign write_resp_fifo_push = reg_req_o.valid & reg_rsp_i.ready & reg_req_o.write; assign write_resp_fifo_pop = axi_lite_rsp_o.b_valid & axi_lite_req_i.b_ready; // AR Channel fifo_v3 #( .DEPTH ( BUFFER_DEPTH ), .DATA_WIDTH ( ADDR_WIDTH ) ) i_fifo_read ( .clk_i, .rst_ni, .flush_i ( 1'b0 ), .testmode_i ( 1'b0 ), .full_o ( read_fifo_full ), .empty_o ( read_fifo_empty ), .usage_o ( /* open */ ), .data_i ( read_fifo_in ), .push_i ( read_fifo_push ), .data_o ( read_fifo_out ), .pop_i ( read_fifo_pop ) ); assign read_fifo_pop = read_valid && read_ready; assign axi_lite_rsp_o.ar_ready = ~read_fifo_full; assign read_fifo_push = axi_lite_rsp_o.ar_ready & axi_lite_req_i.ar_valid; assign read_fifo_in = axi_lite_req_i.ar.addr; // R Channel fifo_v3 #( .DEPTH ( BUFFER_DEPTH ), .dtype ( resp_t ) ) i_fifo_read_resp ( .clk_i, .rst_ni, .flush_i ( 1'b0 ), .testmode_i ( 1'b0 ), .full_o ( read_resp_fifo_full ), .empty_o ( read_resp_fifo_empty ), .usage_o ( /* open */ ), .data_i ( read_resp_fifo_in ), .push_i ( read_resp_fifo_push ), .data_o ( read_resp_fifo_out ), .pop_i ( read_resp_fifo_pop ) ); assign axi_lite_rsp_o.r.data = read_resp_fifo_out.data; assign axi_lite_rsp_o.r.resp = read_resp_fifo_out.error ? axi_pkg::RESP_SLVERR : axi_pkg::RESP_OKAY; assign axi_lite_rsp_o.r_valid = ~read_resp_fifo_empty; assign read_resp_fifo_pop = axi_lite_rsp_o.r_valid & axi_lite_req_i.r_ready; assign read_resp_fifo_push = reg_req_o.valid & reg_rsp_i.ready & ~reg_req_o.write; assign read_resp_fifo_in.data = reg_rsp_i.rdata; assign read_resp_fifo_in.error = reg_rsp_i.error; // Make sure we can capture the responses (e.g. have enough fifo space) assign read_valid = ~read_fifo_empty & ~read_resp_fifo_full; assign write_valid = ~write_fifo_empty & ~write_resp_fifo_full; // Arbitrate between read/write assign read_req.addr = read_fifo_out; assign read_req.write = 1'b0; assign write_req.addr = write_fifo_out.addr; assign write_req.write = 1'b1; stream_arbiter #( .DATA_T ( req_t ), .N_INP ( 2 ), .ARBITER ( "rr" ) ) i_stream_arbiter ( .clk_i, .rst_ni, .inp_data_i ( {read_req, write_req} ), .inp_valid_i ( {read_valid, write_valid} ), .inp_ready_o ( {read_ready, write_ready} ), .oup_data_o ( arb_req ), .oup_valid_o ( reg_req_o.valid ), .oup_ready_i ( reg_rsp_i.ready ) ); assign reg_req_o.addr = arb_req.addr; assign reg_req_o.write = arb_req.write; assign reg_req_o.wdata = write_fifo_out.data; assign reg_req_o.wstrb = write_fifo_out.strb; endmodule `include "register_interface/typedef.svh" `include "register_interface/assign.svh" `include "axi/typedef.svh" `include "axi/assign.svh" /// Interface wrapper. module axi_lite_to_reg_intf #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1, /// Buffer depth (how many outstanding transactions do we allow) parameter int BUFFER_DEPTH = 2, /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. parameter bit DECOUPLE_W = 1 ) ( input logic clk_i , input logic rst_ni , AXI_LITE.Slave axi_i , REG_BUS.out reg_o ); typedef logic [ADDR_WIDTH-1:0] addr_t; typedef logic [DATA_WIDTH-1:0] data_t; typedef logic [DATA_WIDTH/8-1:0] strb_t; `REG_BUS_TYPEDEF_REQ(reg_req_t, addr_t, data_t, strb_t) `REG_BUS_TYPEDEF_RSP(reg_rsp_t, data_t) `AXI_LITE_TYPEDEF_AW_CHAN_T(aw_chan_t, addr_t) `AXI_LITE_TYPEDEF_W_CHAN_T(w_chan_t, data_t, strb_t) `AXI_LITE_TYPEDEF_B_CHAN_T(b_chan_t) `AXI_LITE_TYPEDEF_AR_CHAN_T(ar_chan_t, addr_t) `AXI_LITE_TYPEDEF_R_CHAN_T(r_chan_t, data_t) `AXI_LITE_TYPEDEF_REQ_T(axi_req_t, aw_chan_t, w_chan_t, ar_chan_t) `AXI_LITE_TYPEDEF_RESP_T(axi_resp_t, b_chan_t, r_chan_t) axi_req_t axi_req; axi_resp_t axi_resp; reg_req_t reg_req; reg_rsp_t reg_rsp; `AXI_LITE_ASSIGN_TO_REQ(axi_req, axi_i) `AXI_LITE_ASSIGN_FROM_RESP(axi_i, axi_resp) `REG_BUS_ASSIGN_FROM_REQ(reg_o, reg_req) `REG_BUS_ASSIGN_TO_RSP(reg_rsp, reg_o) axi_lite_to_reg #( .ADDR_WIDTH (ADDR_WIDTH), .DATA_WIDTH (DATA_WIDTH), .BUFFER_DEPTH (BUFFER_DEPTH), .DECOUPLE_W (DECOUPLE_W), .axi_lite_req_t (axi_req_t), .axi_lite_rsp_t (axi_resp_t), .reg_req_t (reg_req_t), .reg_rsp_t (reg_rsp_t) ) i_axi_lite_to_reg ( .clk_i (clk_i), .rst_ni (rst_ni), .axi_lite_req_i (axi_req), .axi_lite_rsp_o (axi_resp), .reg_req_o (reg_req), .reg_rsp_i (reg_rsp) ); endmodule
// Copyright 2018-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. // // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> /// A protocol converter from AXI4 to a register interface. `include "axi/typedef.svh" module axi_to_reg #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1, /// The width of the id. parameter int ID_WIDTH = -1, /// The width of the user signal. parameter int USER_WIDTH = -1, /// Maximum number of outstanding writes. parameter int unsigned AXI_MAX_WRITE_TXNS = 32'd2, /// Maximum number of outstanding reads. parameter int unsigned AXI_MAX_READ_TXNS = 32'd2, /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. parameter bit DECOUPLE_W = 1, /// AXI request struct type. parameter type axi_req_t = logic, /// AXI response struct type. parameter type axi_rsp_t = logic, /// Regbus request struct type. parameter type reg_req_t = logic, /// Regbus response struct type. parameter type reg_rsp_t = logic )( input logic clk_i , input logic rst_ni , input logic testmode_i , input axi_req_t axi_req_i, output axi_rsp_t axi_rsp_o, output reg_req_t reg_req_o , input reg_rsp_t reg_rsp_i ); typedef logic [ADDR_WIDTH-1:0] addr_t; typedef logic [DATA_WIDTH-1:0] data_t; typedef logic [DATA_WIDTH/8-1:0] strb_t; `AXI_LITE_TYPEDEF_AW_CHAN_T(aw_chan_t, addr_t) `AXI_LITE_TYPEDEF_W_CHAN_T(w_chan_t, data_t, strb_t) `AXI_LITE_TYPEDEF_B_CHAN_T(b_chan_t) `AXI_LITE_TYPEDEF_AR_CHAN_T(ar_chan_t, addr_t) `AXI_LITE_TYPEDEF_R_CHAN_T(r_chan_t, data_t) `AXI_LITE_TYPEDEF_REQ_T(axi_lite_req_t, aw_chan_t, w_chan_t, ar_chan_t) `AXI_LITE_TYPEDEF_RESP_T(axi_lite_resp_t, b_chan_t, r_chan_t) axi_lite_req_t axi_lite_req; axi_lite_resp_t axi_lite_resp; // convert axi to axi-lite axi_to_axi_lite #( .AxiAddrWidth ( ADDR_WIDTH ), .AxiDataWidth ( DATA_WIDTH ), .AxiIdWidth ( ID_WIDTH ), .AxiUserWidth ( USER_WIDTH ), /// Maximum number of outstanding writes. .AxiMaxWriteTxns ( AXI_MAX_WRITE_TXNS ), /// Maximum number of outstanding reads. .AxiMaxReadTxns ( AXI_MAX_READ_TXNS ), .FallThrough ( 0 ), .full_req_t ( axi_req_t ), .full_resp_t ( axi_rsp_t ), .lite_req_t ( axi_lite_req_t ), .lite_resp_t ( axi_lite_resp_t ) ) i_axi_to_axi_lite ( .clk_i, .rst_ni, .test_i ( testmode_i ), .slv_req_i (axi_req_i), .slv_resp_o (axi_rsp_o), .mst_req_o (axi_lite_req), .mst_resp_i (axi_lite_resp) ); axi_lite_to_reg #( /// The width of the address. .ADDR_WIDTH ( ADDR_WIDTH ), /// The width of the data. .DATA_WIDTH ( DATA_WIDTH ), /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. .DECOUPLE_W ( DECOUPLE_W ), .axi_lite_req_t ( axi_lite_req_t ), .axi_lite_rsp_t ( axi_lite_resp_t ), .reg_req_t (reg_req_t), .reg_rsp_t (reg_rsp_t) ) i_axi_lite_to_reg ( .clk_i, .rst_ni, .axi_lite_req_i (axi_lite_req), .axi_lite_rsp_o (axi_lite_resp), .reg_req_o, .reg_rsp_i ); endmodule module axi_to_reg_intf #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1, /// The width of the id. parameter int ID_WIDTH = -1, /// The width of the user signal. parameter int USER_WIDTH = -1, /// Maximum number of outstanding writes. parameter int unsigned AXI_MAX_WRITE_TXNS = 32'd2, /// Maximum number of outstanding reads. parameter int unsigned AXI_MAX_READ_TXNS = 32'd2, /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. parameter bit DECOUPLE_W = 1 )( input logic clk_i , input logic rst_ni , input logic testmode_i, AXI_BUS.Slave in , REG_BUS.out reg_o ); AXI_LITE #( .AXI_ADDR_WIDTH ( ADDR_WIDTH ), .AXI_DATA_WIDTH ( DATA_WIDTH ) ) axi_lite (); // convert axi to axi-lite axi_to_axi_lite_intf #( .AXI_ADDR_WIDTH ( ADDR_WIDTH ), .AXI_DATA_WIDTH ( DATA_WIDTH ), .AXI_ID_WIDTH ( ID_WIDTH ), .AXI_USER_WIDTH ( USER_WIDTH ), /// Maximum number of outstanding writes. .AXI_MAX_WRITE_TXNS ( AXI_MAX_WRITE_TXNS ), /// Maximum number of outstanding reads. .AXI_MAX_READ_TXNS ( AXI_MAX_READ_TXNS ), .FALL_THROUGH ( 0 ) ) i_axi_to_axi_lite ( .clk_i, .rst_ni, .testmode_i, .slv ( in ), .mst ( axi_lite ) ); axi_lite_to_reg_intf #( /// The width of the address. .ADDR_WIDTH ( ADDR_WIDTH ), /// The width of the data. .DATA_WIDTH ( DATA_WIDTH ), /// Whether the AXI-Lite W channel should be decoupled with a register. This /// can help break long paths at the expense of registers. .DECOUPLE_W ( DECOUPLE_W ) ) i_axi_lite_to_reg ( .clk_i, .rst_ni, .axi_i ( axi_lite ), .reg_o ); endmodule
// Copyright 2021 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. // // Translates XBAR_PERIPH_BUS to register_interface module periph_to_reg #( parameter int unsigned AW = 32, // Address Width parameter int unsigned DW = 32, // Data Width parameter int unsigned BW = 8, // Byte Width parameter int unsigned IW = 0, // ID Width parameter type req_t = logic, // reg request type parameter type rsp_t = logic // reg response type ) ( input logic clk_i, // Clock input logic rst_ni, // Asynchronous reset active low input logic req_i, input logic [ AW-1:0] add_i, input logic wen_i, input logic [ DW-1:0] wdata_i, input logic [DW/BW-1:0] be_i, input logic [ IW-1:0] id_i, output logic gnt_o, output logic [ DW-1:0] r_rdata_o, output logic r_opc_o, output logic [ IW-1:0] r_id_o, output logic r_valid_o, output req_t reg_req_o, input rsp_t reg_rsp_i ); logic [IW-1:0] r_id_d, r_id_q; logic r_opc_d, r_opc_q; logic r_valid_d, r_valid_q; logic [DW-1:0] r_rdata_d, r_rdata_q; always_comb begin : proc_logic r_id_d = id_i; r_opc_d = reg_rsp_i.error; r_valid_d = gnt_o; r_rdata_d = reg_rsp_i.rdata; end always_ff @(posedge clk_i or negedge rst_ni) begin : proc_seq if (!rst_ni) begin r_id_q <= '0; r_opc_q <= '0; r_valid_q <= '0; r_rdata_q <= '0; end else begin r_id_q <= r_id_d; r_opc_q <= r_opc_d; r_valid_q <= r_valid_d; r_rdata_q <= r_rdata_d; end end assign reg_req_o.addr = add_i; assign reg_req_o.write = ~wen_i; assign reg_req_o.wdata = wdata_i; assign reg_req_o.wstrb = be_i; assign reg_req_o.valid = req_i; assign gnt_o = req_i & reg_rsp_i.ready; assign r_rdata_o = r_rdata_q; assign r_opc_o = r_opc_q; assign r_id_o = r_id_q; assign r_valid_o = r_valid_q; /* Signal explanation for reference {signal: [ {name: 'clk', wave: 'p.|....'}, {name: 'PE_req', wave: '01|..0.'}, {name: 'PE_add', wave: 'x2|..x.', data: ["addr"]}, {name: 'PE_wen', wave: 'x2|..x.', data: ["wen"]}, {name: 'PE_wdata', wave: 'x2|..x.', data: ["wdata"]}, {name: 'PE_be', wave: 'x2|..x.', data: ["strb"]}, {name: 'PE_gnt', wave: '0.|.10.'}, {name: 'PE_id', wave: 'x2|..x.', data: ["ID"]}, {name: 'PE_r_valid', wave: '0.|..10'}, {name: 'PE_r_opc', wave: 'x.|..2x', data: ["error"]}, {name: 'PE_r_id', wave: 'x.|..2x', data: ["ID"]}, {name: 'PE_r_rdata', wave: 'x.|..2x', data: ["rdata"]}, {}, {name: 'write', wave: 'x2|..x.', data:['~wen']}, {name: 'addr' , wave: 'x2|..x.', data: ["addr"]}, {name: 'rdata', wave: 'x.|.2x.', data: ["rdata"]}, {name: 'wdata', wave: 'x2|..x.', data: ["wdata"]}, {name: 'wstrb', wave: 'x2|..x.', data: ["strb"]}, {name: 'error', wave: 'x.|.2x.', data: ["error"]}, {name: 'valid', wave: '01|..0.'}, {name: 'ready', wave: 'x0|.1x.'}, ]} */ 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. // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> // Florian Zaruba <zarubaf@iis.ee.ethz.ch> module reg_cdc #( parameter type req_t = logic, parameter type rsp_t = logic ) ( input logic src_clk_i, input logic src_rst_ni, input req_t src_req_i, output rsp_t src_rsp_o, input logic dst_clk_i, input logic dst_rst_ni, output req_t dst_req_o, input rsp_t dst_rsp_i ); typedef enum logic { Idle, Busy } state_e; state_e src_state_d, src_state_q, dst_state_d, dst_state_q; rsp_t dst_rsp_d, dst_rsp_q; logic src_req_valid, src_req_ready, src_rsp_valid, src_rsp_ready; logic dst_req_valid, dst_req_ready, dst_rsp_valid, dst_rsp_ready; logic src_ready_o; logic dst_valid_o; req_t src_req, dst_req; rsp_t src_rsp, dst_rsp; always_comb begin src_req = src_req_i; src_req.valid = 0; dst_req_o = dst_req; dst_req_o.valid = dst_valid_o; src_rsp_o = src_rsp; src_rsp_o.ready = src_ready_o; dst_rsp = dst_rsp_i; dst_rsp.ready = 0; end /////////////////////////////// // CLOCK DOMAIN CROSSING // /////////////////////////////// // Crossing for the request data from src to dst domain. cdc_2phase #(.T(req_t)) i_cdc_req ( .src_rst_ni ( src_rst_ni ), .src_clk_i ( src_clk_i ), .src_data_i ( src_req ), .src_valid_i ( src_req_valid ), .src_ready_o ( src_req_ready ), .dst_rst_ni ( dst_rst_ni ), .dst_clk_i ( dst_clk_i ), .dst_data_o ( dst_req ), .dst_valid_o ( dst_req_valid ), .dst_ready_i ( dst_req_ready ) ); // Crossing for the response data from dst to src domain. cdc_2phase #(.T(rsp_t)) i_cdc_rsp ( .src_rst_ni ( dst_rst_ni ), .src_clk_i ( dst_clk_i ), .src_data_i ( dst_rsp_q ), .src_valid_i ( dst_rsp_valid ), .src_ready_o ( dst_rsp_ready ), .dst_rst_ni ( src_rst_ni ), .dst_clk_i ( src_clk_i ), .dst_data_o ( src_rsp ), .dst_valid_o ( src_rsp_valid ), .dst_ready_i ( src_rsp_ready ) ); ////////////////////////////// // SRC DOMAIN HANDSHAKE // ////////////////////////////// // In the source domain we translate src_valid_i into a transaction on the // CDC into the destination domain. The FSM then transitions into a busy // state where it waits for a response coming back on the other CDC. Once // this response appears the ready bit goes high for one cycle, finishing // the register bus handshake. always_comb begin src_state_d = src_state_q; src_req_valid = 0; src_rsp_ready = 0; src_ready_o = 0; case (src_state_q) Idle: begin if (src_req_i.valid) begin src_req_valid = 1; if (src_req_ready) src_state_d = Busy; end end Busy: begin src_rsp_ready = 1; if (src_rsp_valid) begin src_ready_o = 1; src_state_d = Idle; end end default:; endcase end always_ff @(posedge src_clk_i, negedge src_rst_ni) begin if (!src_rst_ni) src_state_q <= Idle; else src_state_q <= src_state_d; end ////////////////////////////// // DST DOMAIN HANDSHAKE // ////////////////////////////// // In the destination domain we wait for the request data coming in on the // CDC domain. Once this happens we forward the request and wait for the // peer to acknowledge. Once acknowledged we store the response data and // transition into a busy state. In the busy state we send the response data // back to the src domain and wait for the transaction to complete. always_comb begin dst_state_d = dst_state_q; dst_req_ready = 0; dst_rsp_valid = 0; dst_valid_o = 0; dst_rsp_d = dst_rsp_q; case (dst_state_q) Idle: begin if (dst_req_valid) begin dst_valid_o = 1; if (dst_rsp_i.ready) begin dst_req_ready = 1; dst_rsp_d = dst_rsp; dst_state_d = Busy; end end end Busy: begin dst_rsp_valid = 1; if (dst_rsp_ready) begin dst_state_d = Idle; end end default:; endcase end always_ff @(posedge dst_clk_i, negedge dst_rst_ni) begin if (!dst_rst_ni) begin dst_state_q <= Idle; dst_rsp_q <= '0; end else begin dst_state_q <= dst_state_d; dst_rsp_q <= dst_rsp_d; end end 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. // Florian Zaruba <zarubaf@iis.ee.ethz.ch> module reg_demux #( parameter int unsigned NoPorts = 32'd0, parameter type req_t = logic, parameter type rsp_t = logic, // Dependent parameters, DO NOT OVERRIDE! parameter int unsigned SelectWidth = (NoPorts > 32'd1) ? $clog2(NoPorts) : 32'd1, parameter type select_t = logic [SelectWidth-1:0] ) ( input logic clk_i, input logic rst_ni, input select_t in_select_i, input req_t in_req_i, output rsp_t in_rsp_o, output req_t [NoPorts-1:0] out_req_o, input rsp_t [NoPorts-1:0] out_rsp_i ); always_comb begin out_req_o = '0; in_rsp_o = '0; out_req_o[in_select_i] = in_req_i; in_rsp_o = out_rsp_i[in_select_i]; end endmodule
// 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. // // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> /// A simple register interface. /// /// This is pretty much as simple as it gets. Transactions consist of only one /// phase. The master sets the address, write, write data, and write strobe /// signals and pulls valid high. Once pulled high, valid must remain high and /// none of the signals may change. The transaction completes when both valid /// and ready are high. Valid must not depend on ready. The slave presents the /// read data and error signals. These signals must be constant while valid and /// ready are both high. interface REG_BUS #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1 )( input logic clk_i ); logic [ADDR_WIDTH-1:0] addr; logic write; // 0=read, 1=write logic [DATA_WIDTH-1:0] rdata; logic [DATA_WIDTH-1:0] wdata; logic [DATA_WIDTH/8-1:0] wstrb; // byte-wise strobe logic error; // 0=ok, 1=error logic valid; logic ready; modport in (input addr, write, wdata, wstrb, valid, output rdata, error, ready); modport out (output addr, write, wdata, wstrb, valid, input rdata, error, ready); endinterface
// 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. // // Florian Zaruba <zarubaf@iis.ee.ethz.ch> /// A simple register interface. /// /// This is pretty much as simple as it gets. Transactions consist of only one /// phase. The master sets the address, write, write data, and write strobe /// signals and pulls valid high. Once pulled high, valid must remain high and /// none of the signals may change. The transaction completes when both valid /// and ready are high. Valid must not depend on ready. The slave presents the /// read data and error signals. These signals must be constant while valid and /// ready are both high. package reg_intf; /// 32 bit address, 32 bit data request package typedef struct packed { logic [31:0] addr; logic write; logic [31:0] wdata; logic [3:0] wstrb; logic valid; } reg_intf_req_a32_d32; /// 32 bit address, 64 bit data request package typedef struct packed { logic [31:0] addr; logic write; logic [63:0] wdata; logic [7:0] wstrb; logic valid; } reg_intf_req_a32_d64; /// 32 bit Response packages typedef struct packed { logic [31:0] rdata; logic error; logic ready; } reg_intf_resp_d32; /// 32 bit Response packages typedef struct packed { logic [63:0] rdata; logic error; logic ready; } reg_intf_resp_d64; endpackage
// 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. // Florian Zaruba <zarubaf@iis.ee.ethz.ch> `include "register_interface/typedef.svh" /// Multiplex/Arbitrate one register interface to `NoPorts`. module reg_mux #( parameter int unsigned NoPorts = 32'd0, parameter int unsigned AW = 0, parameter int unsigned DW = 0, parameter type req_t = logic, parameter type rsp_t = logic ) ( input logic clk_i, input logic rst_ni, input req_t [NoPorts-1:0] in_req_i, output rsp_t [NoPorts-1:0] in_rsp_o, output req_t out_req_o, input rsp_t out_rsp_i ); logic [NoPorts-1:0] in_valid, in_ready; `REG_BUS_TYPEDEF_REQ(req_payload_t, logic [AW-1:0], logic [DW-1:0], logic [DW/8-1:0]) req_payload_t [NoPorts-1:0] in_payload; req_payload_t out_payload; for (genvar i = 0; i < NoPorts; i++) begin : gen_unpack // Request assign in_valid[i] = in_req_i[i].valid; assign in_payload[i].addr = in_req_i[i].addr; assign in_payload[i].write = in_req_i[i].write; assign in_payload[i].wdata = in_req_i[i].wdata; assign in_payload[i].wstrb = in_req_i[i].wstrb; assign in_payload[i].valid = in_req_i[i].valid; // Response assign in_rsp_o[i].ready = in_ready[i]; assign in_rsp_o[i].rdata = out_rsp_i.rdata; assign in_rsp_o[i].error = out_rsp_i.error; end stream_arbiter #( .DATA_T (req_payload_t), .N_INP (NoPorts) ) i_stream_arbiter ( .clk_i, .rst_ni, .inp_data_i (in_payload), .inp_valid_i (in_valid), .inp_ready_o (in_ready), .oup_data_o (out_payload), .oup_valid_o (out_req_o.valid), .oup_ready_i (out_rsp_i.ready) ); assign out_req_o.addr = out_payload.addr; assign out_req_o.write = out_payload.write; assign out_req_o.wdata = out_payload.wdata; assign out_req_o.wstrb = out_payload.wstrb; assign out_req_o.valid = out_payload.valid; endmodule
// 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. // // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> /// A set of testbench utilities for AXI interfaces. package reg_test; /// A driver for AXI4-Lite interface. class reg_driver #( parameter int AW , parameter int DW , parameter time TA = 0 , // stimuli application time parameter time TT = 0 // stimuli test time ); virtual REG_BUS #( .ADDR_WIDTH(AW), .DATA_WIDTH(DW) ) bus; function new( virtual REG_BUS #( .ADDR_WIDTH(AW), .DATA_WIDTH(DW) ) bus ); this.bus = bus; endfunction task reset_master; bus.addr <= '0; bus.write <= '0; bus.wdata <= '0; bus.wstrb <= '0; bus.valid <= '0; endtask task reset_slave; bus.rdata <= '0; bus.error <= '0; bus.ready <= '0; endtask task cycle_start; #TT; endtask task cycle_end; @(posedge bus.clk_i); endtask /// Issue a write transaction. task send_write ( input logic [AW-1:0] addr, input logic [DW-1:0] data, input logic [DW/8-1:0] strb, output logic error ); bus.addr <= #TA addr; bus.write <= #TA 1; bus.wdata <= #TA data; bus.wstrb <= #TA strb; bus.valid <= #TA 1; cycle_start(); while (bus.ready != 1) begin cycle_end(); cycle_start(); end error = bus.error; cycle_end(); bus.addr <= #TA '0; bus.write <= #TA 0; bus.wdata <= #TA '0; bus.wstrb <= #TA '0; bus.valid <= #TA 0; endtask /// Issue a read transaction. task send_read ( input logic [AW-1:0] addr, output logic [DW-1:0] data, output logic error ); bus.addr <= #TA addr; bus.write <= #TA 0; bus.valid <= #TA 1; cycle_start(); while (bus.ready != 1) begin cycle_end(); cycle_start(); end data = bus.rdata; error = bus.error; cycle_end(); bus.addr <= #TA '0; bus.write <= #TA 0; bus.valid <= #TA 0; endtask endclass endpackage
// 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. // Florian Zaruba <zarubaf@iis.ee.ethz.ch> // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> `include "common_cells/registers.svh" /// Register bus to SRAM interface. module reg_to_mem #( parameter int unsigned AW = 0, parameter int unsigned DW = 0, parameter type req_t = logic, parameter type rsp_t = logic ) ( input logic clk_i, input logic rst_ni, input req_t reg_req_i, output rsp_t reg_rsp_o, // SRAM out output logic req_o, input logic gnt_i, output logic we_o, output logic [AW-1:0] addr_o, output logic [DW-1:0] wdata_o, output logic [DW/8-1:0] wstrb_o, input logic [DW-1:0] rdata_i, input logic rvalid_i, input logic rerror_i ); logic wait_read_d, wait_read_q; `FF(wait_read_q, wait_read_d, 1'b0) always_comb begin wait_read_d = wait_read_q; if (req_o && gnt_i && !we_o) wait_read_d = 1'b1; if (wait_read_q && reg_rsp_o.ready) wait_read_d = 1'b0; end assign req_o = ~wait_read_q & reg_req_i.valid; assign we_o = reg_req_i.write; assign addr_o = reg_req_i.addr[AW-1:0]; assign wstrb_o = reg_req_i.wstrb; assign wdata_o = reg_req_i.wdata; assign reg_rsp_o.rdata = rdata_i; assign reg_rsp_o.error = rerror_i; assign reg_rsp_o.ready = (reg_req_i.valid & gnt_i & we_o) | (wait_read_q & rvalid_i); endmodule
// 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. // // Fabian Schuiki <fschuiki@iis.ee.ethz.ch> /// A uniform register file. module reg_uniform #( /// The width of the address. parameter int ADDR_WIDTH = -1, /// The width of the data. parameter int DATA_WIDTH = -1, /// The number of registers. parameter int NUM_REG = -1, /// The width of each register. parameter int REG_WIDTH = -1, /// The register write mask parameter logic [NUM_REG-1:0] REG_WRITABLE = '1 )( input logic clk_i , input logic rst_ni , input logic [NUM_REG-1:0][REG_WIDTH-1:0] init_val_i , // initial register value input logic [NUM_REG-1:0][REG_WIDTH-1:0] rd_val_i , // register read value output logic [NUM_REG-1:0][REG_WIDTH-1:0] wr_val_o , // register written value output logic [NUM_REG-1:0] wr_evt_o , REG_BUS.in reg_i ); // Generate the flip flops for the registers. logic [NUM_REG-1:0][REG_WIDTH-1:0] reg_q; logic [NUM_REG-1:0][REG_WIDTH/8-1:0] reg_wr; for (genvar i = 0; i < NUM_REG; i++) begin : gen_regs // If this register is writable, create a flip flop for it. Otherwise map it // to the initial value. if (REG_WRITABLE[i]) begin : gen_writable // Generate one flip-flop per byte enable. for (genvar j = 0; j < REG_WIDTH/8; j++) begin : gen_ff always_ff @(posedge clk_i, negedge rst_ni) begin if (!rst_ni) reg_q[i][j*8+7 -: 8] <= init_val_i[i][j*8+7 -: 8]; else if (reg_wr[i][j]) reg_q[i][j*8+7 -: 8] <= reg_i.wdata[(i*REG_WIDTH+j*8+7)%DATA_WIDTH -: 8]; end end end else begin : gen_readonly assign reg_q[i] = init_val_i[i]; end end // Generate the written register value and event signals. always_comb begin wr_val_o = reg_q; for (int i = 0; i < NUM_REG; i++) wr_evt_o[i] = |reg_wr[i]; end // Map the byte address of the bus to a bus word address. localparam int AddrShift = $clog2(DATA_WIDTH/8); logic [ADDR_WIDTH-AddrShift-1:0] bus_word_addr; assign bus_word_addr = reg_i.addr >> AddrShift; // Map the register dimensions to bus dimensions. localparam int NumBusWords = (NUM_REG * REG_WIDTH + DATA_WIDTH - 1) / DATA_WIDTH; logic [NumBusWords-1:0][DATA_WIDTH-1:0] reg_busmapped; logic [NumBusWords-1:0][DATA_WIDTH/8-1:0] reg_wr_busmapped; assign reg_busmapped = rd_val_i; assign reg_wr = reg_wr_busmapped; // Implement the communication via the register interface. always_comb begin reg_wr_busmapped = '0; reg_i.ready = 1; reg_i.rdata = '0; reg_i.error = 0; if (reg_i.valid) begin if (bus_word_addr < NumBusWords) begin reg_i.rdata = reg_busmapped[bus_word_addr]; if (reg_i.write) begin reg_wr_busmapped[bus_word_addr] = reg_i.wstrb; end end else begin reg_i.error = 1; end end end endmodule
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''A tool to copy source code from upstream into this repository. For an introduction to using this tool, see doc/ug/vendor_hw.md in this repository (on the internet at https://docs.opentitan.org/doc/ug/vendor_hw/). For full documentation, see doc/rm/vendor_in_tool.md (on the internet at https://docs.opentitan.org/doc/rm/vendor_in_tool). ''' import argparse import fnmatch import logging as log import os import re import shutil import subprocess import sys import tempfile import textwrap from pathlib import Path import hjson EXCLUDE_ALWAYS = ['.git'] LOCK_FILE_HEADER = """// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // This file is generated by the util/vendor script. Please do not modify it // manually. """ # Keys in the description (configuration) file which can be overridden through # the command line. OVERRIDABLE_DESC_KEYS = [ 'patch_repo.url', 'patch_repo.rev_base', 'patch_repo.rev_patched', 'upstream.url', 'upstream.ref', ] verbose = False def git_is_clean_workdir(git_workdir): """Check if the git working directory is clean (no unstaged or staged changes)""" cmd = ['git', 'status', '--untracked-files=no', '--porcelain'] modified_files = subprocess.run(cmd, cwd=str(git_workdir), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.strip() return not modified_files def github_qualify_references(log, repo_userorg, repo_name): """ Replace "unqualified" GitHub references with "fully qualified" one GitHub automatically links issues and pull requests if they have a specific format. Links can be qualified with the user/org name and the repository name, or unqualified, if they only contain the issue or pull request number. This function converts all unqualified references to qualified ones. See https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests for a documentation of all supported formats. """ r = re.compile(r"(^|[^\w])(?:#|[gG][hH]-)(\d+)\b") repl_str = r'\1%s/%s#\2' % (repo_userorg, repo_name) return [r.sub(repl_str, l) for l in log] def test_github_qualify_references(): repo_userorg = 'lowRISC' repo_name = 'ibex' # Unqualified references, should be replaced items_unqualified = [ '#28', 'GH-27', 'klaus #27', 'Fixes #27', 'Fixes #27 and #28', '(#27)', 'something (#27) done', '#27 and (GH-38)', ] exp_items_unqualified = [ 'lowRISC/ibex#28', 'lowRISC/ibex#27', 'klaus lowRISC/ibex#27', 'Fixes lowRISC/ibex#27', 'Fixes lowRISC/ibex#27 and lowRISC/ibex#28', '(lowRISC/ibex#27)', 'something (lowRISC/ibex#27) done', 'lowRISC/ibex#27 and (lowRISC/ibex#38)', ] assert github_qualify_references(items_unqualified, repo_userorg, repo_name) == exp_items_unqualified # Qualified references, should stay as they are items_qualified = [ 'Fixes lowrisc/ibex#27', 'lowrisc/ibex#2', ] assert github_qualify_references(items_qualified, repo_userorg, repo_name) == items_qualified # Invalid references, should stay as they are items_invalid = [ 'something#27', 'lowrisc/ibex#', ] assert github_qualify_references(items_invalid, repo_userorg, repo_name) == items_invalid def test_github_parse_url(): assert github_parse_url('https://example.com/something/asdf.git') is None assert github_parse_url('https://github.com/lowRISC/ibex.git') == ( 'lowRISC', 'ibex') assert github_parse_url('https://github.com/lowRISC/ibex') == ('lowRISC', 'ibex') assert github_parse_url('git@github.com:lowRISC/ibex.git') == ('lowRISC', 'ibex') def github_parse_url(github_repo_url): """Parse a GitHub repository URL into its parts. Return a tuple (userorg, name), or None if the parsing failed. """ regex = r"(?:@github\.com\:|\/github\.com\/)([a-zA-Z\d-]+)\/([a-zA-Z\d-]+)(?:\.git)?$" m = re.search(regex, github_repo_url) if m is None: return None return (m.group(1), m.group(2)) def produce_shortlog(clone_dir, mapping, old_rev, new_rev): """ Produce a list of changes between two revisions, one revision per line Merges are excluded""" # If mapping is None, we want to list all changes below clone_dir. # Otherwise, we want to list changes in each 'source' in the mapping. Since # these strings are paths relative to clone_dir, we can just pass them all # to git and let it figure out what to do. subdirs = (['.'] if mapping is None else [m.from_path for m in mapping.items]) cmd = (['git', '-C', str(clone_dir), 'log', '--pretty=format:%s (%aN)', '--no-merges', old_rev + '..' + new_rev] + subdirs) try: proc = subprocess.run(cmd, cwd=str(clone_dir), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) return proc.stdout.splitlines() except subprocess.CalledProcessError as e: log.error("Unable to capture shortlog: %s", e.stderr) return "" def format_list_to_str(list, width=70): """ Create Markdown-style formatted string from a list of strings """ wrapper = textwrap.TextWrapper(initial_indent="* ", subsequent_indent=" ", width=width) return '\n'.join([wrapper.fill(s) for s in list]) class JsonError(Exception): '''An error class for when data in the source HJSON is bad''' def __init__(self, path, msg): self.path = path self.msg = msg def __str__(self): return 'In hjson at {}, {}'.format(self.path, self.msg) def get_field(path, where, data, name, expected_type=dict, optional=False, constructor=None): value = data.get(name) if value is None: if not optional: raise JsonError(path, '{}, missing {!r} field.'.format(where, name)) return None if not isinstance(value, expected_type): raise JsonError(path, '{}, the {!r} field is {!r}, but should be of type {!r}.' .format(where, name, value, expected_type.__name__)) return value if constructor is None else constructor(value) class Upstream: '''A class representing the 'upstream' field in a config or lock file''' def __init__(self, path, data): # Fields: 'url', 'rev', 'only_subdir' (optional). All should be strings. where = 'in upstream dict' self.url = get_field(path, where, data, 'url', str) self.rev = get_field(path, where, data, 'rev', str) self.only_subdir = get_field(path, where, data, 'only_subdir', str, optional=True) def as_dict(self): data = {'url': self.url, 'rev': self.rev} if self.only_subdir is not None: data['only_subdir'] = self.only_subdir return data class PatchRepo: '''A class representing the 'patch_repo' field in a config file''' def __init__(self, path, data): # Fields: 'url', 'rev_base', 'rev_patched'. All should be strings. where = 'in patch_repo dict' self.url = get_field(path, where, data, 'url', str) self.rev_base = get_field(path, where, data, 'rev_base', str) self.rev_patched = get_field(path, where, data, 'rev_patched', str) class Mapping1: '''A class to represent a single item in the 'mapping' field in a config file''' def __init__(self, from_path, to_path, patch_dir): self.from_path = from_path self.to_path = to_path self.patch_dir = patch_dir @staticmethod def make(path, idx, data): assert isinstance(data, dict) def get_path(name, optional=False): val = get_field(path, 'in mapping entry {}'.format(idx + 1), data, name, expected_type=str, optional=optional) if val is None: return None # Check that the paths aren't evil ('../../../foo' or '/etc/passwd' # are *not* ok!) val = os.path.normpath(val) if val.startswith('/') or val.startswith('..'): raise JsonError(path, 'Mapping entry {} has a bad path for {!r} ' '(must be a relative path that doesn\'t ' 'escape the directory)' .format(idx + 1, name)) return Path(val) from_path = get_path('from') to_path = get_path('to') patch_dir = get_path('patch_dir', optional=True) return Mapping1(from_path, to_path, patch_dir) @staticmethod def make_default(have_patch_dir): '''Make a default mapping1, which copies everything straight through''' return Mapping1(Path('.'), Path('.'), Path('.') if have_patch_dir else None) @staticmethod def apply_patch(basedir, patchfile): cmd = ['git', 'apply', '--directory', str(basedir), '-p1', str(patchfile)] if verbose: cmd += ['--verbose'] subprocess.run(cmd, check=True) def import_from_upstream(self, upstream_path, target_path, exclude_files, patch_dir): '''Copy from the upstream checkout to target_path''' from_path = upstream_path / self.from_path to_path = target_path / self.to_path # Make sure the target directory actually exists to_path.parent.mkdir(exist_ok=True, parents=True) # Copy src to dst recursively. For directories, we can use # shutil.copytree. This doesn't support files, though, so we have to # check for them first. if from_path.is_file(): shutil.copy(str(from_path), str(to_path)) else: ignore = ignore_patterns(str(upstream_path), *exclude_files) shutil.copytree(str(from_path), str(to_path), ignore=ignore) # Apply any patches to the copied files. If self.patch_dir is None, # there are none to apply. Otherwise, resolve it relative to patch_dir. if self.patch_dir is not None: patches = (patch_dir / self.patch_dir).glob('*.patch') for patch in sorted(patches): log.info("Applying patch {} at {}".format(patch, to_path)) Mapping1.apply_patch(to_path, patch) class Mapping: '''A class representing the 'mapping' field in a config file This should be a list of dicts. ''' def __init__(self, items): self.items = items @staticmethod def make(path, data): items = [] assert isinstance(data, list) for idx, elt in enumerate(data): if not isinstance(elt, dict): raise JsonError(path, 'Mapping element {!r} is not a dict.'.format(elt)) items.append(Mapping1.make(path, idx, elt)) return Mapping(items) def has_patch_dir(self): '''Check whether at least one item defines a patch dir''' for item in self.items: if item.patch_dir is not None: return True return False class LockDesc: '''A class representing the contents of a lock file''' def __init__(self, handle): data = hjson.loads(handle.read(), use_decimal=True) self.upstream = get_field(handle.name, 'at top-level', data, 'upstream', constructor=lambda data: Upstream(handle.name, data)) class Desc: '''A class representing the configuration file''' def __init__(self, handle, desc_overrides): # Ensure description file matches our naming rules (otherwise we don't # know the name for the lockfile). This regex checks that we have the # right suffix and a nonempty name. if not re.match(r'.+\.vendor\.hjson', handle.name): raise ValueError("Description file names must have a .vendor.hjson suffix.") data = hjson.loads(handle.read(), use_decimal=True) where = 'at top-level' self.apply_overrides(data, desc_overrides) path = Path(handle.name) def take_path(p): return path.parent / p self.path = path self.name = get_field(path, where, data, 'name', expected_type=str) self.target_dir = get_field(path, where, data, 'target_dir', expected_type=str, constructor=take_path) self.upstream = get_field(path, where, data, 'upstream', constructor=lambda data: Upstream(path, data)) self.patch_dir = get_field(path, where, data, 'patch_dir', optional=True, expected_type=str, constructor=take_path) self.patch_repo = get_field(path, where, data, 'patch_repo', optional=True, constructor=lambda data: PatchRepo(path, data)) self.exclude_from_upstream = (get_field(path, where, data, 'exclude_from_upstream', optional=True, expected_type=list) or []) self.mapping = get_field(path, where, data, 'mapping', optional=True, expected_type=list, constructor=lambda data: Mapping.make(path, data)) # Add default exclusions self.exclude_from_upstream += EXCLUDE_ALWAYS # It doesn't make sense to define a patch_repo, but not a patch_dir # (where should we put the patches that we get?) if self.patch_repo is not None and self.patch_dir is None: raise JsonError(path, 'Has patch_repo but not patch_dir.') # We don't currently support a patch_repo and a mapping (just because # we haven't written the code to generate the patches across subdirs # yet). Tracked in issue #2317. if self.patch_repo is not None and self.mapping is not None: raise JsonError(path, "vendor.py doesn't currently support patch_repo " "and mapping at the same time (see issue #2317).") # If a patch_dir is defined and there is no mapping, we will look in # that directory for patches and apply them in (the only) directory # that we copy stuff into. # # If there is a mapping check that there is a patch_dir if and only if # least one mapping entry uses it. if self.mapping is not None: if self.patch_dir is not None: if not self.mapping.has_patch_dir(): raise JsonError(path, 'Has patch_dir, but no mapping item uses it.') else: if self.mapping.has_patch_dir(): raise JsonError(path, 'Has a mapping item with a patch directory, ' 'but there is no global patch_dir key.') # Check that exclude_from_upstream really is a list of strings. Most of # this type-checking is in the constructors for field types, but we # don't have a "ExcludeList" class, so have to do it explicitly here. for efu in self.exclude_from_upstream: if not isinstance(efu, str): raise JsonError(path, 'exclude_from_upstream has entry {}, which is not a string.' .format(efu)) def apply_overrides(self, desc_data, desc_overrides): """ Apply overrides from command line to configuration file data Updates are applied to the desc_data reference.""" for key, value in desc_overrides: log.info("Overriding description key {!r} with value {!r}".format( key, value)) ref = desc_data split_keys = key.split('.') for key_part in split_keys[:-1]: if key_part not in ref: ref[key_part] = {} ref = ref[key_part] ref[split_keys[-1]] = value def lock_file_path(self): desc_file_stem = self.path.name.rsplit('.', 2)[0] return self.path.with_name(desc_file_stem + '.lock.hjson') def import_from_upstream(self, upstream_path): log.info('Copying upstream sources to {}'.format(self.target_dir)) # Remove existing directories before importing them again shutil.rmtree(str(self.target_dir), ignore_errors=True) items = (self.mapping.items if self.mapping is not None else [Mapping1.make_default(self.patch_dir is not None)]) for map1 in items: map1.import_from_upstream(upstream_path, self.target_dir, self.exclude_from_upstream, self.patch_dir) def refresh_patches(desc): if desc.patch_repo is None: log.fatal('Unable to refresh patches, patch_repo not set in config.') sys.exit(1) log.info('Refreshing patches in {}'.format(desc.patch_dir)) # remove existing patches for patch in desc.patch_dir.glob('*.patch'): os.unlink(str(patch)) # get current patches _export_patches(desc.patch_repo.url, desc.patch_dir, desc.patch_repo.rev_base, desc.patch_repo.rev_patched) def _export_patches(patchrepo_clone_url, target_patch_dir, upstream_rev, patched_rev): with tempfile.TemporaryDirectory() as clone_dir: clone_git_repo(patchrepo_clone_url, clone_dir, patched_rev) rev_range = 'origin/' + upstream_rev + '..' + 'origin/' + patched_rev cmd = ['git', 'format-patch', '-o', str(target_patch_dir.resolve()), rev_range] if not verbose: cmd += ['-q'] subprocess.run(cmd, cwd=str(clone_dir), check=True) def ignore_patterns(base_dir, *patterns): """Similar to shutil.ignore_patterns, but with support for directory excludes.""" def _rel_to_base(path, name): return os.path.relpath(os.path.join(path, name), base_dir) def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: pattern_matches = [ n for n in names if fnmatch.fnmatch(_rel_to_base(path, n), pattern) ] ignored_names.extend(pattern_matches) return set(ignored_names) return _ignore_patterns def clone_git_repo(repo_url, clone_dir, rev='master'): log.info('Cloning upstream repository %s @ %s', repo_url, rev) # Clone the whole repository cmd = ['git', 'clone', '--no-single-branch'] if not verbose: cmd += ['-q'] cmd += [repo_url, str(clone_dir)] subprocess.run(cmd, check=True) # Check out exactly the revision requested cmd = ['git', '-C', str(clone_dir), 'checkout', '--force', rev] if not verbose: cmd += ['-q'] subprocess.run(cmd, check=True) # Get revision information cmd = ['git', '-C', str(clone_dir), 'rev-parse', 'HEAD'] rev = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, universal_newlines=True).stdout.strip() log.info('Cloned at revision %s', rev) return rev def git_get_short_rev(clone_dir, rev): """ Get the shortened SHA-1 hash for a revision """ cmd = ['git', '-C', str(clone_dir), 'rev-parse', '--short', rev] short_rev = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, universal_newlines=True).stdout.strip() return short_rev def git_add_commit(paths, commit_msg): """ Stage and commit all changes in paths""" assert paths base_dir = paths[0].parent # Stage all changes # # Rather than figuring out GIT_DIR properly, we cheat and use "git -C" to # pretend that we're running in base_dir. Of course, the elements of paths # are relative to our actual working directory. Rather than do anything # clever, we just resolve them to absolute paths as we go. abs_paths = [p.resolve() for p in paths] subprocess.run(['git', '-C', base_dir, 'add'] + abs_paths, check=True) cmd_commit = ['git', '-C', base_dir, 'commit', '-s', '-F', '-'] try: subprocess.run(cmd_commit, check=True, universal_newlines=True, input=commit_msg) except subprocess.CalledProcessError: log.warning("Unable to create commit. Are there no changes?") def define_arg_type(arg): """Sanity-check and return a config file override argument""" try: (key, value) = [v.strip() for v in arg.split('=', 2)] except Exception: raise argparse.ArgumentTypeError( 'unable to parse {!r}: configuration overrides must be in the form key=value' .format(arg)) if key not in OVERRIDABLE_DESC_KEYS: raise argparse.ArgumentTypeError( 'invalid configuration override: key {!r} cannot be overwritten' .format(key)) return (key, value) def main(argv): parser = argparse.ArgumentParser(prog="vendor", description=__doc__) parser.add_argument( '--update', '-U', dest='update', action='store_true', help='Update locked version of repository with upstream changes') parser.add_argument('--refresh-patches', action='store_true', help='Refresh the patches from the patch repository') parser.add_argument('--commit', '-c', action='store_true', help='Commit the changes') parser.add_argument('--desc-override', '-D', dest="desc_overrides", action="append", type=define_arg_type, default=[], help='Override a setting in the description file. ' 'Format: -Dsome.key=value. ' 'Can be used multiple times.') parser.add_argument('desc_file', metavar='file', type=argparse.FileType('r', encoding='UTF-8'), help='vendoring description file (*.vendor.hjson)') parser.add_argument('--verbose', '-v', action='store_true', help='Verbose') args = parser.parse_args() global verbose verbose = args.verbose if (verbose): log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(message)s") # Load input files (desc file; lock file) and check syntax etc. try: # Load description file desc = Desc(args.desc_file, args.desc_overrides) lock_file_path = desc.lock_file_path() # Try to load lock file (which might not exist) try: with open(str(lock_file_path), 'r') as lock_file: lock = LockDesc(lock_file) except FileNotFoundError: lock = None except (JsonError, ValueError) as err: log.fatal(str(err)) raise SystemExit(1) # Check for a clean working directory when commit is requested if args.commit: if not git_is_clean_workdir(desc.path.parent): log.fatal("A clean git working directory is required for " "--commit/-c. git stash your changes and try again.") raise SystemExit(1) if lock is None and not args.update: log.warning("No lock file at {}, so will update upstream repo." .format(str(desc.lock_file_path()))) args.update = True # If we have a lock file and we're not in update mode, override desc's # upstream field with the one from the lock file. Keep track of whether the # URL differs (in which case, we can't get a shortlog) changed_url = False if lock is not None: changed_url = desc.upstream.url != lock.upstream.url if not args.update: desc.upstream = lock.upstream if args.refresh_patches: refresh_patches(desc) with tempfile.TemporaryDirectory() as clone_dir: # clone upstream repository upstream_new_rev = clone_git_repo(desc.upstream.url, clone_dir, rev=desc.upstream.rev) if not args.update: if upstream_new_rev != lock.upstream.rev: log.fatal( "Revision mismatch. Unable to re-clone locked version of repository." ) log.fatal("Attempted revision: %s", desc.upstream.rev) log.fatal("Re-cloned revision: %s", upstream_new_rev) raise SystemExit(1) clone_subdir = Path(clone_dir) if desc.upstream.only_subdir is not None: clone_subdir = clone_subdir / desc.upstream.only_subdir if not clone_subdir.is_dir(): log.fatal("subdir '{}' does not exist in repo" .format(desc.upstream.only_subdir)) raise SystemExit(1) # copy selected files from upstream repo and apply patches as necessary desc.import_from_upstream(clone_subdir) # get shortlog get_shortlog = args.update if args.update: if lock is None: get_shortlog = False log.warning("No lock file %s: unable to summarize changes.", str(lock_file_path)) elif changed_url: get_shortlog = False log.warning("The repository URL changed since the last run. " "Unable to get log of changes.") shortlog = None if get_shortlog: shortlog = produce_shortlog(clone_subdir, desc.mapping, lock.upstream.rev, upstream_new_rev) # Ensure fully-qualified issue/PR references for GitHub repos gh_repo_info = github_parse_url(desc.upstream.url) if gh_repo_info: shortlog = github_qualify_references(shortlog, gh_repo_info[0], gh_repo_info[1]) log.info("Changes since the last import:\n" + format_list_to_str(shortlog)) # write lock file if args.update: lock_data = {} lock_data['upstream'] = desc.upstream.as_dict() lock_data['upstream']['rev'] = upstream_new_rev with open(str(lock_file_path), 'w', encoding='UTF-8') as f: f.write(LOCK_FILE_HEADER) hjson.dump(lock_data, f) f.write("\n") log.info("Wrote lock file %s", str(lock_file_path)) # Commit changes if args.commit: sha_short = git_get_short_rev(clone_subdir, upstream_new_rev) repo_info = github_parse_url(desc.upstream.url) if repo_info is not None: sha_short = "%s/%s@%s" % (repo_info[0], repo_info[1], sha_short) commit_msg_subject = 'Update %s to %s' % (desc.name, sha_short) intro = ('Update code from {}upstream repository {} to revision {}' .format(('' if desc.upstream.only_subdir is None else 'subdir {} in '.format(desc.upstream.only_subdir)), desc.upstream.url, upstream_new_rev)) commit_msg_body = textwrap.fill(intro, width=70) if shortlog: commit_msg_body += "\n\n" commit_msg_body += format_list_to_str(shortlog, width=70) commit_msg = commit_msg_subject + "\n\n" + commit_msg_body commit_paths = [] commit_paths.append(desc.target_dir) if args.refresh_patches: commit_paths.append(desc.patch_dir) commit_paths.append(lock_file_path) git_add_commit(commit_paths, commit_msg) log.info('Import finished') if __name__ == '__main__': try: main(sys.argv) except subprocess.CalledProcessError as e: log.fatal("Called program '%s' returned with %d.\n" "STDOUT:\n%s\n" "STDERR:\n%s\n" % (" ".join(e.cmd), e.returncode, e.stdout, e.stderr)) raise except KeyboardInterrupt: log.info("Aborting operation on user request.") sys.exit(1)
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // This file is generated by the util/vendor script. Please do not modify it // manually. { upstream: { url: https://github.com/lowRISC/opentitan.git rev: 47a0f4798febd9e53dd131ef8c8c2b0255d8c139 } }
// Copyright 2020 ETH Zurich and University of Bologna. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 { name: "lowrisc_opentitan", target_dir: "lowrisc_opentitan" upstream: { url: "https://github.com/lowRISC/opentitan.git", rev: "master", }, patch_dir: "patches", mapping: [ {from: 'util/regtool.py', to: 'util/regtool.py'} {from: 'util/reggen', to: 'util/reggen', patch_dir: 'lowrisc_opentitan'} {from: 'util/topgen', to: 'util/topgen'} {from: 'hw/ip/prim/rtl/prim_subreg.sv', to: 'src/prim_subreg.sv' } {from: 'hw/ip/prim/rtl/prim_subreg_arb.sv', to: 'src/prim_subreg_arb.sv' } {from: 'hw/ip/prim/rtl/prim_subreg_ext.sv', to: 'src/prim_subreg_ext.sv' } {from: 'hw/ip/prim/rtl/prim_subreg_shadow.sv', to: 'src/prim_subreg_shadow.sv' } ] }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Register slice conforming to Comportibility guide. module prim_subreg #( parameter int DW = 32 , parameter SWACCESS = "RW", // {RW, RO, WO, W1C, W1S, W0C, RC} parameter logic [DW-1:0] RESVAL = '0 // Reset value ) ( input clk_i, input rst_ni, // From SW: valid for RW, WO, W1C, W1S, W0C, RC // In case of RC, Top connects Read Pulse to we input we, input [DW-1:0] wd, // From HW: valid for HRW, HWO input de, input [DW-1:0] d, // output to HW and Reg Read output logic qe, output logic [DW-1:0] q, output logic [DW-1:0] qs ); logic wr_en; logic [DW-1:0] wr_data; prim_subreg_arb #( .DW ( DW ), .SWACCESS ( SWACCESS ) ) wr_en_data_arb ( .we, .wd, .de, .d, .q, .wr_en, .wr_data ); always_ff @(posedge clk_i or negedge rst_ni) begin if (!rst_ni) begin qe <= 1'b0; end else begin qe <= we; end end always_ff @(posedge clk_i or negedge rst_ni) begin if (!rst_ni) begin q <= RESVAL; end else if (wr_en) begin q <= wr_data; end end assign qs = q; endmodule
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Write enable and data arbitration logic for register slice conforming to Comportibility guide. module prim_subreg_arb #( parameter int DW = 32 , parameter SWACCESS = "RW" // {RW, RO, WO, W1C, W1S, W0C, RC} ) ( // From SW: valid for RW, WO, W1C, W1S, W0C, RC. // In case of RC, top connects read pulse to we. input we, input [DW-1:0] wd, // From HW: valid for HRW, HWO. input de, input [DW-1:0] d, // From register: actual reg value. input [DW-1:0] q, // To register: actual write enable and write data. output logic wr_en, output logic [DW-1:0] wr_data ); if ((SWACCESS == "RW") || (SWACCESS == "WO")) begin : gen_w assign wr_en = we | de; assign wr_data = (we == 1'b1) ? wd : d; // SW higher priority // Unused q - Prevent lint errors. logic [DW-1:0] unused_q; assign unused_q = q; end else if (SWACCESS == "RO") begin : gen_ro assign wr_en = de; assign wr_data = d; // Unused we, wd, q - Prevent lint errors. logic unused_we; logic [DW-1:0] unused_wd; logic [DW-1:0] unused_q; assign unused_we = we; assign unused_wd = wd; assign unused_q = q; end else if (SWACCESS == "W1S") begin : gen_w1s // If SWACCESS is W1S, then assume hw tries to clear. // So, give a chance HW to clear when SW tries to set. // If both try to set/clr at the same bit pos, SW wins. assign wr_en = we | de; assign wr_data = (de ? d : q) | (we ? wd : '0); end else if (SWACCESS == "W1C") begin : gen_w1c // If SWACCESS is W1C, then assume hw tries to set. // So, give a chance HW to set when SW tries to clear. // If both try to set/clr at the same bit pos, SW wins. assign wr_en = we | de; assign wr_data = (de ? d : q) & (we ? ~wd : '1); end else if (SWACCESS == "W0C") begin : gen_w0c assign wr_en = we | de; assign wr_data = (de ? d : q) & (we ? wd : '1); end else if (SWACCESS == "RC") begin : gen_rc // This swtype is not recommended but exists for compatibility. // WARN: we signal is actually read signal not write enable. assign wr_en = we | de; assign wr_data = (de ? d : q) & (we ? '0 : '1); // Unused wd - Prevent lint errors. logic [DW-1:0] unused_wd; assign unused_wd = wd; end else begin : gen_hw assign wr_en = de; assign wr_data = d; // Unused we, wd, q - Prevent lint errors. logic unused_we; logic [DW-1:0] unused_wd; logic [DW-1:0] unused_q; assign unused_we = we; assign unused_wd = wd; assign unused_q = q; end endmodule
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Register slice conforming to Comportibility guide. module prim_subreg_ext #( parameter int unsigned DW = 32 ) ( input re, input we, input [DW-1:0] wd, input [DW-1:0] d, // output to HW and Reg Read output logic qe, output logic qre, output logic [DW-1:0] q, output logic [DW-1:0] qs ); assign qs = d; assign q = wd; assign qe = we; assign qre = re; endmodule
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // // Shadowed register slice conforming to Comportibility guide. module prim_subreg_shadow #( parameter int DW = 32 , parameter SWACCESS = "RW", // {RW, RO, WO, W1C, W1S, W0C, RC} parameter logic [DW-1:0] RESVAL = '0 // reset value ) ( input clk_i, input rst_ni, // From SW: valid for RW, WO, W1C, W1S, W0C, RC. // SW reads clear phase unless SWACCESS is RO. input re, // In case of RC, top connects read pulse to we. input we, input [DW-1:0] wd, // From HW: valid for HRW, HWO. input de, input [DW-1:0] d, // Output to HW and Reg Read output logic qe, output logic [DW-1:0] q, output logic [DW-1:0] qs, // Error conditions output logic err_update, output logic err_storage ); // Subreg control signals logic phase_clear; logic phase_q; logic staged_we, shadow_we, committed_we; logic staged_de, shadow_de, committed_de; // Subreg status and data signals logic staged_qe, shadow_qe, committed_qe; logic [DW-1:0] staged_q, shadow_q, committed_q; logic [DW-1:0] committed_qs; // Effective write enable and write data signals. // These depend on we, de and wd, d, q as well as SWACCESS. logic wr_en; logic [DW-1:0] wr_data; prim_subreg_arb #( .DW ( DW ), .SWACCESS ( SWACCESS ) ) wr_en_data_arb ( .we ( we ), .wd ( wd ), .de ( de ), .d ( d ), .q ( q ), .wr_en ( wr_en ), .wr_data ( wr_data ) ); // Phase clearing: // - SW reads clear phase unless SWACCESS is RO. // - In case of RO, SW should not interfere with update process. assign phase_clear = (SWACCESS == "RO") ? 1'b0 : re; // Phase tracker: // - Reads from SW clear the phase back to 0. // - Writes have priority (can come from SW or HW). always_ff @(posedge clk_i or negedge rst_ni) begin : phase_reg if (!rst_ni) begin phase_q <= 1'b0; end else if (wr_en) begin phase_q <= ~phase_q; end else if (phase_clear) begin phase_q <= 1'b0; end end // The staged register: // - Holds the 1's complement value. // - Written in Phase 0. assign staged_we = we & ~phase_q; assign staged_de = de & ~phase_q; prim_subreg #( .DW ( DW ), .SWACCESS ( SWACCESS ), .RESVAL ( ~RESVAL ) ) staged_reg ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .we ( staged_we ), .wd ( ~wd ), .de ( staged_de ), .d ( ~d ), .qe ( staged_qe ), .q ( staged_q ), .qs ( ) ); // The shadow register: // - Holds the 1's complement value. // - Written in Phase 1. // - Writes are ignored in case of update errors. // - Gets the value from the staged register. assign shadow_we = we & phase_q & ~err_update; assign shadow_de = de & phase_q & ~err_update; prim_subreg #( .DW ( DW ), .SWACCESS ( SWACCESS ), .RESVAL ( ~RESVAL ) ) shadow_reg ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .we ( shadow_we ), .wd ( staged_q ), .de ( shadow_de ), .d ( staged_q ), .qe ( shadow_qe ), .q ( shadow_q ), .qs ( ) ); // The committed register: // - Written in Phase 1. // - Writes are ignored in case of update errors. assign committed_we = shadow_we; assign committed_de = shadow_de; prim_subreg #( .DW ( DW ), .SWACCESS ( SWACCESS ), .RESVAL ( RESVAL ) ) committed_reg ( .clk_i ( clk_i ), .rst_ni ( rst_ni ), .we ( committed_we ), .wd ( wd ), .de ( committed_de ), .d ( d ), .qe ( committed_qe ), .q ( committed_q ), .qs ( committed_qs ) ); // Error detection - all bits must match. assign err_update = (~staged_q != wr_data) ? phase_q & wr_en : 1'b0; assign err_storage = (~shadow_q != committed_q); // Remaining output assignments assign qe = staged_qe | shadow_qe | committed_qe; assign q = committed_q; assign qs = committed_qs; endmodule
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r"""Command-line tool to validate and convert register hjson """ import argparse import logging as log import re import sys from pathlib import PurePath from reggen import (gen_cheader, gen_dv, gen_fpv, gen_html, gen_json, gen_rtl, gen_selfdoc, version) from reggen.ip_block import IpBlock DESC = """regtool, generate register info from Hjson source""" USAGE = ''' regtool [options] regtool [options] <input> regtool (-h | --help) regtool (-V | --version) ''' def main(): verbose = 0 parser = argparse.ArgumentParser( prog="regtool", formatter_class=argparse.RawDescriptionHelpFormatter, usage=USAGE, description=DESC) parser.add_argument('input', nargs='?', metavar='file', type=argparse.FileType('r'), default=sys.stdin, help='input file in Hjson type') parser.add_argument('-d', action='store_true', help='Output register documentation (html)') parser.add_argument('--cdefines', '-D', action='store_true', help='Output C defines header') parser.add_argument('--doc', action='store_true', help='Output source file documentation (gfm)') parser.add_argument('-j', action='store_true', help='Output as formatted JSON') parser.add_argument('-c', action='store_true', help='Output as JSON') parser.add_argument('-r', action='store_true', help='Output as SystemVerilog RTL') parser.add_argument('-s', action='store_true', help='Output as UVM Register class') parser.add_argument('-f', action='store_true', help='Output as FPV CSR rw assertion module') parser.add_argument('--outdir', '-t', help='Target directory for generated RTL; ' 'tool uses ../rtl if blank.') parser.add_argument('--dv-base-prefix', default='dv_base', help='Prefix for the DV register classes from which ' 'the register models are derived.') parser.add_argument('--outfile', '-o', type=argparse.FileType('w'), default=sys.stdout, help='Target filename for json, html, gfm.') parser.add_argument('--verbose', '-v', action='store_true', help='Verbose and run validate twice') parser.add_argument('--param', '-p', type=str, default="", help='''Change the Parameter values. Only integer value is supported. You can add multiple param arguments. Format: ParamA=ValA;ParamB=ValB ''') parser.add_argument('--version', '-V', action='store_true', help='Show version') parser.add_argument('--novalidate', action='store_true', help='Skip validate, just output json') args = parser.parse_args() if args.version: version.show_and_exit(__file__, ["Hjson", "Mako"]) verbose = args.verbose if (verbose): log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(message)s") # Entries are triples of the form (arg, (format, dirspec)). # # arg is the name of the argument that selects the format. format is the # name of the format. dirspec is None if the output is a single file; if # the output needs a directory, it is a default path relative to the source # file (used when --outdir is not given). arg_to_format = [('j', ('json', None)), ('c', ('compact', None)), ('d', ('html', None)), ('doc', ('doc', None)), ('r', ('rtl', 'rtl')), ('s', ('dv', 'dv')), ('f', ('fpv', 'fpv/vip')), ('cdefines', ('cdh', None))] format = None dirspec = None for arg_name, spec in arg_to_format: if getattr(args, arg_name): if format is not None: log.error('Multiple output formats specified on ' 'command line ({} and {}).'.format(format, spec[0])) sys.exit(1) format, dirspec = spec if format is None: format = 'hjson' infile = args.input # Split parameters into key=value pairs. raw_params = args.param.split(';') if args.param else [] params = [] for idx, raw_param in enumerate(raw_params): tokens = raw_param.split('=') if len(tokens) != 2: raise ValueError('Entry {} in list of parameter defaults to ' 'apply is {!r}, which is not of the form ' 'param=value.' .format(idx, raw_param)) params.append((tokens[0], tokens[1])) # Define either outfile or outdir (but not both), depending on the output # format. outfile = None outdir = None if dirspec is None: if args.outdir is not None: log.error('The {} format expects an output file, ' 'not an output directory.'.format(format)) sys.exit(1) outfile = args.outfile else: if args.outfile is not sys.stdout: log.error('The {} format expects an output directory, ' 'not an output file.'.format(format)) sys.exit(1) if args.outdir is not None: outdir = args.outdir elif infile is not sys.stdin: outdir = str(PurePath(infile.name).parents[1].joinpath(dirspec)) else: # We're using sys.stdin, so can't infer an output directory name log.error( 'The {} format writes to an output directory, which ' 'cannot be inferred automatically if the input comes ' 'from stdin. Use --outdir to specify it manually.'.format( format)) sys.exit(1) if format == 'doc': with outfile: gen_selfdoc.document(outfile) exit(0) srcfull = infile.read() try: obj = IpBlock.from_text(srcfull, params, infile.name) except ValueError as err: log.error(str(err)) exit(1) if args.novalidate: with outfile: gen_json.gen_json(obj, outfile, format) outfile.write('\n') else: if format == 'rtl': return gen_rtl.gen_rtl(obj, outdir) if format == 'dv': return gen_dv.gen_dv(obj, args.dv_base_prefix, outdir) if format == 'fpv': return gen_fpv.gen_fpv(obj, outdir) src_lic = None src_copy = '' found_spdx = None found_lunder = None copy = re.compile(r'.*(copyright.*)|(.*\(c\).*)', re.IGNORECASE) spdx = re.compile(r'.*(SPDX-License-Identifier:.+)') lunder = re.compile(r'.*(Licensed under.+)', re.IGNORECASE) for line in srcfull.splitlines(): mat = copy.match(line) if mat is not None: src_copy += mat.group(1) mat = spdx.match(line) if mat is not None: found_spdx = mat.group(1) mat = lunder.match(line) if mat is not None: found_lunder = mat.group(1) if found_lunder: src_lic = found_lunder if found_spdx: src_lic += '\n' + found_spdx with outfile: if format == 'html': return gen_html.gen_html(obj, outfile) elif format == 'cdh': return gen_cheader.gen_cdefines(obj, outfile, src_lic, src_copy) else: return gen_json.gen_json(obj, outfile, format) outfile.write('\n') if __name__ == '__main__': sys.exit(main())
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Enumerated types for fields Generated by validation, used by backends """ from enum import Enum from .lib import check_str class JsonEnum(Enum): def for_json(x) -> str: return str(x) class SwWrAccess(JsonEnum): WR = 1 NONE = 2 class SwRdAccess(JsonEnum): RD = 1 RC = 2 # Special handling for port NONE = 3 class SwAccess(JsonEnum): RO = 1 RW = 2 WO = 3 W1C = 4 W1S = 5 W0C = 6 RC = 7 R0W1C = 8 NONE = 9 class HwAccess(JsonEnum): HRO = 1 HRW = 2 HWO = 3 NONE = 4 # No access allowed # swaccess permitted values # text description, access enum, wr access enum, rd access enum, ok in window SWACCESS_PERMITTED = { 'none': ("No access", # noqa: E241 SwAccess.NONE, SwWrAccess.NONE, SwRdAccess.NONE, False), # noqa: E241 'ro': ("Read Only", # noqa: E241 SwAccess.RO, SwWrAccess.NONE, SwRdAccess.RD, True), # noqa: E241 'rc': ("Read Only, reading clears", # noqa: E241 SwAccess.RC, SwWrAccess.WR, SwRdAccess.RC, False), # noqa: E241 'rw': ("Read/Write", # noqa: E241 SwAccess.RW, SwWrAccess.WR, SwRdAccess.RD, True), # noqa: E241 'r0w1c': ("Read zero, Write with 1 clears", # noqa: E241 SwAccess.W1C, SwWrAccess.WR, SwRdAccess.NONE, False), # noqa: E241 'rw1s': ("Read, Write with 1 sets", # noqa: E241 SwAccess.W1S, SwWrAccess.WR, SwRdAccess.RD, False), # noqa: E241 'rw1c': ("Read, Write with 1 clears", # noqa: E241 SwAccess.W1C, SwWrAccess.WR, SwRdAccess.RD, False), # noqa: E241 'rw0c': ("Read, Write with 0 clears", # noqa: E241 SwAccess.W0C, SwWrAccess.WR, SwRdAccess.RD, False), # noqa: E241 'wo': ("Write Only", # noqa: E241 SwAccess.WO, SwWrAccess.WR, SwRdAccess.NONE, True) # noqa: E241 } # hwaccess permitted values HWACCESS_PERMITTED = { 'hro': ("Read Only", HwAccess.HRO), 'hrw': ("Read/Write", HwAccess.HRW), 'hwo': ("Write Only", HwAccess.HWO), 'none': ("No Access Needed", HwAccess.NONE) } class SWAccess: def __init__(self, where: str, raw: object): self.key = check_str(raw, 'swaccess for {}'.format(where)) try: self.value = SWACCESS_PERMITTED[self.key] except KeyError: raise ValueError('Unknown swaccess key, {}, for {}.' .format(self.key, where)) from None def dv_rights(self) -> str: if self.key in ['none', 'ro', 'rc']: return "RO" elif self.key in ['rw', 'r0w1c', 'rw1s', 'rw1c', 'rw0c']: return "RW" else: assert self.key == 'wo' return "WO" def swrd(self) -> SwRdAccess: return self.value[3] def allows_read(self) -> bool: return self.value[3] != SwRdAccess.NONE def allows_write(self) -> bool: return self.value[2] == SwWrAccess.WR class HWAccess: def __init__(self, where: str, raw: object): self.key = check_str(raw, 'hwaccess for {}'.format(where)) try: self.value = HWACCESS_PERMITTED[self.key] except KeyError: raise ValueError('Unknown hwaccess key, {}, for {}.' .format(self.key, where)) from None def allows_read(self) -> bool: return self.key in ['hro', 'hrw'] def allows_write(self) -> bool: return self.key in ['hrw', 'hwo']
# 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 .bits import Bits from .signal import Signal from .lib import check_keys, check_name, check_str, check_list class Alert(Signal): def __init__(self, name: str, desc: str, bit: int, fatal: bool): super().__init__(name, desc, Bits(bit, bit)) self.bit = bit self.fatal = fatal @staticmethod def from_raw(what: str, lsb: int, raw: object) -> 'Alert': rd = check_keys(raw, what, ['name', 'desc'], []) name = check_name(rd['name'], 'name field of ' + what) desc = check_str(rd['desc'], 'desc field of ' + what) # Make sense of the alert name, which should be prefixed with recov_ or # fatal_. pfx = name.split('_')[0] if pfx == 'recov': fatal = False elif pfx == 'fatal': fatal = True else: raise ValueError('Invalid name field of {}: alert names must be ' 'prefixed with "recov_" or "fatal_". Saw {!r}.' .format(what, name)) return Alert(name, desc, lsb, fatal) @staticmethod def from_raw_list(what: str, raw: object) -> List['Alert']: ret = [] for idx, entry in enumerate(check_list(raw, what)): entry_what = 'entry {} of {}'.format(idx, what) alert = Alert.from_raw(entry_what, idx, entry) ret.append(alert) return ret def _asdict(self) -> Dict[str, object]: return { 'name': self.name, 'desc': self.desc, }
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 '''Support code for bit ranges in reggen''' from typing import Tuple from .lib import check_str from .params import ReggenParams class Bits: def __init__(self, msb: int, lsb: int): assert 0 <= lsb <= msb self.msb = msb self.lsb = lsb def bitmask(self) -> int: return (1 << (self.msb + 1)) - (1 << self.lsb) def width(self) -> int: return 1 + self.msb - self.lsb def max_value(self) -> int: return (1 << self.width()) - 1 def extract_field(self, reg_val: int) -> int: return (reg_val & self.bitmask()) >> self.lsb @staticmethod def from_raw(where: str, reg_width: int, params: ReggenParams, raw: object) -> 'Bits': # Bits should be specified as msb:lsb or as just a single bit index. if isinstance(raw, int): msb = raw lsb = raw else: str_val = check_str(raw, 'bits field for {}'.format(where)) msb, lsb = Bits._parse_str(where, params, str_val) # Check that the bit indices look sensible if msb < lsb: raise ValueError('msb for {} is {}: less than {}, the msb.' .format(where, msb, lsb)) if lsb < 0: raise ValueError('lsb for {} is {}, which is negative.' .format(where, lsb)) if msb >= reg_width: raise ValueError("msb for {} is {}, which doesn't fit in {} bits." .format(where, msb, reg_width)) return Bits(msb, lsb) @staticmethod def _parse_str(where: str, params: ReggenParams, str_val: str) -> Tuple[int, int]: try: idx = int(str_val) return (idx, idx) except ValueError: # Doesn't look like an integer. Never mind: try msb:lsb pass parts = str_val.split(':') if len(parts) != 2: raise ValueError('bits field for {} is not an ' 'integer or of the form msb:lsb. Saw {!r}.' .format(where, str_val)) return (params.expand(parts[0], 'msb of bits field for {}'.format(where)), params.expand(parts[1], 'lsb of bits field for {}'.format(where))) def make_translated(self, bit_offset: int) -> 'Bits': assert 0 <= bit_offset return Bits(self.msb + bit_offset, self.lsb + bit_offset) def as_str(self) -> str: if self.lsb == self.msb: return str(self.lsb) else: assert self.lsb < self.msb return '{}:{}'.format(self.msb, self.lsb)
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # 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], 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)) self.has_unnamed_host = has_unnamed_host 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 = [] for idx, raw_entry in enumerate(check_list(raw, where)): entry_what = 'entry {} of {}'.format(idx + 1, where) ed = check_keys(raw_entry, entry_what, ['protocol', 'direction'], ['name']) protocol = check_str(ed['protocol'], 'protocol field of ' + entry_what) if not BusProtocol.has_value(protocol): raise ValueError('Unknown protocol {!r} at {}' .format(protocol, entry_what)) direction = check_str(ed['direction'], 'direction field of ' + entry_what) if direction not in ['device', 'host']: raise ValueError('Unknown interface direction {!r} at {}' .format(direction, entry_what)) name = check_optional_str(ed.get('name'), 'name field of ' + entry_what) if direction == 'host': if name is None: if has_unnamed_host: raise ValueError('Multiple un-named host ' 'interfaces at {}' .format(where)) has_unnamed_host = True else: if name in named_hosts: raise ValueError('Duplicate host interface ' 'with name {!r} at {}' .format(name, where)) named_hosts.append(name) else: if name is None: if has_unnamed_device: raise ValueError('Multiple un-named device ' 'interfaces at {}' .format(where)) has_unnamed_device = True else: if name in named_devices: raise ValueError('Duplicate device interface ' '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, interface_list) def has_host(self) -> bool: return bool(self.has_unnamed_host or self.named_hosts) def _interfaces(self) -> List[Tuple[bool, Optional[str]]]: ret = [] # type: List[Tuple[bool, Optional[str]]] if self.has_unnamed_host: ret.append((True, None)) for name in self.named_hosts: ret.append((True, name)) if self.has_unnamed_device: ret.append((False, None)) for name in self.named_devices: ret.append((False, name)) return ret @staticmethod def _if_dict(is_host: bool, name: Optional[str]) -> Dict[str, object]: ret = { 'protocol': 'tlul', 'direction': 'host' if is_host else 'device' } # type: Dict[str, object] if name is not None: ret['name'] = name return ret def as_dicts(self) -> List[Dict[str, object]]: return [BusInterfaces._if_dict(is_host, name) for is_host, name in self._interfaces()] def get_port_name(self, is_host: bool, name: Optional[str]) -> str: if is_host: tl_suffix = 'tl_h' else: tl_suffix = 'tl_d' if self.has_host() else 'tl' return (tl_suffix if name is None else '{}_{}'.format(name, tl_suffix)) def get_port_names(self, inc_hosts: bool, inc_devices: bool) -> List[str]: ret = [] for is_host, name in self._interfaces(): if not (inc_hosts if is_host else inc_devices): continue ret.append(self.get_port_name(is_host, name)) return ret def _if_inter_signal(self, is_host: bool, name: Optional[str]) -> InterSignal: return InterSignal(self.get_port_name(is_host, name), None, 'tl', 'tlul_pkg', 'req_rsp', 'rsp', 1, None) def inter_signals(self) -> List[InterSignal]: return [self._if_inter_signal(is_host, name) for is_host, name in self._interfaces()] def has_interface(self, is_host: bool, name: Optional[str]) -> bool: if is_host: if name is None: return self.has_unnamed_host else: return name in self.named_hosts else: if name is None: return self.has_unnamed_device else: return name in self.named_devices def find_port_name(self, is_host: bool, name: Optional[str]) -> str: '''Look up the given host/name pair and return its port name. Raises a KeyError if there is no match. ''' if not self.has_interface(is_host, name): called = ('with no name' if name is None else 'called {!r}'.format(name)) raise KeyError('There is no {} bus interface {}.' .format('host' if is_host else 'device', called)) return self.get_port_name(is_host, name)
# 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 .lib import check_keys, check_str, check_int REQUIRED_FIELDS = { 'name': ['s', "name of the member of the enum"], 'desc': ['t', "description when field has this value"], 'value': ['d', "value of this member of the enum"] } class EnumEntry: def __init__(self, where: str, max_val: int, raw: object): rd = check_keys(raw, where, list(REQUIRED_FIELDS.keys()), []) self.name = check_str(rd['name'], 'name field of {}'.format(where)) self.desc = check_str(rd['desc'], 'desc field of {}'.format(where)) self.value = check_int(rd['value'], 'value field of {}'.format(where)) if not (0 <= self.value <= max_val): raise ValueError("value for {} is {}, which isn't representable " "in the field (representable range: 0 .. {})." .format(where, self.value, max_val)) def _asdict(self) -> Dict[str, object]: return { 'name': self.name, 'desc': self.desc, 'value': str(self.value) }
# 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 .bits import Bits from .enum_entry import EnumEntry from .lib import (check_keys, check_str, check_name, check_list, check_str_list, check_xint) from .params import ReggenParams REQUIRED_FIELDS = { 'bits': ['b', "bit or bit range (msb:lsb)"] } OPTIONAL_FIELDS = { 'name': ['s', "name of the field"], 'desc': ['t', "description of field (required if the field has a name)"], 'swaccess': [ 's', "software access permission, copied from " "register if not provided in field. " "(Tool adds if not provided.)" ], 'hwaccess': [ 's', "hardware access permission, copied from " "register if not prvided in field. " "(Tool adds if not provided.)" ], 'resval': [ 'x', "reset value, comes from register resval " "if not provided in field. Zero if neither " "are provided and the field is readable, " "x if neither are provided and the field " "is wo. Must match if both are provided." ], 'enum': ['l', "list of permitted enumeration groups"], 'tags': [ 's', "tags for the field, followed by the format 'tag_name:item1:item2...'" ] } class Field: def __init__(self, name: str, desc: Optional[str], tags: List[str], swaccess: SWAccess, hwaccess: HWAccess, hwqe: bool, hwre: bool, bits: Bits, resval: Optional[int], enum: Optional[List[EnumEntry]]): self.name = name self.desc = desc self.tags = tags self.swaccess = swaccess self.hwaccess = hwaccess self.hwqe = hwqe self.hwre = hwre self.bits = bits self.resval = resval self.enum = enum @staticmethod def from_raw(reg_name: str, field_idx: int, num_fields: int, default_swaccess: SWAccess, default_hwaccess: HWAccess, reg_resval: Optional[int], reg_width: int, reg_hwqe: bool, reg_hwre: bool, params: ReggenParams, raw: object) -> 'Field': where = 'field {} of {} register'.format(field_idx, reg_name) rd = check_keys(raw, where, list(REQUIRED_FIELDS.keys()), list(OPTIONAL_FIELDS.keys())) raw_name = rd.get('name') if raw_name is None: name = ('field{}'.format(field_idx + 1) if num_fields > 1 else reg_name) else: name = check_name(raw_name, 'name of {}'.format(where)) raw_desc = rd.get('desc') if raw_desc is None and raw_name is not None: raise ValueError('Missing desc field for {}' .format(where)) if raw_desc is None: desc = None else: desc = check_str(raw_desc, 'desc field for {}'.format(where)) tags = check_str_list(rd.get('tags', []), 'tags for {}'.format(where)) raw_swaccess = rd.get('swaccess') if raw_swaccess is not None: swaccess = SWAccess(where, raw_swaccess) else: swaccess = default_swaccess raw_hwaccess = rd.get('hwaccess') if raw_hwaccess is not None: hwaccess = HWAccess(where, raw_hwaccess) else: hwaccess = default_hwaccess bits = Bits.from_raw(where, reg_width, params, rd['bits']) raw_resval = rd.get('resval') if raw_resval is None: # The field doesn't define a reset value. Use bits from reg_resval # if it's defined, otherwise None (which means "x"). if reg_resval is None: resval = None else: resval = bits.extract_field(reg_resval) else: # The field does define a reset value. It should be an integer or # 'x'. In the latter case, we set resval to None (as above). resval = check_xint(raw_resval, 'resval field for {}'.format(where)) if resval is None: # We don't allow a field to be explicitly 'x' on reset but for # the containing register to have a reset value. if reg_resval is not None: raise ValueError('resval field for {} is "x", but the ' 'register defines a resval as well.' .format(where)) else: # Check that the reset value is representable with bits if not (0 <= resval <= bits.max_value()): raise ValueError("resval field for {} is {}, which " "isn't representable as an unsigned " "{}-bit integer." .format(where, resval, bits.width())) # If the register had a resval, check this value matches it. if reg_resval is not None: resval_from_reg = bits.extract_field(reg_resval) if resval != resval_from_reg: raise ValueError('resval field for {} is {}, but the ' 'register defines a resval as well, ' 'where bits {}:{} would give {}.' .format(where, resval, bits.msb, bits.lsb, resval_from_reg)) raw_enum = rd.get('enum') if raw_enum is None: enum = None else: enum = [] raw_entries = check_list(raw_enum, 'enum field for {}'.format(where)) enum_val_to_name = {} # type: Dict[int, str] for idx, raw_entry in enumerate(raw_entries): entry = EnumEntry('entry {} in enum list for {}' .format(idx + 1, where), bits.max_value(), raw_entry) if entry.value in enum_val_to_name: raise ValueError('In {}, duplicate enum entries for ' 'value {} ({} and {}).' .format(where, entry.value, enum_val_to_name[entry.value], entry.name)) enum.append(entry) enum_val_to_name[entry.value] = entry.name return Field(name, desc, tags, swaccess, hwaccess, reg_hwqe, reg_hwre, bits, resval, enum) def has_incomplete_enum(self) -> bool: return (self.enum is not None and len(self.enum) != 1 + self.bits.max_value()) def get_n_bits(self, hwext: bool, bittype: List[str]) -> int: '''Get the size of this field in bits bittype should be a list of the types of signals to count. The elements should come from the following list: - 'q': A signal for the value of the field. Only needed if HW can read its contents. - 'd': A signal for the next value of the field. Only needed if HW can write its contents. - 'qe': A write enable signal for bus accesses. Only needed if HW can read the field's contents and the field has the hwqe flag. - 're': A read enable signal for bus accesses. Only needed if HW can read the field's contents and the field has the hwre flag. - 'de': A write enable signal for hardware accesses. Only needed if HW can write the field's contents and the register data is stored in the register block (true if the hwext flag is false). ''' n_bits = 0 if "q" in bittype and self.hwaccess.allows_read(): n_bits += self.bits.width() if "d" in bittype and self.hwaccess.allows_write(): n_bits += self.bits.width() if "qe" in bittype and self.hwaccess.allows_read(): n_bits += int(self.hwqe) if "re" in bittype and self.hwaccess.allows_read(): n_bits += int(self.hwre) if "de" in bittype and self.hwaccess.allows_write(): n_bits += int(not hwext) return n_bits def make_multi(self, reg_width: int, min_reg_idx: int, max_reg_idx: int, cname: str, creg_idx: int, stripped: bool) -> List['Field']: assert 0 <= min_reg_idx <= max_reg_idx # Check that we won't overflow reg_width. We assume that the LSB should # be preserved: if msb=5, lsb=2 then the replicated copies will be # [5:2], [11:8] etc. num_copies = 1 + max_reg_idx - min_reg_idx field_width = self.bits.msb + 1 if field_width * num_copies > reg_width: raise ValueError('Cannot replicate field {} {} times: the ' 'resulting width would be {}, but the register ' 'width is just {}.' .format(self.name, num_copies, field_width * num_copies, reg_width)) desc = ('For {}{}'.format(cname, creg_idx) if stripped else self.desc) enum = None if stripped else self.enum ret = [] for reg_idx in range(min_reg_idx, max_reg_idx + 1): name = '{}_{}'.format(self.name, reg_idx) bit_offset = field_width * (reg_idx - min_reg_idx) bits = (self.bits if bit_offset == 0 else self.bits.make_translated(bit_offset)) ret.append(Field(name, desc, self.tags, self.swaccess, self.hwaccess, self.hwqe, self.hwre, bits, self.resval, enum)) return ret def make_suffixed(self, suffix: str, cname: str, creg_idx: int, stripped: bool) -> 'Field': desc = ('For {}{}'.format(cname, creg_idx) if stripped else self.desc) enum = None if stripped else self.enum return Field(self.name + suffix, desc, self.tags, self.swaccess, self.hwaccess, self.hwqe, self.hwre, self.bits, self.resval, enum) def _asdict(self) -> Dict[str, object]: rd = { 'bits': self.bits.as_str(), 'name': self.name, 'swaccess': self.swaccess.key, 'hwaccess': self.hwaccess.key, 'resval': 'x' if self.resval is None else str(self.resval), 'tags': self.tags } # type: Dict[str, object] if self.desc is not None: rd['desc'] = self.desc if self.enum is not None: rd['enum'] = self.enum return rd