From 0406d2f25e828e310bf5df4d4ce973175295c83f Mon Sep 17 00:00:00 2001 From: Colin McKellar Date: Thu, 19 Nov 2026 22:27:25 +0000 Subject: [PATCH] [vendor] Vendor OpenTitan DV libraries for the UVM bench Add the OpenTitan DV libraries and DVSim/Xcelium files needed by the UART16550 UVM smoke bench, at the existing lock revision 012fb0fe3042a2ab97f9fa045520286486a4b98f: - hw/dv/sv: dv_lib, dv_utils, dv_base_agent, dv_base_reg, csr_utils, common_ifs, str_utils, bus_params_pkg, mem_model, tl_agent, uart_agent and alert_agent, which are the reused agents and the libraries they depend on (the tl_agent self-test bench is excluded) - hw/dv/tools: only the files the Xcelium flow uses: the DVSim job makefile and imported configs, the run script and the Tcl it sources, and the Xcelium coverage files referenced by the configuration Pin the description's upstream rev to the lock revision. Re-running util/vendor.py reproduces all previously vendored files unchanged and the lock file is unchanged. Signed-off-by: Colin McKellar --- hw/vendor/lowrisc_ip.vendor.hjson | 36 +- .../lowrisc_ip/dv/sv/alert_agent/README.md | 14 + .../dv/sv/alert_agent/alert_agent.core | 37 + .../dv/sv/alert_agent/alert_agent.sv | 114 +++ .../dv/sv/alert_agent/alert_agent_cfg.sv | 81 ++ .../dv/sv/alert_agent/alert_agent_cov.sv | 57 ++ .../dv/sv/alert_agent/alert_agent_pkg.sv | 57 ++ .../dv/sv/alert_agent/alert_base_driver.sv | 48 + .../lowrisc_ip/dv/sv/alert_agent/alert_if.sv | 170 ++++ .../dv/sv/alert_agent/alert_monitor.sv | 533 +++++++++++ .../sv/alert_agent/alert_receiver_driver.sv | 466 ++++++++++ .../dv/sv/alert_agent/alert_sender_driver.sv | 268 ++++++ .../dv/sv/alert_agent/alert_seq_item.sv | 111 +++ .../dv/sv/alert_agent/alert_sequencer.sv | 12 + .../lowrisc_ip/dv/sv/alert_agent/data/BUILD | 10 + .../data/alert_agent_testplan.hjson | 28 + .../seq_lib/alert_receiver_alert_rsp_seq.sv | 61 ++ .../seq_lib/alert_receiver_base_seq.sv | 44 + .../seq_lib/alert_receiver_ping_seq.sv | 42 + .../alert_agent/seq_lib/alert_receiver_seq.sv | 21 + .../seq_lib/alert_sender_base_seq.sv | 56 ++ .../seq_lib/alert_sender_ping_rsp_seq.sv | 62 ++ .../alert_agent/seq_lib/alert_sender_seq.sv | 23 + .../lowrisc_ip/dv/sv/bus_params_pkg/README.md | 10 + .../dv/sv/bus_params_pkg/bus_params_pkg.core | 19 + .../dv/sv/bus_params_pkg/bus_params_pkg.sv | 64 ++ .../lowrisc_ip/dv/sv/common_ifs/README.md | 114 +++ .../lowrisc_ip/dv/sv/common_ifs/clk_if.sv | 29 + .../lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv | 362 ++++++++ .../dv/sv/common_ifs/common_ifs.core | 22 + .../dv/sv/common_ifs/common_ifs_pkg.sv | 15 + .../entropy_subsys_fifo_exception_if.core | 20 + .../entropy_subsys_fifo_exception_if.sv | 59 ++ .../entropy_subsys_fifo_exception_pkg.sv | 18 + .../lowrisc_ip/dv/sv/common_ifs/pins_if.sv | 116 +++ .../lowrisc_ip/dv/sv/common_ifs/pins_if.svg | 96 ++ .../lowrisc_ip/dv/sv/common_ifs/pins_ifs.core | 17 + .../dv/sv/common_ifs/rst_shadowed_if.core | 17 + .../dv/sv/common_ifs/rst_shadowed_if.sv | 39 + .../lowrisc_ip/dv/sv/csr_utils/README.md | 134 +++ .../dv/sv/csr_utils/csr_aliasing_seq.sv | 172 ++++ .../dv/sv/csr_utils/csr_base_seq.sv | 239 +++++ .../dv/sv/csr_utils/csr_hw_reset_seq.sv | 65 ++ .../lowrisc_ip/dv/sv/csr_utils/csr_seq_lib.sv | 340 +++++++ .../lowrisc_ip/dv/sv/csr_utils/csr_utils.core | 24 + .../dv/sv/csr_utils/csr_utils_pkg.sv | 868 ++++++++++++++++++ .../dv/sv/dv_base_agent/dv_base_agent.core | 32 + .../dv/sv/dv_base_agent/dv_base_agent.sv | 86 ++ .../dv/sv/dv_base_agent/dv_base_agent_cfg.sv | 53 ++ .../dv/sv/dv_base_agent/dv_base_agent_cov.sv | 18 + .../dv/sv/dv_base_agent/dv_base_agent_pkg.sv | 33 + .../dv/sv/dv_base_agent/dv_base_driver.sv | 91 ++ .../dv/sv/dv_base_agent/dv_base_monitor.sv | 110 +++ .../dv/sv/dv_base_agent/dv_base_seq.sv | 25 + .../dv/sv/dv_base_agent/dv_base_sequencer.sv | 18 + .../dv/sv/dv_base_agent/dv_reactive_agent.sv | 59 ++ .../sv/dv_base_agent/dv_reactive_agent_cfg.sv | 27 + .../sv/dv_base_agent/dv_reactive_monitor.sv | 31 + .../sv/dv_base_agent/dv_reactive_sequencer.sv | 38 + .../dv/sv/dv_base_reg/csr_excl_item.sv | 161 ++++ .../dv_base_reg/dv_base_lockable_field_cov.sv | 50 + .../dv/sv/dv_base_reg/dv_base_mem.sv | 93 ++ .../dv/sv/dv_base_reg/dv_base_mubi_cov.sv | 136 +++ .../dv/sv/dv_base_reg/dv_base_reg.core | 29 + .../dv/sv/dv_base_reg/dv_base_reg.sv | 591 ++++++++++++ .../dv/sv/dv_base_reg/dv_base_reg_block.sv | 616 +++++++++++++ .../dv/sv/dv_base_reg/dv_base_reg_field.sv | 381 ++++++++ .../dv/sv/dv_base_reg/dv_base_reg_map.sv | 9 + .../dv/sv/dv_base_reg/dv_base_reg_pkg.sv | 145 +++ .../dv_base_reg/dv_base_shadowed_field_cov.sv | 29 + hw/vendor/lowrisc_ip/dv/sv/dv_lib/README.md | 52 ++ .../dv/sv/dv_lib/bit_toggle_cg_wrap.sv | 42 + .../lowrisc_ip/dv/sv/dv_lib/dv_base_env.sv | 94 ++ .../dv/sv/dv_lib/dv_base_env_cfg.sv | 347 +++++++ .../dv/sv/dv_lib/dv_base_env_cov.sv | 16 + .../dv/sv/dv_lib/dv_base_scoreboard.sv | 81 ++ .../lowrisc_ip/dv/sv/dv_lib/dv_base_test.sv | 163 ++++ .../dv/sv/dv_lib/dv_base_virtual_sequencer.sv | 32 + .../lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv | 291 ++++++ hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib.core | 32 + .../lowrisc_ip/dv/sv/dv_lib/dv_lib_pkg.sv | 36 + hw/vendor/lowrisc_ip/dv/sv/dv_utils/README.md | 0 .../dv/sv/dv_utils/dv_fcov_macros.core | 17 + .../dv/sv/dv_utils/dv_fcov_macros.svh | 112 +++ .../lowrisc_ip/dv/sv/dv_utils/dv_macros.core | 17 + .../lowrisc_ip/dv/sv/dv_utils/dv_macros.svh | 651 +++++++++++++ .../dv/sv/dv_utils/dv_report_catcher.sv | 46 + .../dv/sv/dv_utils/dv_report_server.sv | 66 ++ .../dv/sv/dv_utils/dv_test_status.core | 19 + .../dv/sv/dv_utils/dv_test_status_pkg.sv | 38 + .../lowrisc_ip/dv/sv/dv_utils/dv_utils.core | 27 + .../lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv | 350 +++++++ .../lowrisc_ip/dv/sv/mem_model/README.md | 27 + .../lowrisc_ip/dv/sv/mem_model/mem_model.core | 21 + .../lowrisc_ip/dv/sv/mem_model/mem_model.sv | 99 ++ .../dv/sv/mem_model/mem_model_pkg.sv | 13 + .../lowrisc_ip/dv/sv/str_utils/README.md | 6 + .../lowrisc_ip/dv/sv/str_utils/str_utils.core | 19 + .../dv/sv/str_utils/str_utils_pkg.sv | 236 +++++ hw/vendor/lowrisc_ip/dv/sv/tl_agent/README.md | 3 + .../dv/sv/tl_agent/seq_lib/tl_device_seq.sv | 187 ++++ .../sv/tl_agent/seq_lib/tl_host_base_seq.sv | 86 ++ .../sv/tl_agent/seq_lib/tl_host_custom_seq.sv | 20 + .../seq_lib/tl_host_protocol_err_seq.sv | 18 + .../dv/sv/tl_agent/seq_lib/tl_host_seq.sv | 104 +++ .../sv/tl_agent/seq_lib/tl_host_single_seq.sv | 50 + .../dv/sv/tl_agent/seq_lib/tl_seq_list.sv | 10 + .../lowrisc_ip/dv/sv/tl_agent/tl_agent.core | 40 + .../lowrisc_ip/dv/sv/tl_agent/tl_agent.sv | 41 + .../lowrisc_ip/dv/sv/tl_agent/tl_agent_cfg.sv | 251 +++++ .../lowrisc_ip/dv/sv/tl_agent/tl_agent_cov.sv | 131 +++ .../lowrisc_ip/dv/sv/tl_agent/tl_agent_pkg.sv | 89 ++ .../dv/sv/tl_agent/tl_device_driver.sv | 128 +++ .../dv/sv/tl_agent/tl_host_driver.sv | 381 ++++++++ hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_if.sv | 45 + .../lowrisc_ip/dv/sv/tl_agent/tl_monitor.sv | 293 ++++++ .../dv/sv/tl_agent/tl_reg_adapter.sv | 185 ++++ .../lowrisc_ip/dv/sv/tl_agent/tl_seq_item.sv | 472 ++++++++++ .../lowrisc_ip/dv/sv/tl_agent/tl_sequencer.sv | 17 + .../lowrisc_ip/dv/sv/uart_agent/README.md | 3 + .../dv/sv/uart_agent/seq_lib/uart_base_seq.sv | 18 + .../sv/uart_agent/seq_lib/uart_default_seq.sv | 18 + .../dv/sv/uart_agent/seq_lib/uart_seq.sv | 37 + .../dv/sv/uart_agent/seq_lib/uart_seq_list.sv | 7 + .../dv/sv/uart_agent/uart_agent.core | 32 + .../lowrisc_ip/dv/sv/uart_agent/uart_agent.sv | 44 + .../dv/sv/uart_agent/uart_agent_cfg.sv | 103 +++ .../dv/sv/uart_agent/uart_agent_cov.sv | 33 + .../dv/sv/uart_agent/uart_agent_pkg.sv | 63 ++ .../dv/sv/uart_agent/uart_driver.sv | 74 ++ .../lowrisc_ip/dv/sv/uart_agent/uart_if.sv | 65 ++ .../lowrisc_ip/dv/sv/uart_agent/uart_item.sv | 46 + .../dv/sv/uart_agent/uart_logger.sv | 98 ++ .../dv/sv/uart_agent/uart_monitor.sv | 211 +++++ .../dv/sv/uart_agent/uart_sequencer.sv | 10 + hw/vendor/lowrisc_ip/dv/tools/common.tcl | 73 ++ .../dv/tools/dvsim/common_modes.hjson | 82 ++ .../lowrisc_ip/dv/tools/dvsim/fusesoc.hjson | 16 + hw/vendor/lowrisc_ip/dv/tools/dvsim/sim.mk | 137 +++ .../lowrisc_ip/dv/tools/dvsim/xcelium.hjson | 283 ++++++ hw/vendor/lowrisc_ip/dv/tools/sim.tcl | 60 ++ hw/vendor/lowrisc_ip/dv/tools/waves.tcl | 163 ++++ .../lowrisc_ip/dv/tools/xcelium/common.ccf | 56 ++ .../dv/tools/xcelium/common_cov_excl.tcl | 10 + .../lowrisc_ip/dv/tools/xcelium/cov_merge.tcl | 26 + .../dv/tools/xcelium/cov_report.tcl | 75 ++ .../lowrisc_ip/dv/tools/xcelium/cover.ccf | 53 ++ hw/vendor/lowrisc_ip/dv/tools/xcelium/unr.cfg | 15 + 148 files changed, 15482 insertions(+), 1 deletion(-) create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_base_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_monitor.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_receiver_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sender_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_seq_item.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/BUILD create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/alert_agent_testplan.hjson create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_alert_rsp_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_ping_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_ping_rsp_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.svg create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_ifs.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_aliasing_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_hw_reset_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_seq_lib.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_monitor.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_monitor.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/csr_excl_item.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_lockable_field_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mem.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_block.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_field.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_map.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_shadowed_field_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/bit_toggle_cg_wrap.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_scoreboard.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_test.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_virtual_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.svh create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.svh create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_catcher.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_server.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/mem_model/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/str_utils/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_device_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_custom_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_protocol_err_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_single_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_seq_list.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_device_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_host_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_monitor.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_reg_adapter.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_seq_item.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/README.md create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_base_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_default_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq_list.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.core create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cfg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cov.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_pkg.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_driver.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_if.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_item.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_logger.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_monitor.sv create mode 100644 hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_sequencer.sv create mode 100644 hw/vendor/lowrisc_ip/dv/tools/common.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/dvsim/common_modes.hjson create mode 100644 hw/vendor/lowrisc_ip/dv/tools/dvsim/fusesoc.hjson create mode 100644 hw/vendor/lowrisc_ip/dv/tools/dvsim/sim.mk create mode 100644 hw/vendor/lowrisc_ip/dv/tools/dvsim/xcelium.hjson create mode 100644 hw/vendor/lowrisc_ip/dv/tools/sim.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/waves.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/common.ccf create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/common_cov_excl.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_merge.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_report.tcl create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/cover.ccf create mode 100644 hw/vendor/lowrisc_ip/dv/tools/xcelium/unr.cfg diff --git a/hw/vendor/lowrisc_ip.vendor.hjson b/hw/vendor/lowrisc_ip.vendor.hjson index 57ff6d8..51329cf 100644 --- a/hw/vendor/lowrisc_ip.vendor.hjson +++ b/hw/vendor/lowrisc_ip.vendor.hjson @@ -8,7 +8,8 @@ upstream: { url: "https://github.com/lowRISC/opentitan" - rev: "master" + // Pinned to the lock revision so the description alone is reproducible. + rev: "012fb0fe3042a2ab97f9fa045520286486a4b98f" } mapping: [ @@ -25,6 +26,37 @@ {from: "hw/check_tool_requirements.py", to: "check_tool_requirements.py"}, {from: "hw/tool_requirements.py", to: "tool_requirements.py", patch_dir: "scripts"}, + // DV libraries for the UVM bench (hw/ip/uart16550/dv), with their dependencies + {from: "hw/dv/sv/alert_agent", to: "dv/sv/alert_agent"}, + {from: "hw/dv/sv/bus_params_pkg", to: "dv/sv/bus_params_pkg"}, + {from: "hw/dv/sv/common_ifs", to: "dv/sv/common_ifs"}, + {from: "hw/dv/sv/csr_utils", to: "dv/sv/csr_utils"}, + {from: "hw/dv/sv/dv_base_agent", to: "dv/sv/dv_base_agent"}, + {from: "hw/dv/sv/dv_base_reg", to: "dv/sv/dv_base_reg"}, + {from: "hw/dv/sv/dv_lib", to: "dv/sv/dv_lib"}, + {from: "hw/dv/sv/dv_utils", to: "dv/sv/dv_utils"}, + {from: "hw/dv/sv/mem_model", to: "dv/sv/mem_model"}, + {from: "hw/dv/sv/str_utils", to: "dv/sv/str_utils"}, + {from: "hw/dv/sv/tl_agent", to: "dv/sv/tl_agent"}, + {from: "hw/dv/sv/uart_agent", to: "dv/sv/uart_agent"}, + + // Only the DVSim/Xcelium files the smoke flow uses: the job makefile, configs imported + // by the project sim cfg, the run script with the Tcl it sources (waves for debug), and + // the coverage files referenced by xcelium.hjson and the project sim cfg. + {from: "hw/dv/tools/dvsim/sim.mk", to: "dv/tools/dvsim/sim.mk"}, + {from: "hw/dv/tools/dvsim/common_modes.hjson", to: "dv/tools/dvsim/common_modes.hjson"}, + {from: "hw/dv/tools/dvsim/fusesoc.hjson", to: "dv/tools/dvsim/fusesoc.hjson"}, + {from: "hw/dv/tools/dvsim/xcelium.hjson", to: "dv/tools/dvsim/xcelium.hjson"}, + {from: "hw/dv/tools/sim.tcl", to: "dv/tools/sim.tcl"}, + {from: "hw/dv/tools/common.tcl", to: "dv/tools/common.tcl"}, + {from: "hw/dv/tools/waves.tcl", to: "dv/tools/waves.tcl"}, + {from: "hw/dv/tools/xcelium/cover.ccf", to: "dv/tools/xcelium/cover.ccf"}, + {from: "hw/dv/tools/xcelium/common.ccf", to: "dv/tools/xcelium/common.ccf"}, + {from: "hw/dv/tools/xcelium/unr.cfg", to: "dv/tools/xcelium/unr.cfg"}, + {from: "hw/dv/tools/xcelium/common_cov_excl.tcl", to: "dv/tools/xcelium/common_cov_excl.tcl"}, + {from: "hw/dv/tools/xcelium/cov_merge.tcl", to: "dv/tools/xcelium/cov_merge.tcl"}, + {from: "hw/dv/tools/xcelium/cov_report.tcl", to: "dv/tools/xcelium/cov_report.tcl"}, + // Commit linting scripts {from: "util/lint_commits.py", to: "util/lint_commits.py"}, {from: "ci/scripts/lint-commits.sh", to: "ci/scripts/lint-commits.sh", patch_dir: "ci"}, @@ -38,5 +70,7 @@ "hw/ip/prim/util", "hw/ip/tlul/generic_dv", "hw/ip/uart/dv", + // Self-test bench of the TL agent + "hw/dv/sv/tl_agent/dv", ] } diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/README.md b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/README.md new file mode 100644 index 0000000..5206a3c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/README.md @@ -0,0 +1,14 @@ +# Alert agent + +The alert agent extends from the `dv_lib` agent classes. + +## Description + +This agent implements the alert interface protocol. +For design documentation, please refer to [alert_handler spec](../../../top_earlgrey/ip_autogen/alert_handler/README.md). +The agent can be configured to behave as an alert sender (host mode) or receiver (device mode). + +## Device Agent + +For IPs that send out alerts, it is recommended to attach alert device agents to the block level testbench. +Please refer to [cip_lib documentation](../cip_lib/README.md) regarding instructions to configure alert device agent in DV testbenches. diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.core b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.core new file mode 100644 index 0000000..0c5ab78 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.core @@ -0,0 +1,37 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:alert_agent" +description: "A UVM agent that interacts with the alert interface" + +filesets: + files_dv: + depend: + - lowrisc:prim:all:0.1 + - lowrisc:dv:dv_lib + files: + - alert_if.sv + - alert_agent_pkg.sv + - alert_agent_cfg.sv: {is_include_file: true} + - alert_agent.sv: {is_include_file: true} + - alert_agent_cov.sv: {is_include_file: true} + - alert_base_driver.sv: {is_include_file: true} + - alert_sender_driver.sv: {is_include_file: true} + - alert_receiver_driver.sv: {is_include_file: true} + - alert_monitor.sv: {is_include_file: true} + - alert_seq_item.sv: {is_include_file: true} + - alert_sequencer.sv: {is_include_file: true} + - seq_lib/alert_receiver_base_seq.sv: {is_include_file: true} + - seq_lib/alert_receiver_alert_rsp_seq.sv: {is_include_file: true} + - seq_lib/alert_receiver_ping_seq.sv: {is_include_file: true} + - seq_lib/alert_receiver_seq.sv: {is_include_file: true} + - seq_lib/alert_sender_base_seq.sv: {is_include_file: true} + - seq_lib/alert_sender_ping_rsp_seq.sv: {is_include_file: true} + - seq_lib/alert_sender_seq.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.sv new file mode 100644 index 0000000..46dea28 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent.sv @@ -0,0 +1,114 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// An agent that represents an alert interface. + +class alert_agent extends dv_reactive_agent #( + .CFG_T (alert_agent_cfg), + .DRIVER_T (alert_base_driver), + .HOST_DRIVER_T (alert_sender_driver), + .DEVICE_DRIVER_T (alert_receiver_driver), + .SEQUENCER_T (alert_sequencer), + .MONITOR_T (alert_monitor), + .COV_T (alert_agent_cov) + ); + + `uvm_component_utils(alert_agent) + + // An output port that reports alert items that have been seen. + uvm_analysis_port #(alert_seq_item) m_alert_port; + + extern function new (string name, uvm_component parent); + extern function void build_phase(uvm_phase phase); + // Create automatic response (from monitor) to ping and alert requests. + extern function void connect_phase(uvm_phase phase); + extern virtual task run_phase(uvm_phase phase); + +endclass : alert_agent + +function alert_agent::new (string name, uvm_component parent); + super.new(name, parent); +endfunction : new + +function void alert_agent::build_phase(uvm_phase phase); + alert_agent_cfg cfg; + if (!uvm_config_db#(CFG_T)::get(this, "", "cfg", cfg)) begin + `uvm_fatal(`gfn, $sformatf("failed to get %s from uvm_config_db", cfg.get_type_name())) + end + + // The reactive agent upon which we build will have a request fifo iff the agent is active. + cfg.has_req_fifo = cfg.is_active; + + super.build_phase(phase); + + m_alert_port = new("m_alert_port", this); + + void'($value$plusargs("bypass_alert_ready_to_end_check=%0b", + cfg.bypass_alert_ready_to_end_check)); + + // get alert_if handle + if (!uvm_config_db#(virtual alert_if)::get(this, "", "vif", cfg.vif)) begin + `uvm_fatal(`gfn, "failed to get alert_if handle from uvm_config_db") + end + + // set variables to alert interface + cfg.vif.is_async = cfg.is_async; + cfg.vif.is_active = cfg.is_active; + cfg.vif.if_mode = cfg.if_mode; + + // set async alert clock frequency + if (cfg.is_async) begin + cfg.vif.clk_rst_async_if.set_active(.drive_rst_n_val(0)); + if (cfg.clk_freq_mhz > 0) begin + int min_freq_mhz = (cfg.clk_freq_mhz / 10) ? (cfg.clk_freq_mhz / 10) : 1; + cfg.vif.clk_rst_async_if.set_freq_mhz($urandom_range(min_freq_mhz, cfg.clk_freq_mhz * 10)); + end else begin + cfg.vif.clk_rst_async_if.set_freq_mhz($urandom_range(10, 240)); + end + end + + // Configure the sequencer to take priorities into account. This allows alert responses to be + // scheduled over ping requests, which come from a sequence that is started with low priority. + if (sequencer != null) sequencer.set_arbitration(UVM_SEQ_ARB_STRICT_FIFO); +endfunction : build_phase + +function void alert_agent::connect_phase(uvm_phase phase); + super.connect_phase(phase); + if (cfg.has_req_fifo) begin + monitor.req_analysis_port.connect(sequencer.req_analysis_fifo.analysis_export); + end + + monitor.m_alert_port.connect(m_alert_port); +endfunction : connect_phase + +task alert_agent::run_phase(uvm_phase phase); + super.run_phase(phase); + if (cfg.is_active && cfg.start_default_rsp_seq) begin + // For host mode, run alert ping auto-response sequence. + if (cfg.if_mode == dv_utils_pkg::Host) begin + alert_sender_ping_rsp_seq m_seq = + alert_sender_ping_rsp_seq::type_id::create("m_seq", this); + uvm_config_db#(uvm_object_wrapper)::set(null, {sequencer.get_full_name(), ".run_phase"}, + "default_sequence", m_seq.get_type()); + sequencer.start_phase_sequence(phase); + end else begin + alert_receiver_alert_rsp_seq response_seq; + alert_receiver_ping_seq ping_seq; + + // For device mode, run an alert auto-response sequence, which will only have a sequence + // item when an alert is generated by the device. + response_seq = alert_receiver_alert_rsp_seq::type_id::create("response_seq", this); + uvm_config_db#(uvm_object_wrapper)::set(null, {sequencer.get_full_name(), ".run_phase"}, + "default_sequence", response_seq.get_type()); + sequencer.start_phase_sequence(phase); + + // Also run an alert ping sequence, which will send back-to-back sequence items that wait a + // while and then request a ping (stopping immediately if a genuine alert has been raised). + // The priority is low so that the response sequence will take precedence. + ping_seq = alert_receiver_ping_seq::type_id::create("ping_seq", this); + `DV_CHECK_FATAL(ping_seq.randomize()) + ping_seq.start(sequencer, .this_priority(1)); + end + end +endtask diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cfg.sv new file mode 100644 index 0000000..b0950e3 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cfg.sv @@ -0,0 +1,81 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class alert_agent_cfg extends dv_reactive_agent_cfg; + virtual alert_if vif; + + bit is_async = 0; + bit en_ping_cov = 1; + bit en_lpg_cov = 1; + bit alert_init_done = 0; + bit en_alert_lpg = 0; + + // Enabled via plusarg. + // Please only use this plusarg in top-level test. + // For IP level test, please set `exp_fatal_alert` in post_start() instead. + bit bypass_alert_ready_to_end_check = 0; + + // When this flag is set to 1, and agent in alert host mode, the sequence will automatically + // response to alert ping requests. + bit start_default_rsp_seq = 1; + + // Control if ping response will timeout or not. + bit ping_timeout = 0; + + // Monitor will set this value to 1 when the agent is under ping handshake. + bit under_ping_handshake = 0; + + // Monitor will set this value to 1 when the agent is under ping handshake phase 2. + bit under_ping_handshake_ph_2 = 0; + + // dut clk frequency, used to generate alert async_clk frequency + int clk_freq_mhz; + + // sender mode + int unsigned alert_delay_min = 0; + int unsigned alert_delay_max = 10; + + // receiver mode + int unsigned ack_delay_min = 0; + int unsigned ack_delay_max = 10; + + int unsigned ack_stable_min = 0; + int unsigned ack_stable_max = 10; + + // The minimum and maximum value that alert_receiver_ping_seq will use for ping_delay + // + // To enable a "stress test", which sends lots of back-to-back ping items, these can be made + // small. + int unsigned ping_delay_min = 10000; + int unsigned ping_delay_max = 20000; + + // When this bit is set, alert agent responds to alert without delay + // This is set by plusarg "+fast_rcvr_{alert_name}" + bit fast_rcvr = 0; + + int unsigned ping_timeout_cycle = 32; + + // Incremented by the monitor on each ping + int unsigned ping_count = 0; + // Needed for alert checks starting after a ping + // This flag is updated in the alert_monitor task `monitor_ping` when a ping is detected. + bit active_ping = 0; + + `uvm_object_utils_begin(alert_agent_cfg) + `uvm_field_int(alert_delay_min, UVM_DEFAULT) + `uvm_field_int(alert_delay_max, UVM_DEFAULT) + `uvm_field_int(ack_delay_min, UVM_DEFAULT) + `uvm_field_int(ack_delay_max, UVM_DEFAULT) + `uvm_field_int(ack_stable_min, UVM_DEFAULT) + `uvm_field_int(ack_stable_max, UVM_DEFAULT) + `uvm_field_int(ping_delay_max, UVM_DEFAULT) + `uvm_object_utils_end + + extern function new (string name=""); + +endclass : alert_agent_cfg + +function alert_agent_cfg::new (string name=""); + super.new(name); +endfunction : new diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cov.sv new file mode 100644 index 0000000..1a7df9f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_cov.sv @@ -0,0 +1,57 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A general covergroup to track completion / alerts in an alert interface. The status input to the +// sample() function should be an alert_handshake_e enum value, but the function takes an int +// unsigned (the encoding of the enum) to avoid needing to parameterise the type. +covergroup handshake_complete_cg (int unsigned complete_status) + with function sample(int unsigned handshake_status); + option.per_instance = 1; + + cp_handshake_complete: coverpoint handshake_status { + bins complete = {complete_status}; + } +endgroup : handshake_complete_cg + +covergroup alert_trans_cg with function sample(alert_trans_type_e trans); + option.per_instance = 1; + + cp_handshake_complete: coverpoint trans { + bins alert_trans = {AlertSigTrans}; + bins ping_trans = {AlertPingTrans}; + } +endgroup : alert_trans_cg + +covergroup alert_lpg_cg with function sample(bit alert_lpg_en); + option.per_instance = 1; + cp_alert_lpg: coverpoint alert_lpg_en; +endgroup + +// If a module contains alert ports, these covergroups can check if all alerts/pings have been +// completed. +class alert_agent_cov extends dv_base_agent_cov #(alert_agent_cfg); + + handshake_complete_cg m_handshake_complete_cg; + alert_trans_cg m_alert_trans_cg; + alert_lpg_cg m_alert_lpg_cg; + + `uvm_component_utils(alert_agent_cov) + + extern function new (string name, uvm_component parent); + extern function void build_phase(uvm_phase phase); + +endclass : alert_agent_cov + +function alert_agent_cov::new (string name, uvm_component parent); + super.new(name, parent); +endfunction : new + +function void alert_agent_cov::build_phase(uvm_phase phase); + super.build_phase(phase); + + if (cfg.en_ping_cov) m_alert_trans_cg = new(); + if (cfg.en_lpg_cov) m_alert_lpg_cg = new(); + + m_handshake_complete_cg = new(AlertAckComplete); +endfunction : build_phase diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_pkg.sv new file mode 100644 index 0000000..8f8fb90 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_agent_pkg.sv @@ -0,0 +1,57 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package alert_agent_pkg; + // dep packages + import uvm_pkg::*; + import dv_base_agent_pkg::*; + import dv_lib_pkg::*; + import dv_utils_pkg::*; + import prim_alert_pkg::*; + + // 2 clock cycles between two alert handshakes, 1 clock cycle to go back to `Idle` state, + // 1 clock cycle for monitor to detect alert, and 1 for synchronizer skip. + parameter uint ALERT_B2B_DELAY = 5; + + typedef class alert_agent_cfg; + + typedef enum { + AlertPingTrans, + AlertSigTrans, + AlertIntFail + } alert_trans_type_e; + + typedef enum { + AlertPingReceived, + AlertReceived, + AlertAckReceived, + AlertComplete, + AlertAckComplete + } alert_handshake_e; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + `include "alert_seq_item.sv" + + `include "alert_agent_cfg.sv" + `include "alert_agent_cov.sv" + `include "alert_base_driver.sv" + `include "alert_sender_driver.sv" + `include "alert_receiver_driver.sv" + `include "alert_sequencer.sv" + `include "alert_monitor.sv" + + // Sequences + `include "seq_lib/alert_receiver_base_seq.sv" + `include "seq_lib/alert_receiver_alert_rsp_seq.sv" + `include "seq_lib/alert_receiver_ping_seq.sv" + `include "seq_lib/alert_receiver_seq.sv" + `include "seq_lib/alert_sender_base_seq.sv" + `include "seq_lib/alert_sender_ping_rsp_seq.sv" + `include "seq_lib/alert_sender_seq.sv" + + `include "alert_agent.sv" +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_base_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_base_driver.sv new file mode 100644 index 0000000..d1148aa --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_base_driver.sv @@ -0,0 +1,48 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Virtual base class used for alert_sender_driver and alert_receiver_driver + +virtual class alert_base_driver extends dv_base_driver#(alert_seq_item, alert_agent_cfg); + // Items that have been taken from seq_item_port and should be sent + protected uvm_tlm_analysis_fifo #(alert_seq_item) m_requests; + + extern function new (string name, uvm_component parent); + + // Take items from the sequencer and drive them. This implements a task from dv_base_driver. + extern virtual task get_and_drive(); + + // Monitor seq_item_port and add the items to the various queues + // + // This is run by get_and_drive. + extern local task get_req(); + + // Drive items that have been added to the various queues by get_req + // + // This should run forever and is started by get_and_drive. + pure virtual task drive_req(); +endclass + +function alert_base_driver::new (string name, uvm_component parent); + super.new(name, parent); + m_requests = new("m_requests", this); +endfunction : new + +task alert_base_driver::get_and_drive(); + fork + get_req(); + drive_req(); + join +endtask + +task alert_base_driver::get_req(); + wait(!cfg.in_reset); + forever begin + alert_seq_item req_clone; + seq_item_port.get(req); + `downcast(req_clone, req.clone()); + req_clone.set_id_info(req); + m_requests.write(req_clone); + end +endtask : get_req diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_if.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_if.sv new file mode 100644 index 0000000..5c29c17 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_if.sv @@ -0,0 +1,170 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +interface alert_if(input clk, input rst_n); + import uvm_pkg::*; + + wire prim_alert_pkg::alert_tx_t alert_tx; + wire prim_alert_pkg::alert_rx_t alert_rx; + + prim_alert_pkg::alert_tx_t alert_tx_sync_dly2; // sync alert_tx 2 clk cycle delay flop + prim_alert_pkg::alert_tx_t alert_tx_sync_dly1; // sync alert_tx 1 clk cycle delay flop + // final alert_tx value depends if on async and host mode + prim_alert_pkg::alert_tx_t alert_tx_final; + + prim_alert_pkg::alert_rx_t alert_rx_sync_dly2; // sync alert_rx 2 clk cycle delay flop + prim_alert_pkg::alert_rx_t alert_rx_sync_dly1; // sync alert_rx 1 clk cycle delay flop + // final alert_rx value depends if on async and device mode + prim_alert_pkg::alert_rx_t alert_rx_final; + + prim_alert_pkg::alert_tx_t alert_tx_int; // internal alert_tx + prim_alert_pkg::alert_rx_t alert_rx_int; // internal alert_rx + + wire async_clk; + bit is_async, is_active; + dv_utils_pkg::if_mode_e if_mode; + clk_rst_if clk_rst_async_if(.clk(async_clk), .rst_n(rst_n)); + + logic ping_pq; + always_ff @(posedge clk or negedge rst_n) begin + ping_pq <= alert_rx.ping_p; + end + + // Code ping_request and alert_active so they will not assert for unknown values. + logic ping_request; + always_comb ping_request = (alert_rx.ping_p ^ ping_pq) === 1'b1; + + logic alert_active; + always_comb alert_active = (alert_tx.alert_p ^ alert_tx.alert_n) === 1'b1 && alert_tx.alert_p; + + logic alert_inactive; + always_comb alert_inactive = (alert_tx.alert_p ^ alert_tx.alert_n) === 1'b1 && alert_tx.alert_n; + + typedef enum logic [1:0] { IdleSt, PingSt, AlertSt } state_e; + state_e state_d, state_q; + // Delaying the state in the same way as the alert_tx/rx signals + state_e state_q_dly1, state_q_final; + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + state_q <= IdleSt; + state_q_dly1 <= IdleSt; + state_q_final <= IdleSt; + end else begin + state_q <= state_d; + state_q_dly1 <= state_q; + state_q_final <= state_q_dly1; + end + end + + always_comb begin + state_d = state_q; + unique case (state_q) + IdleSt: if (ping_request) state_d = PingSt; + PingSt: if (alert_active) state_d = AlertSt; + AlertSt: if (alert_inactive) state_d = IdleSt; + default: state_d = IdleSt; + endcase // unique case (state_q) + end + + logic ping_pending; + always_comb ping_pending = state_q_final != IdleSt; + + // if alert sender is async mode, the clock will be driven in alert_agent, + // if it is sync mode, will assign to dut clk here + assign async_clk = (is_async) ? 'z : clk ; + + // async interface for alert_tx has two_clock cycles delay + // ICEBOX(#3275): this is not needed once the CDC module is implemented + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + alert_tx_sync_dly2 <= {2'b01}; + alert_tx_sync_dly1 <= {2'b01}; + alert_rx_sync_dly2 <= {4'b0101}; + alert_rx_sync_dly1 <= {4'b0101}; + end else begin + alert_tx_sync_dly2 <= alert_tx_sync_dly1; + alert_tx_sync_dly1 <= alert_tx; + alert_rx_sync_dly2 <= alert_rx_sync_dly1; + alert_rx_sync_dly1 <= alert_rx; + end + end + + // Used by the monitor for "symmetrical" sampling with equal delay from both sides + // This ensures correct sampling. Otherwise there can be race conditions where the monitor misses + // a ping due to a delay. + assign alert_tx_final = alert_tx_sync_dly2; + assign alert_rx_final = alert_rx_sync_dly2; + + clocking sender_cb @(posedge async_clk); + output alert_tx_int; + input alert_rx; + endclocking + + clocking receiver_cb @(posedge async_clk); + input alert_tx; + output alert_rx_int; + endclocking + + clocking monitor_cb @(posedge clk); + input alert_tx_final; + input alert_rx_final; + endclocking + + assign alert_tx = (if_mode == dv_utils_pkg::Host && is_active) ? alert_tx_int : 'z; + assign alert_rx = (if_mode == dv_utils_pkg::Device && is_active) ? alert_rx_int : 'z; + + task automatic wait_ack_complete(); + while (alert_tx_final.alert_p === 1'b1) @(monitor_cb); + while (alert_rx_final.ack_p === 1'b1) @(monitor_cb); + endtask : wait_ack_complete + + function automatic bit get_alert(); + if (alert_tx_final.alert_p === 1'b1 && ping_pending) begin + `uvm_info($sformatf("%m"), + $sformatf("This alert is a ping response: alert_p:%b, alert_n:%b, ping_pending:%p", + alert_tx_final.alert_p, alert_tx_final.alert_n, ping_pending), UVM_MEDIUM) + end + get_alert = (alert_tx_final.alert_p === 1'b1 && alert_tx_final.alert_n === 1'b0 && + ! ping_pending); + endfunction : get_alert + + bit is_alert_handshaking; + assign is_alert_handshaking = alert_tx_final.alert_p === 1'b1 || alert_rx_final.ack_p === 1'b1; + + // this task wait for alert_ping request. + // alert_ping request is detected by level triggered "alert_rx.ping_p/n" signals pairs + // and no sig_int_err + task automatic wait_alert_ping(); + do begin + logic ping_p; + wait(rst_n === 1'b1); + ping_p = alert_rx_final.ping_p; + wait(alert_rx_final.ping_p !== ping_p && alert_rx_final.ping_p === !alert_rx_final.ping_n); + end while (rst_n != 1'b1); + endtask : wait_alert_ping + + // Set the alert pins to the requested value (either 1;0 or 0;1) when the interface is active and + // configured to act as the alert sender. + // + // This uses a clocking drive to update the version of the signal in sender_cb (causing the update + // to have a lasting effect, and also to be synchronised with the next clock edge). + task automatic force_alert(bit alert_p, bit alert_n); + sender_cb.alert_tx_int.alert_p <= alert_p; + sender_cb.alert_tx_int.alert_n <= alert_n; + endtask + + // Return true if the current state is PingSt + // + // This rather trivial function is needed because we want to use the interface through a virtual + // interface handle, so cannot refer to PingSt or state_q because they are both defined in terms + // of an enum defined inside the interface. + function automatic logic in_ping_st(); + return state_q == PingSt; + endfunction + + // Check the differential alert signals have no unknown values. + `ASSERT_KNOWN(PingKnown_A, alert_rx.ping_p ^ alert_rx.ping_n, clk, !rst_n) + `ASSERT_KNOWN(AckKnown_A, alert_rx.ack_p ^ alert_rx.ack_n, clk, !rst_n) + `ASSERT_KNOWN(AlertKnown_A, alert_tx.alert_p ^ alert_tx.alert_n, clk, !rst_n) +endinterface: alert_if diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_monitor.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_monitor.sv new file mode 100644 index 0000000..fb3dddc --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_monitor.sv @@ -0,0 +1,533 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +// --------------------------------------------- +// Alert sender receiver interface monitor +// --------------------------------------------- + +class alert_monitor extends dv_reactive_monitor #( + .ITEM_T(alert_seq_item), + .CFG_T (alert_agent_cfg), + .COV_T (alert_agent_cov) +); + + `uvm_component_utils(alert_monitor) + + // An output port that reports alert items that have been seen. + uvm_analysis_port #(alert_seq_item) m_alert_port; + + // Flags used to know when there are pings/alerts + // This flag is updated in the task `monitor_alert` when an alert is detected. + bit active_alert = 1'b0; + + extern function new (string name, uvm_component parent); + extern function void build_phase(uvm_phase phase); + extern task run_phase(uvm_phase phase); + + // Track the rst_n signal in the interface and maintain cfg.in_reset + extern task track_resets(); + + // A task from dv_base_monitor, which sets ok_to_end to false unless {alert_p, alert_n} is {0, 1} + // (or the check is bypassed). + extern task monitor_ready_to_end(); + + // This function is run (by run_phase) when a reset is seen. It is responsible for clearing + // monitor state. + extern local function void on_reset(); + + // This task is run (by run_phase) when a reset ends. It waits for initialisation to complete, + // then watches for pings and alerts. This task will run forever but is safe to kill (so run_phase + // can do so when it sees a reset). + extern local task run_between_resets(); + + // Watch the ping signal that starts a ping transaction. When a ping is visible, report it on + // req_analysis_port. This is run by run_between_resets (so will not run when under reset) but, + // unlike monitor_alerts and monitor_ping, doesn't need to wait for the alert_p/alert_n interface + // to be initialised. + extern local task report_ping_requests(); + + // Monitor alert_p/alert_n and set active_alert if an alert is observed (a valid alert signal that + // doesn't coincide with an existing ping handshake). + extern local task monitor_alerts(); + + // Watch for "ping transactions", and set cfg.active_ping if one starts. This task ignores resets, + // but is safe to kill. + // + // A ping transaction is caused by ping_p changing value. To allow us to see a change in value + // happening on *this* cycle, initial_ping_p should be used as "the value ping_p just had". + extern local task monitor_ping(bit initial_ping_p); + + // Block until alert initialisation happens. When alert initialisation is complete, set + // cfg.alert_init_done. + // + // Alert initialisation is normally tracked by the p/n signals becoming equal and then different + // again. As a special case, we also consider alert initialisation to have happened when + // en_alert_lpg is high. In this case, alert_sender can still send alerts, and alert_handler + // should ignore the alert_tx request. + // + // This task completely ignores resets (we expect it to be killed by run_phase if one happens when + // it is running). + extern local task wait_alert_init_done(); + + // Watch a ping transaction. In the normal case (the low power group is not enabled), the alert + // receiver will receive an alert and ack it. This is tracked with monitor_ping_handshake. + // + // If the low power group is enabled, the alert sender will not respond to the ping, but the + // receiver should still ack the (nonexistent) alert. + extern local task ping_thread(); + + // Watch the internals of a ping -> alert transaction and report it through m_alert_port. Note + // that this is only called when cfg.en_alert_lpg is false (because otherwise the ping should be + // ignored). + // + // Unlike ping_thread (which calls this task), monitor_ping_handshake doesn't wait for the ack. + // + // This task ignores cfg.en_alert_lpg and cfg.in_reset: if either become true, this task will be + // killed by something further up the stack. + extern local task monitor_ping_handshake(); + + // This thread is spawned after an alert is detected if no ping is in the middle of a handshake. + extern virtual task alert_thread(); + + // Watch the core of an alert transaction (which is expected if cfg.en_alert_lpg is false). Write + // sequence items reporting that the alert has started (which is why this task was called) then, + // when the ack is complete, write a sequence item describing the transaction. + extern local task monitor_alert_handshake(); + + // Watch for signal integrity errors (alert_p == alert_n), reporting them to m_alert_port. If + // cfg.is_async, allow a single cycle of integrity error without a report, to allow for clock + // skew. + extern local task int_fail_thread(); + + // Wait for the alert_p signal to be cleared + extern local task wait_alert_complete(); + + // Wait for the ack_p signal to be asserted + extern local task wait_ack(); + + // Wait for the ack_p signal to be cleared + extern local task wait_ack_complete(); + + // Return true if alert_p and alert_n are equal + extern local function bit is_sig_int_err(); + + // Return true if {alert_p, alert_n} are {1, 0}. + extern local function bit is_valid_alert(); + + // Wait for count cycles of the slower of the two clocks (clk and async_clk) by waiting for both + // of them in parallel. + extern local task wait_slow_clocks(int unsigned count); + +endclass : alert_monitor + +function alert_monitor::new (string name, uvm_component parent); + super.new(name, parent); +endfunction : new + +function void alert_monitor::build_phase(uvm_phase phase); + super.build_phase(phase); + m_alert_port = new("m_alert_port", this); +endfunction + +task alert_monitor::run_phase(uvm_phase phase); + // Run the base class run_phase task in parallel + fork + super.run_phase(phase); + track_resets(); + forever begin + wait (!cfg.in_reset); + fork begin : isolation_fork + fork + run_between_resets(); + wait (cfg.in_reset); + join_any + disable fork; + on_reset(); + end join + end + join +endtask + +task alert_monitor::track_resets(); + // Make sure that in_reset is correct at the start of the phase, then check that we are + // genuinely in reset by the start of the loop. + cfg.in_reset = (cfg.vif.rst_n !== 1'b1); + wait(!cfg.vif.rst_n); + + forever begin + cfg.in_reset = 1; + wait (cfg.vif.rst_n); + + // reset signals at posedge rst_n to avoid race condition at negedge rst_n + cfg.under_ping_handshake = 0; + cfg.in_reset = 0; + + wait (!cfg.vif.rst_n); + end +endtask + +task alert_monitor::monitor_ready_to_end(); + if (!cfg.bypass_alert_ready_to_end_check) begin + forever begin + @(cfg.vif.monitor_cb.alert_tx_final.alert_p); + ok_to_end = ({cfg.vif.monitor_cb.alert_tx_final.alert_p, + cfg.vif.monitor_cb.alert_tx_final.alert_n} == 2'b01); + end + end +endtask : monitor_ready_to_end + +function void alert_monitor::on_reset(); + active_alert = 1'b0; + cfg.active_ping = 1'b0; + cfg.alert_init_done = 0; + cfg.under_ping_handshake = 0; + cfg.under_ping_handshake_ph_2 = 0; +endfunction + +task alert_monitor::run_between_resets(); + // We've just come out of reset. The alert_p/alert_n lines will start with an initialisation + // handshake. Take a note of the current value of ping_p though: if it changes while we're + // initialising, we still want to remember there was an edge. + logic old_ping_p = cfg.vif.monitor_cb.alert_rx_final.ping_p; + + // There are two top-level tasks running. + // + // - report_ping_requests is responsible for noticing ping requests and writing them to + // req_analysis_port (for responses from sequences or analysis from the scoreboard). + // + // - Everything else depends on the alert_p/alert_n lines to be initialised (so we run that + // first). Once that has run, the other monitor tasks are in charge of watching ping_p and + // alert_p and interpreting whether transactions are pings with responses or genuine alerts. + fork + report_ping_requests(); + begin + // Wait for the initialisation protocol to set up the alert_p/alert_n lines. + wait_alert_init_done(); + + // Now we get to the "main part of the task". Track alerts and pings (telling + // alert_and_ping_thread the initial state of ping_p so that we don't miss any ping that + // happened before the alert_p/alert_n initialisation had happened). + fork + // Detect and report signal integrity errors (alert_p == alert_n) + int_fail_thread(); + + // The two monitor_* tasks keep track of the start of a alert/ping, with active_alert and + // cfg.active_ping. These tasks only ever *set* the relevant flag, which will be cleared by + // the assocated *_thread task below. + monitor_alerts(); + monitor_ping(old_ping_p); + + // Handle the "next" alert or ping request. + begin : thread_arbiter + bit first_time = 1; + forever begin + // Wait for one of these flags to change, but don't necessarily wait the on the first + // iteration: they get set by monitor_alerts and monitor_ping and the relevant task + // might have been scheduled before our first run. + if (!first_time) @({active_alert, + cfg.active_ping, + cfg.under_ping_handshake || cfg.under_ping_handshake_ph_2}); + first_time = 0; + + if (active_alert) begin + if (! (cfg.under_ping_handshake || cfg.under_ping_handshake_ph_2)) begin + alert_thread(); + end + end else if (cfg.active_ping) begin + ping_thread(); + end + end + end : thread_arbiter + join + end + join +endtask + +task alert_monitor::monitor_alerts(); + logic ping_p; + + forever @(cfg.vif.monitor_cb) begin + if (cfg.active_ping) begin + // If we're in a ping, wait until it is done + wait (!cfg.active_ping); + end else begin + // Look for an alert request. We might be in some other part of the ping handshake. If that is + // the case, don't act on the seeming alert request yet (but we'll be able to register it on + // the next cycle). + if (is_valid_alert() && !(cfg.under_ping_handshake || + ping_p != cfg.vif.monitor_cb.alert_rx_final.ping_p)) begin + active_alert = 1; + end + end + // We've just done a "loop iteration". Before waiting for the next clock cycle, register the + // current value of ping_p (allowing us to detect edges) + ping_p = cfg.vif.monitor_cb.alert_rx_final.ping_p; + end +endtask : monitor_alerts + +task alert_monitor::monitor_ping(bit initial_ping_p); + bit old_ping_p = initial_ping_p; + + if (cfg.active_ping) `uvm_fatal(`gfn, "Cannot start monitor_ping when cfg.active_ping is set.") + + forever begin + // Wait until a ping request is sent. Note that this includes a check that active_ping is false: + // theoretically, there is nothing stopping the receiver from sending a second ping request that + // overlaps with the end of the first (because the receiver can send one immediately after + // dropping its ack signal). + wait (cfg.vif.monitor_cb.alert_rx_final.ping_p != old_ping_p && !cfg.active_ping); + + // The ping_p signal has changed value, which means that the receiver is sending a ping. If + // there is an alert in flight at the moment, wait until that finishes. (The ping request should + // be delayed, but will not be forgotten) + wait (active_alert==0); + + // At this point a ping transaction is starting. Record that by setting active_ping, which will + // be cleared on reset or at the end of the ping_thread task (the task that actually responds to + // the ping). + `uvm_info(`gfn, $sformatf("%m - Ping detected: setting 'active_ping'"), UVM_DEBUG) + cfg.active_ping = 1; + + old_ping_p = cfg.vif.monitor_cb.alert_rx_final.ping_p; + end +endtask : monitor_ping + +task alert_monitor::report_ping_requests(); + forever begin + wait(!cfg.en_alert_lpg); + fork begin : isolation_fork + fork + wait(cfg.en_alert_lpg); + begin + logic last_ping = cfg.vif.monitor_cb.alert_rx_final.ping_p; + forever @(cfg.vif.monitor_cb) begin + if (cfg.vif.monitor_cb.alert_rx_final.ping_p != last_ping) begin + alert_seq_item req = alert_seq_item::type_id::create("req"); + req.m_trans_type = AlertPingTrans; + req_analysis_port.write(req); + end + last_ping = cfg.vif.monitor_cb.alert_rx_final.ping_p; + end + end + join_any + disable fork; + end join + end +endtask + +task alert_monitor::wait_alert_init_done(); + fork begin : isolation_fork + fork + wait (cfg.en_alert_lpg); + begin + wait (cfg.vif.monitor_cb.alert_tx_final.alert_p == + cfg.vif.monitor_cb.alert_tx_final.alert_n); + wait (cfg.vif.monitor_cb.alert_tx_final.alert_p != + cfg.vif.monitor_cb.alert_tx_final.alert_n); + @(cfg.vif.monitor_cb); + `uvm_info($sformatf("%m"), "Alert init done.", UVM_HIGH) + end + join_any + disable fork; + end join + + cfg.alert_init_done = 1; +endtask : wait_alert_init_done + +task alert_monitor::ping_thread(); + // If the lower power group (lpg) is disabled, we expect an alert sender to respond to the ping. + // Watch it happen, dropping out (and killing monitor_ping_handshake) if lpg becomes enabled. + if (!cfg.en_alert_lpg) begin + fork begin : isolation_fork + fork + wait(cfg.en_alert_lpg); + monitor_ping_handshake(); + join_any + disable fork; + end join + end + wait_ack_complete(); + `uvm_info(`gfn, "ACK for ping received", UVM_DEBUG) + cfg.under_ping_handshake_ph_2 = 0; + + cfg.active_ping = 0; +endtask : ping_thread + +task alert_monitor::monitor_ping_handshake(); + alert_seq_item req = alert_seq_item::type_id::create("req"); + + // If alert_p is currently asserted, that must be the tail of a different alert. Wait for it to + // clear. + if (cfg.vif.monitor_cb.alert_tx_final.alert_p) wait_alert_complete(); + wait (active_alert==0); + + // Register the fact that we're in a ping handshake, and increment the count of pings that we have + // seen. + `uvm_info(`gfn, $sformatf("%m: Sampling ping - item will be sent after ACK"), UVM_DEBUG) + cfg.under_ping_handshake = 1; + cfg.ping_count++; + + req.m_trans_type = AlertPingTrans; + + // Track the ping transaction: the sender should respond by setting alert_p, which should then get + // acked by the receiver. + fork begin : isolation_fork + fork + begin : wait_ping_timeout + // If there is an alert handler in the design, the ping timeout is configured through a + // PING_TIMEOUT_CYC register, which the sequence configures to match cfg.ping_timeout_cycle. + // This monitor configures itself to match, waiting that long before concluding that a ping + // request has timed out. + // + // To get the timing to exactly match the alert handler, we have to be a little careful + // about flops and clocking blocks. The change to the ping output from the alert handler + // takes 3 cycles to be reflected in alert_rx_final, then one final cycle to appear through + // monitor_cb (which just triggered us). The change to the crashdump state only takes 2 + // cycles to propagate to an output. To match the timing, subtract two from the timeout. + if (cfg.ping_timeout_cycle > 2) begin + wait_slow_clocks(cfg.ping_timeout_cycle - 2); + end + req.m_ping_timeout = 1'b1; + end + begin : wait_ping_handshake + wait(cfg.vif.monitor_cb.alert_tx_final.alert_p); + req.m_alert_handshake_sta = AlertReceived; + wait_ack(); + req.m_alert_handshake_sta = AlertAckReceived; + cfg.under_ping_handshake = 0; + cfg.under_ping_handshake_ph_2 = 1; + end + join_any + disable fork; + end join + + `uvm_info(`gfn, $sformatf("%m - Sending req: \n%0s",req.sprint), UVM_DEBUG) + m_alert_port.write(req); + + if (cfg.en_cov && cfg.en_ping_cov) cov.m_alert_trans_cg.sample(req.m_trans_type); + + // It's possible that the alert_p signal went high quickly, but the ack was slow (in which case + // we'll see a ping timeout with m_alert_handshake_sta == AlertReceived). + // + // This might cause a spurious alert error. For details see the discussion on Issue #2321. + if (req.m_ping_timeout && req.m_alert_handshake_sta == AlertReceived) begin + @(cfg.vif.monitor_cb); + if (cfg.vif.monitor_cb.alert_rx_final.ack_p == 1'b1) begin + `uvm_info(`gfn, $sformatf("%m - Sending req: \n%0s",req.sprint), UVM_DEBUG) + m_alert_port.write(req); + end + end + + cfg.under_ping_handshake = 0; +endtask : monitor_ping_handshake + +task alert_monitor::alert_thread(); + if (cfg.en_lpg_cov && cfg.en_cov) begin + cov.m_alert_lpg_cg.sample(cfg.en_alert_lpg); + end + if (!cfg.en_alert_lpg) begin + fork begin : isolation_fork + fork + wait(cfg.en_alert_lpg); + monitor_alert_handshake(); + join_any + disable fork; + end join + end +endtask : alert_thread + +task alert_monitor::monitor_alert_handshake(); + alert_seq_item req = alert_seq_item::type_id::create("req"); + + req.m_trans_type = AlertSigTrans; + req.m_alert_handshake_sta = AlertReceived; + `uvm_info(`gfn, $sformatf("%m - Sending req on 'm_alert_port': \n%0s",req.sprint), + UVM_DEBUG) + // Write alert packet to scb when receiving alert signal + m_alert_port.write(req); + // Write alert packet to sequence for auto alert responses. + `uvm_info(`gfn, $sformatf("%m - Sending req on 'req_analysis_port': \n%0s",req.sprint), + UVM_DEBUG) + req_analysis_port.write(req); + + // Duplicate req for writing alert packet at the end of alert handshake + `downcast(req, req.clone()) + + req.m_alert_handshake_sta = AlertAckReceived; + wait_alert_complete(); + req.m_alert_handshake_sta = AlertComplete; + wait_ack_complete(); + req.m_alert_handshake_sta = AlertAckComplete; + + active_alert = 0; + + `uvm_info(`gfn, $sformatf("[%s]: handshake status is %s", req.m_trans_type.name(), + req.m_alert_handshake_sta.name()), UVM_HIGH) + `uvm_info(`gfn, $sformatf("%m - Sending req on 'm_alert_port': \n%0s",req.sprint), + UVM_DEBUG) + m_alert_port.write(req); + + if (cfg.en_cov) begin + cov.m_handshake_complete_cg.sample(req.m_alert_handshake_sta); + if (cfg.en_ping_cov) cov.m_alert_trans_cg.sample(req.m_trans_type); + end +endtask + +task alert_monitor::int_fail_thread(); + int unsigned skew_grace_time = cfg.is_async ? 1 : 0; + int unsigned failure_len = 0; + + forever begin + wait(!cfg.en_alert_lpg); + fork begin : isolation_fork + fork + wait(cfg.en_alert_lpg); + forever @(cfg.vif.monitor_cb) begin + if (is_sig_int_err()) begin + failure_len += 1; + if (failure_len > skew_grace_time) begin + alert_seq_item req = alert_seq_item::type_id::create("req"); + req.m_trans_type = AlertIntFail; + `uvm_info(`gfn, + $sformatf("%m - Sending req on 'm_alert_port': \n%0s", req.sprint), + UVM_DEBUG) + m_alert_port.write(req); + end + end else begin + failure_len = 0; + end + end + join_any + disable fork; + end join + end +endtask : int_fail_thread + +task alert_monitor::wait_alert_complete(); + wait (!cfg.vif.monitor_cb.alert_tx_final.alert_p); +endtask : wait_alert_complete + +task alert_monitor::wait_ack(); + wait (cfg.vif.monitor_cb.alert_rx_final.ack_p); +endtask : wait_ack + +task alert_monitor::wait_ack_complete(); + wait (!cfg.vif.monitor_cb.alert_rx_final.ack_p); +endtask : wait_ack_complete + +function bit alert_monitor::is_sig_int_err(); + return cfg.vif.monitor_cb.alert_tx_final.alert_p === cfg.vif.monitor_cb.alert_tx_final.alert_n; +endfunction : is_sig_int_err + +function bit alert_monitor::is_valid_alert(); + return cfg.vif.monitor_cb.alert_tx_final.alert_p && !cfg.vif.monitor_cb.alert_tx_final.alert_n; +endfunction : is_valid_alert + +task alert_monitor::wait_slow_clocks(int unsigned count); + fork + repeat (count) @(cfg.vif.monitor_cb); + repeat (count) @(cfg.vif.receiver_cb); + join +endtask diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_receiver_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_receiver_driver.sv new file mode 100644 index 0000000..d68beb7 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_receiver_driver.sv @@ -0,0 +1,466 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A driver that behaves as an alert_receiver. This is used in an alert_agent when configured in +// "device mode" + +class alert_receiver_driver extends alert_base_driver; + `uvm_component_utils(alert_receiver_driver) + + // The drive_req_between_resets task will consume requests from m_requests and add these requests + // to this pair of FIFOs (to be consumed by the send_pings and send_alert_rsps tasks that it + // spawns). + // + // When reset is asserted, both of those tasks will exit after flushing their respective queues. + local uvm_tlm_analysis_fifo #(alert_seq_item) m_pending_pings; + local uvm_tlm_analysis_fifo #(alert_seq_item) m_pending_alert_rsps; + + // When a ping gets an alert response or a genuine alert is sent, this driver needs to acknowledge + // the alert, but the two options need to be handled serially. The ack is handled by ack_alert, + // which uses this semaphore as a mutex. + local semaphore m_ack_semaphore; + + extern function new(string name, uvm_component parent); + + // Clear interface signals because reset has been asserted + // + // This implements a task in dv_base_driver + extern task on_enter_reset(); + + // Drive requests that have been seen by alert_base_driver::get_req. This task runs forever. + // + // This implements a task in alert_base_driver + extern task drive_req(); + + // Take items from m_requests and (depending on the type of the item) add them to m_pending_pings + // and m_pending_alert_rsps. + // + // Exits immediately on reset. + extern local task consume_requests_betwen_resets(); + + // Drive requests that have been seen by alert_base_driver::get_req, until the next reset. This is + // called by drive_req. + extern local task drive_req_between_resets(); + + // Drive any items that were added to m_pending_pings. + // + // Exits early on reset. + extern local task send_pings(); + + // Drive any items that were added to m_pending_alert_rsps. + // + // Exits early on reset. + extern local task send_alert_rsps(); + + // Send a ping described by item. + // + // This will start by waiting ping_delay cycles before sending the ping request. Once the ping has + // gone out, we wait for an alert to arrive and then acknowledge it using ack_alert (and + // passing ack_delay and ack_stable). + // + // The task allows to retract driving the ping. If there's an alert (r_alert_rsp_q.size > 0) + // before the ping delay, the ping is aborted and the driver moves to tackle the alert in + // 'rsp_alert' task. This is notified by setting `item_not_driven=1` + // + // The task exits early on reset. + extern local task send_ping(alert_seq_item item); + + // Handle a sequence item that demands an alert response + // + // An item should only be added to that queue in response to an alert being generated on the + // interface. We will wait a randomised time (in ack_alert) before acknowledging the alert. + // + // Exits early on reset. + extern local task send_alert_rsp(alert_seq_item item); + + // Wait for a short time to allow an alert to propagate through the clocking blocks in the + // interface. The max_cycles argument is the maximum number of cycles to wait. + // + // The task will stop as soon as any of these events happens: + // + // - The alert_p signal goes high in receiver_cb. + // - There have been max_cycles edges of both clocks. + // - A reset is asserted. + extern local task wait_for_alert_propagation(int unsigned max_cycles); + + // Acknowledge the next alert + // + // This task waits until an alert is signalled, then waits a short time before acknowledging the + // alert. Once the ack has been asserted, the ack stays high for a time before it, in turn, drops. + // + // This task uses m_ack_semaphore as a mutex (to serialise ping response acks and other alert + // acks). + // + // The delay before the initial ack is from the ack_delay argument. The ack then stays stable for + // the number of cycles in the ack_stable argument. + // + // Both of these times will be truncated if cfg.fast_rcvr is true. In that case, they will be + // cfg.ack_delay_min, cfg.ack_stable_min respectively. + // + // The task will exit quickly on reset (replacing the token on the semaphore) + extern local task ack_alert(int unsigned ack_delay, int unsigned ack_stable); + + // Set the ack signal to be the given boolean value (so either 0;1 or 1;0) + extern local task set_ack(bit asserted); + + // Toggle the ping state + extern local task set_ping(); + + // Set the ping state to 0;1 (the reset value) + extern task reset_ping(); + + // Perform the alert init handshake, exiting early on reset + extern task do_alert_rx_init(); + + // Wait for num_cycles positive edges of the slower of the two clocks + // + // Return early on reset. + extern task wait_slower_clock(int unsigned num_cycles); +endclass : alert_receiver_driver + +function alert_receiver_driver::new(string name, uvm_component parent); + super.new(name, parent); + m_ack_semaphore = new(1); + m_pending_pings = new("m_pending_pings", this); + m_pending_alert_rsps = new("m_pending_alert_rsps", this); +endfunction + +task alert_receiver_driver::on_enter_reset(); + // Clear ping and ack signals (both the actual signals and the clocking block values) + cfg.vif.alert_rx_int.ping_p <= 1'b0; + cfg.vif.alert_rx_int.ping_n <= 1'b1; + cfg.vif.alert_rx_int.ack_p <= 1'b0; + cfg.vif.alert_rx_int.ack_n <= 1'b1; + cfg.vif.receiver_cb.alert_rx_int.ping_p <= 1'b0; + cfg.vif.receiver_cb.alert_rx_int.ping_n <= 1'b1; + cfg.vif.receiver_cb.alert_rx_int.ack_p <= 1'b0; + cfg.vif.receiver_cb.alert_rx_int.ack_n <= 1'b1; +endtask + +task alert_receiver_driver::drive_req(); + forever begin + // Wait until we are out of reset. Until that happens, respond instantly to any sequence items + // that come in. + while (cfg.in_reset) begin + alert_seq_item item; + fork : isolation_fork begin + fork + wait (!cfg.in_reset); + m_requests.get(item); + join_any + disable fork; + end join + if (item != null) seq_item_port.put_response(item); + end + + drive_req_between_resets(); + end +endtask + +task alert_receiver_driver::consume_requests_betwen_resets(); + fork : isolation_fork begin + fork + wait (cfg.in_reset); + forever begin + alert_seq_item item; + m_requests.get(item); + + case (item.m_trans_type) + AlertSigTrans: m_pending_alert_rsps.write(item); + AlertPingTrans: m_pending_pings.write(item); + default: `uvm_fatal(get_full_name(), "Unknown transaction type") + endcase + end + join_any + disable fork; + end join +endtask + +task alert_receiver_driver::drive_req_between_resets(); + // Drive the init protocol from the receiver side. do_alert_rx_init will exit early if it sees + // reset. + do_alert_rx_init(); + if (cfg.in_reset) return; + + // Fetch items to drive and drive them. The first task takes items from the m_requests fifo and + // uses them to populate m_pending_pings and m_pending_alert_rsps. The second two tasks take (and + // drive) items from those two fifos. + // + // All three tasks exit on reset. + fork + consume_requests_betwen_resets(); + send_alert_rsps(); + send_pings(); + join + + // As a consistency check, make sure that m_pending_pings and m_pending_alert_rsps were cleared by + // send_alert_rsps and send_pings before they exited. + if (m_pending_pings.size()) + `uvm_error(get_full_name(), + $sformatf("m_pending_pings nonempty after reset: %0p", m_pending_pings)) + if (m_pending_alert_rsps.size()) + `uvm_error(get_full_name(), + $sformatf("m_pending_alert_rsps nonempty after reset: %0p", m_pending_alert_rsps)) +endtask + +task alert_receiver_driver::send_pings(); + alert_seq_item item; + + while(!cfg.in_reset) begin + // Clear the item variable (so that we can tell whether the fork below gets an item or sees a + // reset) + item = null; + + fork : isolation_fork begin + fork + wait (cfg.in_reset); + m_pending_pings.get(item); + join_any + disable fork; + end join + + // If there is an item, send it with send_ping. The task will exit early on reset. + if (item != null) begin + send_ping(item); + + // Now that the item has been sent, report this to the sequencer + seq_item_port.put_response(item); + end + end + + // When we get here, we must be in reset. m_pending_pings might be nonempty (if reset was asserted + // when there were lots of pending pings). Report all the items done (in a trivial way) before + // returning. + while(m_pending_pings.try_get(item)) seq_item_port.put_response(item); +endtask + +task alert_receiver_driver::send_alert_rsps(); + alert_seq_item item; + + while (!cfg.in_reset) begin + // Clear the item variable (so that we can tell whether the fork below gets an item or sees a + // reset) + item = null; + + fork : isolation_fork begin + fork + wait (cfg.in_reset); + m_pending_alert_rsps.get(item); + join_any + disable fork; + end join + + // If there is an item, send it with send_alert_rsp. The task will exit early on reset. + if (item != null) begin + send_alert_rsp(item); + + // Now that the item has been sent, report this to the sequencer + seq_item_port.put_response(item); + end + end + + // When we get here, we must be in reset. m_pending_alert_rsps might be nonempty. (This probably + // shouldn't actually be possible, but let's not worry too much about it). Report all the items + // done (in a trivial way) before returning. + while(m_pending_alert_rsps.try_get(item)) seq_item_port.put_response(item); +endtask + +task alert_receiver_driver::send_ping(alert_seq_item item); + `uvm_info(get_full_name(), "Sending ping", UVM_HIGH) + + if (item.m_int_err_cyc) begin + `uvm_fatal(get_full_name(), "Cannot send ping with m_int_err_cyc > 0: not supported by driver.") + end + + // Wait for item.m_ping_delay cycles (which might be quite a while) before sending the ping. There + // may be other alerts happening in the meantime, but this task doesn't need to worry about them. + // Exit early on reset + fork : isolation_fork begin + fork + wait(cfg.in_reset); + begin + repeat (item.m_ping_delay) @(cfg.vif.receiver_cb); + set_ping(); + end + join_any + disable fork; + end join + if (cfg.in_reset) return; + + // After waiting (possibly for a long time), we finally sent a ping. The alert sender should + // respond with an alert, which we ack here, treating it as the ping response. + // + // If the sender decided to send an alert at the same time as we sent the ping then we'll treat + // that alert as a ping response. But the sender will then respond to the ping with an alert that + // we'll treat as a genuine alert: the end result will be that we and the sender agree on the set + // of things that happened (one ping response and one genuine alert). + ack_alert(item.m_ack_delay, item.m_ack_stable); + + // Before responding to the item, we need to wait for the sender to complete its FSM (so that we + // don't send another ping when it's still sitting in PingHsPhase2, Pause0 or Pause1). The ack + // that we just sent has to be decoded by a prim_diff_decode (u_decode_ack), which will take at + // most 3 posedges of the sender's clock, then we take two more cycles (one in each of Pause0 and + // Pause1), for a total of 5 cycles. + // + // Wait with the slower of vif.clk and vif.async_clk. + wait_slower_clock(5); +endtask + +task alert_receiver_driver::send_alert_rsp(alert_seq_item item); + `uvm_info(get_full_name(), "Responding to alert", UVM_HIGH) + + // If we get here then something should have been pushed onto the alert queue in response to + // an alert being generated. Wait a short time to allow the alert to propagate through the + // clocking blocks (which should only take a cycle, but give it a couple more to make sure). + // The count of 7 cycles was chosen as an upper bound: an alert should be visible in at most that + // time. + // + // Either way, we stop as soon as the alert propagates through, or if we see a reset. + wait_for_alert_propagation(7); + if (cfg.in_reset) return; + + // Check that the alert really has arrived (which is a consistency check for the testbench, rather + // than a check about the dut). + if (cfg.vif.receiver_cb.alert_tx.alert_p !== 1'b1) begin + `uvm_fatal(get_full_name(), "alert_p not high, despite an item from the monitor") + end + + // Now send an ack with ack_alert. This then waits for the alert to drop, then clears the ack + // again. + // + // The task exits early on reset. + ack_alert(item.m_ack_delay, item.m_ack_stable); +endtask + +task alert_receiver_driver::wait_for_alert_propagation(int unsigned max_cycles); + fork : isolation_fork begin + fork + wait (cfg.in_reset); + fork : isolation_fork begin + bit seen_alert; + + fork + repeat (max_cycles) begin + if (cfg.vif.receiver_cb.alert_tx.alert_p) begin + seen_alert = 1; + end + if (seen_alert) break; + @(cfg.vif.receiver_cb); + end + repeat (max_cycles) begin + if (cfg.vif.monitor_cb.alert_tx_final.alert_p) begin + seen_alert = 1; + end + if (seen_alert) break; + @(cfg.vif.monitor_cb); + end + join + end join + join_any + disable fork; + end join +endtask + +task alert_receiver_driver::ack_alert(int unsigned ack_delay, int unsigned ack_stable); + if (cfg.fast_rcvr) begin + ack_delay = cfg.ack_delay_min; + ack_stable = cfg.ack_stable_min; + end + + m_ack_semaphore.get(); + + // Wait for the alert to appear (but stop early if a reset is asserted) + fork : isolation_fork1 begin + fork + wait(cfg.in_reset); + wait(cfg.vif.receiver_cb.alert_tx.alert_p); + join_any + disable fork; + end join + + // If there has been a reset, there is nothing more to do. + if (cfg.in_reset) begin + m_ack_semaphore.put(); + return; + end + + // Now wait a short time and set the ack (dropping out early on reset) + fork : isolation_fork2 begin + fork + wait(cfg.in_reset); + begin + repeat (ack_delay + 1) @(cfg.vif.receiver_cb); + set_ack(1'b1); + end + join_any + disable fork; + end join + if (cfg.in_reset) begin + m_ack_semaphore.put(); + return; + end + + // Finally, wait for the alert to be cleared again, stopping early on reset. + fork : isolation_fork3 begin + fork + wait(cfg.in_reset); + begin + wait(!cfg.vif.receiver_cb.alert_tx.alert_p); + repeat (ack_stable) @(cfg.vif.receiver_cb); + set_ack(1'b0); + end + join_any + disable fork; + end join + + m_ack_semaphore.put(); +endtask + +task alert_receiver_driver::set_ack(bit asserted); + cfg.vif.receiver_cb.alert_rx_int.ack_p <= asserted; + cfg.vif.receiver_cb.alert_rx_int.ack_n <= !asserted; +endtask + +task alert_receiver_driver::set_ping(); + cfg.vif.receiver_cb.alert_rx_int.ping_p <= !cfg.vif.alert_rx.ping_p; + cfg.vif.receiver_cb.alert_rx_int.ping_n <= !cfg.vif.alert_rx.ping_n; +endtask + +task alert_receiver_driver::reset_ping(); + cfg.vif.receiver_cb.alert_rx_int.ping_p <= 1'b0; + cfg.vif.receiver_cb.alert_rx_int.ping_n <= 1'b1; +endtask + +task alert_receiver_driver::do_alert_rx_init(); + fork : isolation_fork begin + fork + wait(cfg.in_reset); + begin + repeat ($urandom_range(1, 10)) @(cfg.vif.receiver_cb); + cfg.vif.alert_rx_int.ack_p <= 1'b0; + cfg.vif.alert_rx_int.ack_n <= 1'b0; + + wait (cfg.vif.receiver_cb.alert_tx.alert_p == cfg.vif.receiver_cb.alert_tx.alert_n); + repeat ($urandom_range(1, 10)) @(cfg.vif.receiver_cb); + cfg.vif.alert_rx_int.ack_n <= 1'b1; + + wait (cfg.vif.receiver_cb.alert_tx.alert_p != cfg.vif.receiver_cb.alert_tx.alert_n); + end + join_any + disable fork; + end join +endtask + +task alert_receiver_driver::wait_slower_clock(int unsigned num_cycles); + fork : isolation_fork begin + fork + wait(cfg.in_reset); + fork + repeat (num_cycles) @(posedge cfg.vif.clk); + repeat (num_cycles) @(posedge cfg.vif.async_clk); + join + join_any + disable fork; + end join +endtask diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sender_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sender_driver.sv new file mode 100644 index 0000000..eceafe0 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sender_driver.sv @@ -0,0 +1,268 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +class alert_sender_driver extends alert_base_driver; + + `uvm_component_utils(alert_sender_driver) + + // An event that can be triggered (by functions as well as tasks). This is monitored by + // maintain_alert_drive, which will call cfg.vif.force_alert with m_desired_alert_val. + uvm_event m_update_alert_val; + bit [1:0] m_desired_alert_val; + + extern function new (string name, uvm_component parent); + + // This function gets called by dv_base_driver::reset_signals when the interface enters reset. + // Clear any alert signal. + extern virtual task on_enter_reset(); + + // Drive sequence items for alerts and pings that have been retrieved by get_req (and therefore + // have started) and have been pushed to the various queues. This also does the alert init + // handshake (with no sequence item) after each reset. + // + // An implementation of alert_base_driver::drive_req + extern virtual task drive_req(); + + // Drive sequence items for alerts and pings until either a reset or a change of cfg.en_alert_lpg + extern local task drive_reqs_with_lpg_mode(bit en_alert_lpg); + + // Drive a single sequence item to send an alert, possibly responding to a ping. This task doesn't + // mark the item done in seq_item_port: the caller should do that. + // + // This exits immediately on a reset. + extern local task send_item(bit is_ping_rsp, alert_seq_item item); + + // Drive the alert_p/alert_n pins for the sequence item. There may be a delay before asserting the + // alert or before de-asserting it (once an ack has been seen). + // + // This is safe to kill. + extern local task drive_alert_pins(alert_seq_item req); + + // Assert an alert (alert_p=1; alert_n=0) after alert_delay cycles. + // + // This is safe to kill. + extern local task set_alert_pins(int alert_delay); + + // Wait for an ack from the receiver, then de-assert the alert (alert_p=0; alert_n=1) after an + // extra ack_delay cycles. Finally, wait for the receiver to de-assert ack. + // + // The handshake above has a timeout, and the task will exit if it is reached. If cfg.en_alert_lpg + // becomes false, this means that the receiver will no longer respond. We regard that as an + // immediate timeout. + // + // This is safe to kill. + extern local task reset_alert_pins(int ack_delay); + + // Send invalid alert pin values (either 11 or 00) for int_err_cyc cycles + // + // This is safe to kill. + extern local task random_drive_int_fail(int int_err_cyc); + + // Set the alert pins to be (alert_p=1; alert_n=0) if enabled=1 and (alert_p=0; alert_n=1) + // otherwise. + // + // Because the alert signals are set through a clocking block (using cfg.vif.force_alert()), this + // works by setting m_desired_alert_val and triggering the m_update_alert_val event. + extern local function void set_alert(bit enabled); + + // Set the alert pins to 11 or 00 (depending on the high argument). + // + // This task takes zero time (but needs to be a task because it uses non-blocking assignment) + extern local task drive_invalid_alert(bit high); + + // Wait for count cycles of the sender clock + // + // This is safe to kill. + extern local task wait_sender_clk(int unsigned count); + + // Handle an alert init request. + // + // After alert_receiver is reset, it will send a signal integrity fail with a non-differential ack + // signal. The alert sender has to acknowledge the init by setting the alert pins to 00 until ack + // becomes differential again. + // + // This task exits early on reset or if cfg.en_alert_lpg is asserted (in which case, the receiver + // won't reply to the init) + extern local task do_alert_tx_init(); + + // This task runs forever, calling cfg.vif.set_alert() each time the m_update_alert_val event is + // triggered. + extern local task maintain_alert_drive(); +endclass : alert_sender_driver + +function alert_sender_driver::new (string name, uvm_component parent); + super.new(name, parent); + m_update_alert_val = new("m_update_alert_val"); +endfunction : new + +task alert_sender_driver::on_enter_reset(); + set_alert(1'b0); +endtask + +task alert_sender_driver::drive_req(); + fork + maintain_alert_drive(); + forever begin + // Wait until we are out of reset. Until that happens, respond instantly to any sequence items + // that come in. + while (cfg.in_reset) begin + fork : isolation_fork begin + alert_seq_item item; + fork + wait(!cfg.in_reset); + m_requests.get(item); + join_any + disable fork; + if (item != null) seq_item_port.put_response(item); + end join + end + + while(!cfg.in_reset) begin + bit en_alert_lpg = cfg.en_alert_lpg; + + // If LPG is not enabled, initialise the alert interface + if (!en_alert_lpg) begin + do_alert_tx_init(); + end + + // Drive any requests that we see. The task will exit on reset or if the LPG flag changes, + // letting us initialise the alert interface (if LPG is disabled) and continue. + drive_reqs_with_lpg_mode(en_alert_lpg); + end + end + join +endtask + +task alert_sender_driver::drive_reqs_with_lpg_mode(bit en_alert_lpg); + forever begin + alert_seq_item item, rsp; + + // Pick an item to drive, but keep track of resets and any change to the LPG flag. + fork : isolation_fork begin + fork + wait(cfg.en_alert_lpg != en_alert_lpg); + wait(cfg.in_reset); + m_requests.get(item); + join_any + disable fork; + end join + + // If there is no item, there has been a reset or the LPG flag has changed. Return from the + // task. + if (item == null) return; + + `downcast(rsp, item.clone()); + rsp.set_id_info(item); + + // Handle the alert request or ping response. + case (item.m_trans_type) + AlertSigTrans: send_item(1'b0, rsp); + AlertPingTrans: send_item(1'b1, rsp); + default: `uvm_fatal(get_full_name(), "Unknown txn type.") + endcase + + seq_item_port.put_response(rsp); + end +endtask + +task alert_sender_driver::send_item(bit is_ping_rsp, alert_seq_item item); + + `uvm_info("driving_item", + $sformatf("starting sender item: %0s, m_int_err_cyc=%0b", + item.m_trans_type.name(), item.m_int_err_cyc), + UVM_HIGH) + fork : isolation_fork begin + fork + wait (cfg.in_reset); + if (!is_ping_rsp || !cfg.ping_timeout) begin + drive_alert_pins(item); + end else begin + wait_sender_clk(cfg.ping_timeout_cycle); + end + join_any + disable fork; + end join + `uvm_info("driving_item", + $sformatf("finished sender item: %0s, m_int_err_cyc=%0b", + item.m_trans_type.name(), item.m_int_err_cyc), + UVM_HIGH) +endtask + +task alert_sender_driver::drive_alert_pins(alert_seq_item req); + if (req.m_int_err_cyc) begin + random_drive_int_fail(req.m_int_err_cyc); + set_alert(1'b0); + end else begin + set_alert_pins(req.m_alert_delay); + reset_alert_pins(req.m_ack_delay); + end + + // There must be at least two sender clock delays before next alert_handshake + wait_sender_clk(2); +endtask + +task alert_sender_driver::set_alert_pins(int alert_delay); + wait_sender_clk(alert_delay + 1); + set_alert(1'b1); +endtask + +task alert_sender_driver::reset_alert_pins(int ack_delay); + fork : isolation_fork begin + fork + wait (cfg.en_alert_lpg); + begin : wait_alert_handshake + wait (cfg.vif.alert_rx.ack_p == 1'b1); + wait_sender_clk(1 + ack_delay); + set_alert(1'b0); + wait (cfg.vif.alert_rx.ack_p == 1'b0); + end + join_any + disable fork; + end join +endtask + +task alert_sender_driver::random_drive_int_fail(int int_err_cyc); + repeat (int_err_cyc) begin + wait_sender_clk(1); + drive_invalid_alert($urandom & 1); + end +endtask + +function void alert_sender_driver::set_alert(bit enabled); + m_desired_alert_val = {enabled, !enabled}; + m_update_alert_val.trigger(); +endfunction + +task alert_sender_driver::drive_invalid_alert(bit high); + cfg.vif.sender_cb.alert_tx_int.alert_p <= high; + cfg.vif.sender_cb.alert_tx_int.alert_n <= high; +endtask + +task alert_sender_driver::wait_sender_clk(int unsigned count); + repeat (count) @(cfg.vif.sender_cb); +endtask + +task alert_sender_driver::do_alert_tx_init(); + fork : isolation_fork begin + fork + wait (cfg.in_reset || cfg.en_alert_lpg); + begin + wait (cfg.vif.alert_rx.ack_p == cfg.vif.alert_rx.ack_n); + drive_invalid_alert(1'b0); + wait (cfg.vif.alert_rx.ack_p != cfg.vif.alert_rx.ack_n); + set_alert(1'b0); + end + join_any + disable fork; + end join +endtask + +task alert_sender_driver::maintain_alert_drive(); + forever begin + m_update_alert_val.wait_ptrigger(); + cfg.vif.force_alert(m_desired_alert_val[1], m_desired_alert_val[0]); + m_update_alert_val.reset(); + end +endtask diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_seq_item.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_seq_item.sv new file mode 100644 index 0000000..49cd6d5 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_seq_item.sv @@ -0,0 +1,111 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// An item that represents transactions on an alert interface + +class alert_seq_item extends uvm_sequence_item; + // The type of transaction represented by this item. This is set by monitors to report an alert, a + // ping request, or a signal integrity failure. + // + // When the item is being driven, this will always be a ping request or an alert (this is + // guaranteed when randomising by ping_or_alert_c) + rand alert_trans_type_e m_trans_type; + + // If this field is nonzero, the driver will cause a signal integrity error of that many cycles + // when driving this item. + rand int unsigned m_int_err_cyc; + + // A delay injected by alert_receiver_driver before it actually sends a ping request. This allows + // the driver to be sent a stream of back-to-back items without locking up the interface. + rand int unsigned m_ping_delay; + + // The number of cycles the driver should wait before acking an alert (when being an alert + // receiver) or clearing an alert after it has been acked (when being an alert sender). + rand int unsigned m_ack_delay; + + // The number of cycles a receiver should continue to assert ack after the sender has dropped + // alert_p. + // + // This only has an effect when acting as an alert receiver. + rand int unsigned m_ack_stable; + + // The number of cycles to wait before sending an alert. + // + // This only has an effect when acting as an alert sender. + rand int unsigned m_alert_delay; + + // This bit is set on items generated by a monitor that has seen a timeout caused by an + // alert/escalation sender not responding to a ping. + bit m_ping_timeout; + + // Generated by alert_monitor: this item shows the current stage of the alert handshake + alert_handshake_e m_alert_handshake_sta; + + extern function new (string name = ""); + + // Constrain delays in the generated item + extern constraint delay_c; + + // Randomised items (to be driven, rather than items generated by a monitor) should only have + // transaction types representing a ping request or an alert. + extern constraint ping_or_alert_c; + + // Constraints on m_int_err_cyc for items randomised for a driver. + // + // Normally, we don't want to generate signal integrity errors, so there's a soft constraint that + // m_int_err_cyc is zero. If this is overridden or disabled, provide a distribution for the length + // of the signal integrity error. + extern constraint int_err_cyc_c; + + // Randomised items (to be driven, rather than items generated by a monitor) to request a ping + // should not have a nonzero m_int_err_cyc: generating ping signal integrity errors is not yet + // supported by the driver. + extern constraint ping_cannot_cause_int_err_c; + + `uvm_object_utils_begin(alert_seq_item) + `uvm_field_enum(alert_trans_type_e, m_trans_type, UVM_DEFAULT) + `uvm_field_int (m_int_err_cyc, UVM_DEFAULT) + `uvm_field_int (m_ping_delay, UVM_DEFAULT) + `uvm_field_int (m_ack_delay, UVM_DEFAULT) + `uvm_field_int (m_ack_stable, UVM_DEFAULT) + `uvm_field_int (m_alert_delay, UVM_DEFAULT) + `uvm_field_int (m_ping_timeout, UVM_DEFAULT) + `uvm_field_enum(alert_handshake_e, m_alert_handshake_sta, UVM_DEFAULT) + `uvm_object_utils_end +endclass + +function alert_seq_item::new (string name = ""); + super.new(name); +endfunction + +constraint alert_seq_item::delay_c { + soft m_ack_delay <= 32; + soft m_ack_stable <= 32; + soft m_alert_delay <= 32; +} + +constraint alert_seq_item::ping_or_alert_c { + m_trans_type inside {AlertPingTrans, AlertSigTrans}; +} + +constraint alert_seq_item::int_err_cyc_c { + // Normally we constrain m_int_err_cyc to be zero. But it's a soft constraint, so the call-site + // that drives the randomisation can override it by adding a hard "m_int_err_cyc != 0" constraint. + // + // If the call-site *has* overridden the constraint (but hasn't disabled this whole constraint by + // name), we want to control the distribution of values. The obvious way to express that would be + // something like "m_int_err_cyc != 0 -> m_int_err_cyc dist {some_distribution_here};", but that + // doesn't work in EDA tools that can't solve distributions in parallel with hard constraints. + // + // Fortunately, we can cheat! The trick is to use a single distribution statement that gives a + // nonzero probability to m_int_err_cyc == 0. This allows the usual case (where the value is + // *constrained* to equal zero), and doesn't affect the special case (because the value is already + // constrained not to equal zero). + soft m_int_err_cyc == 0; + m_int_err_cyc dist {0 := 1, 1 :/ 1, [2:10] :/ 1}; +} + +constraint alert_seq_item::ping_cannot_cause_int_err_c { + m_trans_type == AlertPingTrans -> m_int_err_cyc == 0; +} diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sequencer.sv new file mode 100644 index 0000000..6d5761c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/alert_sequencer.sv @@ -0,0 +1,12 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class alert_sequencer extends dv_reactive_sequencer #(alert_seq_item, alert_agent_cfg); + `uvm_component_utils(alert_sequencer) + extern function new (string name, uvm_component parent); +endclass + +function alert_sequencer::new (string name, uvm_component parent); + super.new(name, parent); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/BUILD b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/BUILD new file mode 100644 index 0000000..395083a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/BUILD @@ -0,0 +1,10 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +package(default_visibility = ["//visibility:public"]) + +filegroup( + name = "doc_files", + srcs = glob(["*_testplan.hjson"]), +) diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/alert_agent_testplan.hjson b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/alert_agent_testplan.hjson new file mode 100644 index 0000000..0596742 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/data/alert_agent_testplan.hjson @@ -0,0 +1,28 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// This DV coverplan documents additional alert agent covergroups. +// To enable these covergroups, please ensure the following variables are enabled: +// `cfg.en_ping_cov` and `cfg.en_lpg_cov` +// Note that if LPG is enabled, the alert ping request handshake won't be initiated, so we cannot +// collect that coverage in this agent. +{ + covergroups: [ + { + name: alert_handshake_complete_cg + desc: '''Cover if the alert handshake completes.''' + } + { + name: alert_trans_cg + desc: '''Cover if the transaction is a ping request or an actual alert request.''' + } + { + name: alert_lpg_cg + desc: '''Covers alert lpg status during an alert request. + + Cover if its lower-power-group (lpg) is enabled or disabled during an alert request. + ''' + } + ] +} diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_alert_rsp_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_alert_rsp_seq.sv new file mode 100644 index 0000000..c7b66f9 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_alert_rsp_seq.sv @@ -0,0 +1,61 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this sequence responses to alert pins by sending the ack pins +class alert_receiver_alert_rsp_seq extends alert_receiver_base_seq; + + `uvm_object_utils(alert_receiver_alert_rsp_seq) + + extern constraint alert_receiver_alert_rsp_seq_c; + + extern function new (string name = ""); + extern virtual task body(); + // Sends alert rsps back to host. + extern virtual task default_rsp_thread(); + +endclass : alert_receiver_alert_rsp_seq + +constraint alert_receiver_alert_rsp_seq::alert_receiver_alert_rsp_seq_c { + m_trans_type == AlertSigTrans; +} + +function alert_receiver_alert_rsp_seq::new (string name = ""); + super.new(name); +endfunction : new + +task alert_receiver_alert_rsp_seq::body(); + if (cfg.start_default_rsp_seq) begin + default_rsp_thread(); + end else begin + super.body(); + end +endtask : body + +task alert_receiver_alert_rsp_seq::default_rsp_thread(); + alert_seq_item req_q[$]; + fork + forever begin : get_req + p_sequencer.req_analysis_fifo.get(req); + if (req.m_trans_type == AlertSigTrans) req_q.push_back(req); + end : get_req + forever begin : send_rsp + if (cfg.in_reset) begin + req_q.delete(); + wait (!cfg.in_reset); + end + wait (req_q.size()); + rsp = req_q.pop_front(); + start_item(rsp); + if (!rsp.randomize() with { + m_trans_type == local::m_trans_type; + cfg.ack_delay_min <= m_ack_delay && m_ack_delay <= cfg.ack_delay_max; + cfg.ack_stable_min <= m_ack_stable && m_ack_stable <= cfg.ack_stable_max; + }) begin + `uvm_error(get_full_name(), "Failed to randomize rsp") + end + finish_item(rsp); + get_response(rsp); + end : send_rsp + join +endtask : default_rsp_thread diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_base_seq.sv new file mode 100644 index 0000000..051e799 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_base_seq.sv @@ -0,0 +1,44 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this is a base sequence for alert_receiver side +class alert_receiver_base_seq extends dv_base_seq #( + .REQ (alert_seq_item), + .CFG_T (alert_agent_cfg), + .SEQUENCER_T (alert_sequencer) + ); + + `uvm_object_utils(alert_receiver_base_seq) + + rand alert_trans_type_e m_trans_type; + + extern function new (string name = ""); + extern task body(); + +endclass : alert_receiver_base_seq + +function alert_receiver_base_seq::new (string name = ""); + super.new(name); +endfunction : new + +task alert_receiver_base_seq::body(); + `uvm_info(`gfn, $sformatf("starting alert receiver transfer"), UVM_HIGH) + req = alert_seq_item::type_id::create("req"); + start_item(req); + + if (!req.randomize() with { + m_trans_type == local::m_trans_type; + cfg.ack_delay_min <= m_ack_delay && m_ack_delay <= cfg.ack_delay_max; + cfg.ack_stable_min <= m_ack_stable && m_ack_stable <= cfg.ack_stable_max; + m_int_err_cyc == 0; // This agent do not support alert_receiver int_err + }) begin + `uvm_fatal(get_full_name(), "Failed to randomize req") + end + + `uvm_info(`gfn, $sformatf("seq_item: %0s", m_trans_type.name()), UVM_MEDIUM) + + finish_item(req); + get_response(rsp); + `uvm_info(`gfn, "alert receiver transfer done", UVM_HIGH) +endtask : body diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_ping_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_ping_seq.sv new file mode 100644 index 0000000..b015bde --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_ping_seq.sv @@ -0,0 +1,42 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A sequence that repeatedly sends alert_seq_item items that are configured to request pings. These +// ping requests are configured with large ping_delay values. Note that if an alert is raised while +// the driver is waiting at the start of sending a ping request then the driver will complete the +// item immediately (and the sequencer will then be able to enqueue an alert response item) +class alert_receiver_ping_seq extends dv_base_seq #(.REQ (alert_seq_item), + .CFG_T (alert_agent_cfg), + .SEQUENCER_T (alert_sequencer)); + `uvm_object_utils(alert_receiver_ping_seq) + extern function new (string name=""); + extern virtual task body(); +endclass : alert_receiver_ping_seq + +function alert_receiver_ping_seq::new (string name=""); + super.new(name); +endfunction : new + +task alert_receiver_ping_seq::body(); + forever begin + // Items submitted while cfg.in_reset is asserted are discarded by the driver so there is no point + // creating a new item until reset has cleared + if (cfg.in_reset) wait (!cfg.in_reset); + req = alert_seq_item::type_id::create("req"); + start_item(req); + // Randomise the item to be a ping request. When driven, the item will "wait around" for + // ping_delay cycles before it actually sends the ping. Bound this to be at most + // cfg.ping_delay_max. + if (!req.randomize() with { + m_trans_type == AlertPingTrans; + cfg.ack_delay_min <= m_ack_delay && m_ack_delay <= cfg.ack_delay_max; + cfg.ack_stable_min <= m_ack_stable && m_ack_stable <= cfg.ack_stable_max; + cfg.ping_delay_min <= m_ping_delay && m_ping_delay <= cfg.ping_delay_max; + }) begin + `uvm_error(get_full_name(), "Failed to randomize req") + end + finish_item(req); + get_response(req); + end +endtask : body diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_seq.sv new file mode 100644 index 0000000..1d71615 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_receiver_seq.sv @@ -0,0 +1,21 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this sequence send ping_p and ping_n to trigger ping signals +class alert_receiver_seq extends alert_receiver_base_seq; + + `uvm_object_utils(alert_receiver_seq) + + extern constraint alert_receiver_seq_c; + extern function new (string name = ""); + +endclass : alert_receiver_seq + +constraint alert_receiver_seq::alert_receiver_seq_c { + m_trans_type == AlertPingTrans; +} + +function alert_receiver_seq::new (string name = ""); + super.new(name); +endfunction : new diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_base_seq.sv new file mode 100644 index 0000000..3a27e87 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_base_seq.sv @@ -0,0 +1,56 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this is a base sequence for alert sender side +class alert_sender_base_seq extends dv_base_seq #( + .REQ (alert_seq_item), + .CFG_T (alert_agent_cfg), + .SEQUENCER_T (alert_sequencer) + ); + + `uvm_object_utils(alert_sender_base_seq) + + rand alert_trans_type_e m_trans_type; + + rand bit int_err; + rand bit ping_timeout; + + extern function new (string name = ""); + extern virtual task body(); + +endclass : alert_sender_base_seq + +function alert_sender_base_seq::new (string name = ""); + super.new(name); +endfunction : new + +task alert_sender_base_seq::body(); + `uvm_info(`gfn, $sformatf("starting alert sender transfer"), UVM_HIGH) + req = alert_seq_item::type_id::create("req"); + start_item(req); + + if (!req.randomize() with { + m_trans_type == local::m_trans_type; + + // If int_err is true, override the soft constraint in the sequence item and request a + // nonzero time with an error. + if (local::int_err) { + m_int_err_cyc != 0; + } + + cfg.ack_delay_min <= m_ack_delay && m_ack_delay <= cfg.ack_delay_max; + cfg.alert_delay_min <= m_alert_delay && m_alert_delay <= cfg.alert_delay_max; + }) begin + `uvm_error(get_full_name(), "Failed to randomize req.") + end + + `uvm_info(get_full_name(), + $sformatf("seq_item: %0s, m_int_err_cyc=%0b", + req.m_trans_type.name(), req.m_int_err_cyc), + UVM_MEDIUM) + + finish_item(req); + get_response(rsp); + `uvm_info(`gfn, "alert sender transfer done", UVM_HIGH) +endtask : body diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_ping_rsp_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_ping_rsp_seq.sv new file mode 100644 index 0000000..ac04763 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_ping_rsp_seq.sv @@ -0,0 +1,62 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this sequence responses to ping pins by sending the alert pins +class alert_sender_ping_rsp_seq extends alert_sender_base_seq; + + `uvm_object_utils(alert_sender_ping_rsp_seq) + + extern constraint alert_sender_ping_rsp_seq_c; + + extern function new (string name = ""); + extern virtual task body(); + // Sends random rsps (device data and ack) back to host. + extern virtual task default_rsp_thread(); + +endclass : alert_sender_ping_rsp_seq + +constraint alert_sender_ping_rsp_seq::alert_sender_ping_rsp_seq_c { + m_trans_type == AlertPingTrans; +} + +function alert_sender_ping_rsp_seq::new (string name = ""); + super.new(name); +endfunction : new + +task alert_sender_ping_rsp_seq::body(); + if (cfg.start_default_rsp_seq) begin + default_rsp_thread(); + end else begin + super.body(); + end +endtask : body + +task alert_sender_ping_rsp_seq::default_rsp_thread(); + alert_seq_item req_q[$]; + fork + forever begin : get_req + p_sequencer.req_analysis_fifo.get(req); + if (req.m_trans_type == AlertPingTrans) req_q.push_back(req); + end : get_req + forever begin : send_rsp + if (cfg.in_reset) begin + req_q.delete(); + wait (!cfg.in_reset); + end + wait (req_q.size()); + rsp = req_q.pop_front(); + start_item(rsp); + if (!rsp.randomize() with { + m_trans_type == local::m_trans_type; + m_ping_timeout == 0; + cfg.ack_delay_min <= m_ack_delay && m_ack_delay <= cfg.ack_delay_max; + cfg.alert_delay_min <= m_alert_delay && m_alert_delay <= cfg.alert_delay_max; + }) begin + `uvm_error(get_full_name(), "Failed to randomize rsp") + end + finish_item(rsp); + get_response(rsp); + end : send_rsp + join +endtask : default_rsp_thread diff --git a/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_seq.sv new file mode 100644 index 0000000..52679cc --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/alert_agent/seq_lib/alert_sender_seq.sv @@ -0,0 +1,23 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// this sequence send the alert pins to the receiver +class alert_sender_seq extends alert_sender_base_seq; + + `uvm_object_utils(alert_sender_seq) + + constraint alert_sender_seq_c; + + extern function new (string name = ""); + +endclass : alert_sender_seq + +function alert_sender_seq::new (string name = ""); + super.new(name); +endfunction : new + +constraint alert_sender_seq::alert_sender_seq_c { + m_trans_type == AlertSigTrans; + ping_timeout == 0; +} diff --git a/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/README.md b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/README.md new file mode 100644 index 0000000..826f934 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/README.md @@ -0,0 +1,10 @@ +# bus_params_pkg + +This package provides an isolation for all common verification components under +`hw/dv/sv/` from the OpenTitan specific design constants provided in +`hw/top_earlgrey/rtl/top_pkg.sv`. This mostly includes common bus parameters +such as address and data widths. + +When vendoring the common DV code into another repo, the other repo must +provide its own implementation of `bus_params_pkg` so that the +dependency on the `top_pkg` can be avoided. diff --git a/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.core b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.core new file mode 100644 index 0000000..7659f86 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.core @@ -0,0 +1,19 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:opentitan:bus_params_pkg" +description: "Package holding common bus parameters such as widths." + +filesets: + files_dv: + depend: + - lowrisc:virtual_constants:top_pkg + files: + - bus_params_pkg.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.sv new file mode 100644 index 0000000..d4116d7 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/bus_params_pkg/bus_params_pkg.sv @@ -0,0 +1,64 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package bus_params_pkg; + + // Set the bus address width. +`ifdef BUS_AW + parameter int BUS_AW = `BUS_AW; +`else + parameter int BUS_AW = top_pkg::TL_AW; +`endif + + // Set the bus data width. +`ifdef BUS_DW + parameter int BUS_DW = `BUS_DW; +`else + parameter int BUS_DW = top_pkg::TL_DW; +`endif + + // Set the bus data mask width (# of byte lanes). +`ifdef BUS_DBW + parameter int BUS_DBW = `BUS_DBW; +`else + parameter int BUS_DBW = top_pkg::TL_DBW; +`endif + + // Set the bus transfer size width (# of bits required to select the # of bytes). +`ifdef BUS_SZW + parameter int BUS_SZW = `BUS_SZW; +`else + parameter int BUS_SZW = top_pkg::TL_SZW; +`endif + +// Set the bus address info (source) width. +`ifdef BUS_AIW + parameter int BUS_AIW = `BUS_AIW; +`else + parameter int BUS_AIW = top_pkg::TL_AIW; +`endif + +// Set the bus data info (source) width. +`ifdef BUS_DIW + parameter int BUS_DIW = `BUS_DIW; +`else + parameter int BUS_DIW = top_pkg::TL_DIW; +`endif + +// Set the bus a channel user width. +`ifdef BUS_AUW + parameter int BUS_AUW = `BUS_AUW; +`else + parameter int BUS_AUW = top_pkg::TL_AUW; +`endif + +// Set the bus d channel user width. +`ifdef BUS_DUW + parameter int BUS_DUW = `BUS_DUW; +`else + parameter int BUS_DUW = top_pkg::TL_DUW; +`endif + + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/README.md b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/README.md new file mode 100644 index 0000000..54124d2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/README.md @@ -0,0 +1,114 @@ +# Common Interfaces + +## Overview +In this directory, we provide commonly used interfaces used to construct +testbenches for DV. These interfaces are instantiated inside `tb` module for +connecting dut signals. They are described in detail below. + +### `clk_if` +This is a passive clock interface that is used to wait for clock events in +testbenches. This interface has two clocking blocks, `cb` and `cbn`, for +synchronizing to positive and negative clock edges, respectively. The interface +also has the following tasks: +* `wait_clks`: waits for specified number of positive clock edges +* `wait_n_clks`: waits for specified number of negative clock edges + +### `clk_rst_if` + +Unlike `clk_if`, this interface can generate a clock and a reset signal. These +are connected as `inout` signals and the interface observes them passively +unless the `set_active` function is called. + +Just like `clk_if`, this interface has clocking blocks `cb` and `cbn`, together +with `wait_clks` and `wait_n_clks` utility tasks. It also has +* `wait_for_reset`: wait for a reset signaled on `rst_n` + +To generate a clock signal, call `set_active` at the start of the simulation. +This is typically called from an `initial` block in the testbench. To configure +the frequency and duty cycle of the generated clock, use the following +functions: +* `set_freq_mhz` / `set_freq_khz`: set the clock frequency in MHz / KHz. This + is 50MHz by default. +* `set_period_ps`: set the clock period in picoseconds. This is 20_000ps by default + (giving a clock period of 50MHz). +* `set_duty_cycle`: set the duty cycle (as a percentage: 1 - 99). This is 50 by + default. + +The clock can also have jitter added. This is generated as an offset in +picoseconds added to randomly selected clock half-periods. It can be enabled +and configured with: +* `set_jitter_chance_pc`: set the percentage probability of adding a jitter to + a given half-period. By default, this is 0 and the clock has no jitter. +* `set_max_jitter_ps`: set the maximum jitter to add to each clock half-period + in picoseconds. This is 1000ps (1 ns) by default. + +To start and stop the clock or apply a reset, use the following tasks. These +will have no effect if `set_active` has not been called. +* `start_clk`: start the clock. The clock is started by default, so this + task is only needed after a call to `stop_clk`. +* `stop_clk`: stop / gate the clk +* `apply_reset`: signal a reset on `rst_n`. The length of this reset and + whether it is synchronous or not can be configured with arguments to the + function. + +### `pins_if` + +This parameterized interface provides the ability to drive or sample any signal +in the DUT. + +```systemverilog +interface pins_if #( + parameter int Width = 1 +) ( + inout [Width-1:0] pins +); +``` + +By default, it behaves as a passive interface. The values of the pins can be +read with the following functions: +* `sample`: sample and return all the pin values +* `sample_pin`: sample just the given pin + +The interface can also be configured to drive, pull up, or pull down its +outputs. To do this, call +* `drive` / `drive_pin`: Drive the output to the given value. +* `drive_en` / `drive_en_pin`: Configure output enable; when enabled, this + drives value previously stored by a call to `drive` or `drive_pin`. +* `set_pullup_en` / `set_pullup_en_pin`: Configure pull-up setting. If true and + output enable is false, drives the output to `1`. +* `set_pulldown_en` / `set_pulldown_en_pin`: Configure pull-down setting. If + true and both output_enable and pull-up are false, drives the output to `0`. + +The diagram below gives a schematic view of `pins_if`. The driver shown is +replicated for each bit. + +![Block diagram](pins_if.svg) + +### `entropy_subsys_fifo_exception_if` + +The IPs in the entropy subsystem (`entropy_src`, `CSRNG` and `EDN`) raise fatal alerts if they +detect that data is lost in one of the intermediate FIFOS, either through: + - Write errors (Overflow) wvalid_i asserted when full + - Read errors (Underflow) rready_i asserted when empty (i.e. rvalid_o == 0) + - State errors: Anomalous behavior rvalid_o deasserted (FIFO is not empty) when full + +Furthermore some instances of prim packer fifo's also raise recoverable alerts if firmware +tries to write data to it when it is not ready. + +The events described above need not be treated as errors in general purpose designs. +In many general designs where the fifo is capable of applying backpressure (stalling +the read or write inputs) these do not have to be an error. One could in principal +only signal an alert if it is observed that data was indeed lost (e.g., if `wvalid_i` is +deasserted or data changes before `wready_o` is high). However most of the entropy complex +fifo stages do not respond to such backpressure, and thus the conditions above do +indicate a loss of data. + +The entropy_subsys_fifo_exception_if.sv has pins that can map either to synchronous +FIFOs or to packer fifos. Though some interface ports will be unused in any case +the interface parameter `IsPackerFifo` indicates which ports to use (True for +packer FIFOs or False for synchronous FIFOs. + +The interface then generates error pulses in the `mon_cb` clocking block under +the signal `mon_cb.error_pulses`, which has one line per possible error condition. +The enumeration entropy_subsys_fifo_exception_pkg::fifo_exception_e lists the +types of exceptions and provides the mapping to the corresponding error pulse line. diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_if.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_if.sv new file mode 100644 index 0000000..4729a54 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_if.sv @@ -0,0 +1,29 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +//----------------------------- DESCRIPTION ------------------------------------ +// +// Generic clock interface for clock events in various utilities +// +//------------------------------------------------------------------------------ + +interface clk_if(input logic clk); + + clocking cb @(posedge clk); + endclocking + + clocking cbn @(negedge clk); + endclocking + + // Wait for 'n' clocks based of positive clock edge + task automatic wait_clks(int num_clks); + repeat (num_clks) @cb; + endtask + + // Wait for 'n' clocks based of negative clock edge + task automatic wait_n_clks(int num_clks); + repeat (num_clks) @cbn; + endtask + +endinterface diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv new file mode 100644 index 0000000..27a89be --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/clk_rst_if.sv @@ -0,0 +1,362 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// +// Interface: clk_rst_if +// Generic clock and reset interface for clock events in various utilities +// It also generates o_clk and o_rst_n signals for driving clk and rst_n in the tb. The advantage is +// clk and rst_n can be completely controlled in course of the simulation. +// This interface provides methods to set freq/period, wait for clk/rst_n, apply rst_n among other +// things. See individual method descriptions below. +// inout clk +// inout rst_n + +interface clk_rst_if ( + inout clk, + inout rst_n +); + +`ifndef VERILATOR + // include macros and import pkgs + `include "dv_macros.svh" + `include "uvm_macros.svh" + import uvm_pkg::*; + import common_ifs_pkg::*; +`endif + + // Enables clock to be generated and driven by this interface. + bit drive_clk; + + // The internal output clock value. + logic o_clk; + + // Enables the rst_n to be generated and driven by this interface. + bit drive_rst_n; + + // The internal output reset value. + logic o_rst_n; + + // This event is used to start the initial block driving the clock after set_active sets + // the values of drive_clk and drive_rst_n. + event set_active_called; + + // Applies clock gating. + bit clk_gate = 1'b0; + + // The nominal (chosen) frequency (as period in ps) of the driven clock (50MHz by default). + int clk_period_ps = 20_000; + + // The variation of clock period (mimics uncalibrated clocks), to scale the nominal frequency + // down. If set to non-zero value, the clock frequency is scaled randomly on every edge. + int clk_freq_scaling_pc = 0; + + // The percentage chance of freq scaled down randomly on each edge. + int clk_freq_scaling_chance_pc = 50; + + // Clock frequency is scaled down. This enables the frequency to be randomly scaled up as well. + // + // Note: If set, the randomness of the clock frequency being scaled up or down may result in a + // bigger frequency distribution than the intended clk_freq_scaling_pc setting. For example, 50MHz + // with 10% scaling may result in pulses that are < 45MHz and > 55MHz wide as well. + bit clk_freq_scale_up = 1'b0; + + // The computed clock frequency in MHz. + real clk_freq_mhz = 50; + + // The duty cycle of the clock period as percentage. If jitter and scaling is applied, then the + // duty cycle will not be maintained. + int duty_cycle = 50; + + // Maximum jitter applied to each period of the clock - this is expected to be about 20% or less + // than the clock period. + // The jitter is divided to two values - plus-jitter and minus-jitter. + // Plus jitter is the possible time can be added to the clock period, while the minus jitter is + // the possible time can be subtracted from the clock period. + // _________ + // _____:_| : : |_:_______ + // + // The actual jitter value is picked randomly within the window + // {[-max_minus_jitter_ps:max_plus_jitter_ps]} + // and is added to the time to next edge. + int max_plus_jitter_ps = 1000; + int max_minus_jitter_ps = 1000; + + // The percentage chance of jitter occurring on each edge. If 0 (default value), then jitter is + // disabled altogether. If 100, jitter is computed and applied at every edge. + int jitter_chance_pc = 0; + + // Internal signal indicating the clock half periods need to be recomputed. + bit recompute = 1'b1; + + // Internal signal indicating the amount of time for which the clock stays high / lo in the next + // cycle. + int clk_hi_ps; + int clk_lo_ps; + real clk_hi_modified_ps; + real clk_lo_modified_ps; + + // If true, this is the only clock in the system; there is no need to add initial jitter. + bit sole_clock = 1'b0; + + string msg_id = $sformatf("[%m(clk_rst_if)]"); + + clocking cb @(posedge clk); + endclocking + + clocking cbn @(negedge clk); + endclocking + + // Wait for 'n' clocks based of postive clock edge + task automatic wait_clks(int num_clks); + repeat (num_clks) @cb; + endtask + + // Wait for 'n' clocks based of negative clock edge + task automatic wait_n_clks(int num_clks); + repeat (num_clks) @cbn; + endtask + + // Wait for 'num_clks' clocks based on the positive clock edge or reset, whichever comes first. + task automatic wait_clks_or_rst(int num_clks); + fork begin : isolation_fork + fork + wait_clks(num_clks); + wait_for_reset(.wait_negedge(1'b1), .wait_posedge(1'b0)); + join_any + disable fork; + end join + endtask + + // Wait for 'num_clks' clocks based on the negative clock edge or reset, whichever comes first. + task automatic wait_n_clks_or_rst(int num_clks); + fork begin : isolation_fork + fork + wait_n_clks(num_clks); + wait_for_reset(.wait_negedge(1'b1), .wait_posedge(1'b0)); + join_any + disable fork; + end join + endtask + + // wait for rst_n to assert and then deassert + task automatic wait_for_reset(bit wait_negedge = 1'b1, bit wait_posedge = 1'b1); + if (wait_negedge && ($isunknown(rst_n) || rst_n === 1'b1)) @(negedge rst_n); + if (wait_posedge && (rst_n === 1'b0)) @(posedge rst_n); + endtask + + // set the clk frequency in khz + function automatic void set_freq_khz(int freq_khz); + clk_freq_mhz = $itor(freq_khz) / 1000; + if (drive_clk && clk_freq_mhz <= 0) begin + `uvm_fatal(msg_id, "Since drive_clk is true, freq_mhz must be greater than zero.") + end + clk_period_ps = 1000_000 / clk_freq_mhz; + recompute = 1'b1; + endfunction + + // set the clk frequency in mhz + function automatic void set_freq_mhz(int freq_mhz); + if (drive_clk && freq_mhz <= 0) begin + `uvm_fatal(msg_id, "Since drive_clk is true, freq_mhz must be greater than zero.") + end + set_freq_khz(freq_mhz * 1000); + endfunction + + // Set the clk frequency scaling, chance in percentage and scaling up. + // + // freq_scaling_pc is a positive integer that determines by what amount (as percentage of the + // nominal frequency) is the frequency scaled (jittered) down. + // freq_scaling_chance_pc is a percentage number between 0 and 100 that determines how often is + // the scaling randomly recomputed and applied. + // freq_scale_up is a bit that enables the random scaling up of the frequency as well. + function automatic void set_freq_scaling(int freq_scaling_pc, int freq_scaling_chance_pc = 50, + bit freq_scale_up = 1'b0); + `DV_CHECK_FATAL(freq_scaling_pc >= 0, , msg_id) + `DV_CHECK_FATAL(freq_scaling_chance_pc inside {[0:100]}, , msg_id) + clk_freq_scaling_pc = freq_scaling_pc; + clk_freq_scaling_chance_pc = freq_scaling_chance_pc; + clk_freq_scale_up = freq_scale_up; + endfunction + + // Enables the clock and reset to be driven. + function automatic void set_active(bit drive_clk_val = 1'b1, bit drive_rst_n_val = 1'b1); + if (drive_clk_val && clk_freq_mhz <= 0) begin + `uvm_fatal(msg_id, "Cannot enable drive_clk unless clk_freq_mhz is greater than zero.") + end + + drive_clk = drive_clk_val; + drive_rst_n = drive_rst_n_val; + -> set_active_called; + endfunction + + // set the clk period in ps + function automatic void set_period_ps(int period_ps); + clk_period_ps = period_ps; + clk_freq_mhz = 1000_000 / clk_period_ps; + recompute = 1'b1; + endfunction + + // set the duty cycle (1-99) + function automatic void set_duty_cycle(int duty); + `DV_CHECK_FATAL(duty inside {[1:99]}, , msg_id) + duty_cycle = duty; + recompute = 1'b1; + endfunction + + // set maximum jitter in ps, separating the plus jitter and the minus jitter. + // In default the plus and minus jitters are the same. + function automatic void set_max_jitter_ps(int plus_jitter_ps, + int minus_jitter_ps = plus_jitter_ps); + max_plus_jitter_ps = plus_jitter_ps; + max_minus_jitter_ps = minus_jitter_ps; + endfunction + + // set jitter chance in percentage (0 - 100) + // 0 - dont add any jitter; 100 - add jitter on every clock edge + function automatic void set_jitter_chance_pc(int jitter_chance); + `DV_CHECK_FATAL(jitter_chance inside {[0:100]}, , msg_id) + jitter_chance_pc = jitter_chance; + endfunction + + // Set whether this is the only clock in the system. If true, various bits of timing randomisation + // are disabled. If there's no other clock to (de)synchronise with, this should not weaken the + // test at all. + function automatic void set_sole_clock(bit is_sole = 1'b1); + sole_clock = is_sole; + endfunction + + // start / ungate the clk + task automatic start_clk(bit wait_for_posedge = 1'b0); + clk_gate = 1'b0; + if (wait_for_posedge) wait_clks(1); + endtask + + // stop / gate the clk + function automatic void stop_clk(); + clk_gate = 1'b1; + endfunction + + // Scales the clock frequency up and down on every edge. + function automatic void apply_freq_scaling(); + real scaling; + real mult = $urandom_range(0, int'(clk_freq_scale_up)) ? 1.0 : -1.0; + + if ($urandom_range(1, 100) <= clk_freq_scaling_chance_pc) begin + scaling = 1.0 + mult * real'($urandom_range(0, clk_freq_scaling_pc)) / 100; + clk_hi_modified_ps = clk_hi_ps * scaling; + scaling = 1.0 + mult * real'($urandom_range(0, clk_freq_scaling_pc)) / 100; + clk_lo_modified_ps = clk_lo_ps * scaling; + end + endfunction + + // Applies jitter to clk_hi and clk_lo half periods based on jitter_chance_pc. + function automatic void apply_jitter(); + int jitter; + int plus_jitter; + int minus_jitter; + + if ($urandom_range(1, 100) <= jitter_chance_pc) begin + plus_jitter = $urandom_range(0, max_plus_jitter_ps/2); + minus_jitter = $urandom_range(0, max_minus_jitter_ps/2); + jitter = ($urandom_range(0, 1) ? plus_jitter : (-1 * minus_jitter)); + clk_hi_modified_ps = clk_hi_ps + jitter; + end + if ($urandom_range(1, 100) <= jitter_chance_pc) begin + plus_jitter = $urandom_range(0, max_plus_jitter_ps/2); + minus_jitter = $urandom_range(0, max_minus_jitter_ps/2); + jitter = ($urandom_range(0, 1) ? plus_jitter : (-1 * minus_jitter)); + clk_lo_modified_ps = clk_lo_ps + jitter; + end + endfunction + + // can be used to override clk/rst pins, e.g. at the beginning of the simulation + task automatic drive_rst_pin(logic val = 1'b0); + o_rst_n = val; + endtask + + // apply reset with specified scheme + task automatic apply_reset(int reset_width_clks = $urandom_range(50, 100), + int post_reset_dly_clks = 0, + rst_scheme_e rst_n_scheme = RstAssertAsyncDeassertSync); + if (drive_rst_n) begin + int dly_ps; + dly_ps = $urandom_range(0, clk_period_ps); + case (rst_n_scheme) + RstAssertSyncDeassertSync: begin + o_rst_n <= 1'b0; + wait_clks(reset_width_clks); + o_rst_n <= 1'b1; + end + RstAssertAsyncDeassertSync: begin + #(dly_ps * 1ps); + o_rst_n <= 1'b0; + wait_clks(reset_width_clks); + o_rst_n <= 1'b1; + end + RstAssertAsyncDeassertASync: begin + #(dly_ps * 1ps); + o_rst_n <= 1'b0; + wait_clks(reset_width_clks); + dly_ps = $urandom_range(0, clk_period_ps); + #(dly_ps * 1ps); + o_rst_n <= 1'b1; + end + default: begin + `dv_fatal($sformatf("rst_n_scheme %0d not supported", rst_n_scheme), msg_id) + end + endcase + wait_clks(post_reset_dly_clks); + end + endtask + + // clk gen when the clock is active, so this waits until the set_active function was called. + initial begin + // start driving clk only after the first por reset assertion. The fork/join means that we'll + // wait a whole number of clock periods, which means it's possible for the clock to synchronise + // with the "expected" timestamps. + bit done; + @set_active_called; + if (drive_clk) begin + fork + begin + // Only wait for reset if driving it, otherwise it may never come. + if (drive_rst_n) begin + wait_for_reset(.wait_posedge(1'b0)); + + // Wait a short time after reset before starting to drive the clock. + #1ps; + end + o_clk = 1'b0; + + done = 1'b1; + end + while (!done) #(clk_period_ps * 1ps); + join + + // If there might be multiple clocks in the system, wait another (randomised) short time to + // desynchronise. + if (!sole_clock) #($urandom_range(0, clk_period_ps) * 1ps); + + forever begin + if (recompute) begin + clk_hi_ps = clk_period_ps * duty_cycle / 100; + clk_lo_ps = clk_period_ps - clk_hi_ps; + clk_hi_modified_ps = clk_hi_ps; + clk_lo_modified_ps = clk_lo_ps; + recompute = 1'b0; + end + if (clk_freq_scaling_pc && clk_freq_scaling_chance_pc) apply_freq_scaling(); + if (jitter_chance_pc) apply_jitter(); + #(clk_lo_modified_ps * 1ps); + if (!clk_gate) o_clk = 1'b1; + #(clk_hi_modified_ps * 1ps); + o_clk = 1'b0; + end + end + end + + assign clk = drive_clk ? o_clk : 1'bz; + assign rst_n = drive_rst_n ? o_rst_n : 1'bz; + +endinterface diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs.core b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs.core new file mode 100644 index 0000000..e646798 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs.core @@ -0,0 +1,22 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:common_ifs" +description: "Common interfaces used in DV" + +filesets: + files_dv: + depend: + - lowrisc:prim:assert + - lowrisc:dv:pins_if + files: + - common_ifs_pkg.sv + - clk_if.sv + - clk_rst_if.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs_pkg.sv new file mode 100644 index 0000000..d240966 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/common_ifs_pkg.sv @@ -0,0 +1,15 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package common_ifs_pkg; + // dep packages + import uvm_pkg::*; + + // Enum representing reset scheme + typedef enum bit [1:0] { + RstAssertSyncDeassertSync, + RstAssertAsyncDeassertSync, + RstAssertAsyncDeassertASync + } rst_scheme_e; +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.core b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.core new file mode 100644 index 0000000..981934f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.core @@ -0,0 +1,20 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:entropy_subsys_fifo_exception_if" +description: "DV interface for detecting FIFO exceptions, particularly in entropy subsystem IPs" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_lib + files: + - entropy_subsys_fifo_exception_pkg.sv + - entropy_subsys_fifo_exception_if.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.sv new file mode 100644 index 0000000..07dd244 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_if.sv @@ -0,0 +1,59 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// Interface for capturing overflow/underflow/status events in +// entropy complex (entropy_src, CSRNG, EDN) fifos + + +interface entropy_subsys_fifo_exception_if#( + parameter bit IsPackerFifo = 0 +) +( + input logic clk_i, + input logic rst_ni, + + input logic wready_o, + input logic wvalid_i, + input logic rready_i, + input logic rvalid_o, + input logic full_o +); + + import entropy_subsys_fifo_exception_pkg::*; + + logic read_err_d, write_err_d, state_err_d; + logic read_err_q, write_err_q, state_err_q; + logic read_err_pulse, write_err_pulse, state_err_pulse; + logic write_forbidden; + + logic [N_FIFO_ERR_TYPES-1:0] error_pulses; + assign error_pulses[FIFO_READ_ERR] = read_err_pulse; + assign error_pulses[FIFO_WRITE_ERR] = write_err_pulse; + assign error_pulses[FIFO_STATE_ERR] = state_err_pulse; + + // Error conditions map to the types of events that cause errors in the + // entropy subsystem IPs + assign write_forbidden = IsPackerFifo ? !wready_o : full_o; + + assign write_err_d = wvalid_i && write_forbidden; + assign read_err_d = IsPackerFifo ? 1'b0 : (!rvalid_o && rready_i); + assign state_err_d = IsPackerFifo ? 1'b0 : (!rvalid_o && full_o); + + always @(posedge clk_i) begin + state_err_q <= state_err_d; + read_err_q <= read_err_d; + write_err_q <= write_err_d; + end + + clocking mon_cb @(posedge clk_i); + input write_forbidden; + input error_pulses; + endclocking + + + assign write_err_pulse = write_err_d && !write_err_q; + assign state_err_pulse = state_err_d && !state_err_q; + assign read_err_pulse = read_err_d && !read_err_q; + +endinterface : entropy_subsys_fifo_exception_if diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_pkg.sv new file mode 100644 index 0000000..700e429 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/entropy_subsys_fifo_exception_pkg.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// +// Datatypes for describing FIFO exceptions in the Entropy Subsystem +// + +package entropy_subsys_fifo_exception_pkg; + + typedef enum int { + FIFO_READ_ERR = 0, + FIFO_WRITE_ERR, + FIFO_STATE_ERR, + N_FIFO_ERR_TYPES + } fifo_exception_e; + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.sv new file mode 100644 index 0000000..bf90c27 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.sv @@ -0,0 +1,116 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Interface: pins_if +// Description: Pin interface for driving and sampling individual pins such as interrupts, alerts +// and gpios. +`ifndef SYNTHESIS + +interface pins_if #( + parameter int Width = 1, + parameter bit [8*4-1:0] PullStrength = "Pull" +) ( + inout [Width-1:0] pins +); + + `include "prim_assert.sv" + + `ASSERT_INIT(PullStrengthParamValid, PullStrength inside {"Weak", "Pull"}) + + logic [Width-1:0] pins_o; // value to be driven out + bit [Width-1:0] pins_oe = '0; // output enable + bit [Width-1:0] pins_pd = '0; // pull down enable + bit [Width-1:0] pins_pu = '0; // pull up enable + + // function to set pin output enable for specific pin (useful for single pin interface) + function automatic void drive_en_pin(int idx = 0, bit val); + pins_oe[idx] = val; + endfunction + + // function to set pin output enable for all pins + function automatic void drive_en(bit [Width-1:0] val); + pins_oe = val; + endfunction + + // function to drive a specific pin with a value (useful for single pin interface) + function automatic void drive_pin(int idx = 0, logic val); + pins_oe[idx] = 1'b1; + pins_o[idx] = val; + endfunction // drive_pin + + // function to drive all pins + function automatic void drive(logic [Width-1:0] val); + pins_oe = {Width{1'b1}}; + pins_o = val; + endfunction // drive + + // function to drive all pull down values + function automatic void set_pulldown_en(bit [Width-1:0] val); + pins_pd = val; + endfunction // set_pulldown_en + + // function to drive all pull up values + function automatic void set_pullup_en(bit [Width-1:0] val); + pins_pu = val; + endfunction // set_pullup_en + + // function to drive the pull down value on a specific pin + function automatic void set_pulldown_en_pin(int idx = 0, bit val); + pins_pd[idx] = val; + endfunction // set_pulldown_en_pin + + // function to drive the pull up value on a specific pin + function automatic void set_pullup_en_pin(int idx = 0, bit val); + pins_pu[idx] = val; + endfunction // set_pullup_en_pin + + // function to sample a specific pin (useful for single pin interface) + function automatic logic sample_pin(int idx = 0); + return pins[idx]; + endfunction + + // function to sample all pins + function automatic logic [Width-1:0] sample(); + return pins; + endfunction + + // Fully disconnect this interface, including the pulls. + function automatic void disconnect(); + pins_oe = {Width{1'b0}}; + pins_pu = {Width{1'b0}}; + pins_pd = {Width{1'b0}}; + endfunction + + // make connections + for (genvar i = 0; i < Width; i++) begin : gen_each_pin +`ifdef VERILATOR + assign pins[i] = pins_oe[i] ? pins_o[i] : + pins_pu[i] ? 1'b1 : + pins_pd[i] ? 1'b0 : 1'bz; +`else + // Drive the pin based on whether pullup / pulldown is enabled. + // + // If output is not enabled, then the pin is pulled up or down with the `PullStrength` strength + // Pullup has priority over pulldown. + if (PullStrength == "Pull") begin : gen_pull_strength_pull + assign (pull0, pull1) pins[i] = ~pins_oe[i] ? (pins_pu[i] ? 1'b1 : + pins_pd[i] ? 1'b0 : 1'bz) : 1'bz; + end : gen_pull_strength_pull + else if (PullStrength == "Weak") begin : gen_pull_strength_weak + assign (weak0, weak1) pins[i] = ~pins_oe[i] ? (pins_pu[i] ? 1'b1 : + pins_pd[i] ? 1'b0 : 1'bz) : 1'bz; + end : gen_pull_strength_weak + + // If output enable is 1, strong driver assigns pin to 'value to be driven out'; + // the external strong driver can still affect pin, if exists. + // Else if output enable is 0, weak pullup or pulldown is applied to pin. + // By doing this, we make sure that weak pullup or pulldown does not override + // any 'x' value on pin, that may result due to conflicting values + // between 'value to be driven out' and the external driver's value. + assign pins[i] = pins_oe[i] ? pins_o[i] : 1'bz; +`endif + end : gen_each_pin + +endinterface +`endif diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.svg b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.svg new file mode 100644 index 0000000..0d624ff --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_if.svg @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + pins_if + + 00 + 01 + 10 + 11 + + + + + + + + + + z + 1 + 0 + 0 + 0 + 1 + + + + + pins_int + + + pu + pd + + + + + + + + + + + pins_oe + + pins_o + + + + + + + + (strong0, strong1) + (pull0, pull1) + + external driver + pins + + diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_ifs.core b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_ifs.core new file mode 100644 index 0000000..4663365 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/pins_ifs.core @@ -0,0 +1,17 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:pins_if" +description: "Common interfaces used in DV" + +filesets: + files_dv: + files: + - pins_if.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.core b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.core new file mode 100644 index 0000000..8cbbcaf --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.core @@ -0,0 +1,17 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:rst_shadowed_if" +description: "Shadowed reset pin interfaces used in DV" + +filesets: + files_dv: + files: + - rst_shadowed_if.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.sv b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.sv new file mode 100644 index 0000000..3a7e02e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/common_ifs/rst_shadowed_if.sv @@ -0,0 +1,39 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// +// Interface: rst_shadowed_if +// An interface to drive rst_shadowed_n pin +// By default, the `rst_shadowed_n` pin is directly connected to `rst_n` pin from the IP. +// This interface provide methods to drive `rst_shadowed_n` pin when `drive_shadow_rst_pin()` task is +// called, and can use `reconnect_shadowed_rst_n_to_rst_n()` to reconnect to `rst_n` pin. +interface rst_shadowed_if ( + input rst_n, + output rst_shadowed_n +); + +`ifndef VERILATOR + // include macros and import pkgs + `include "dv_macros.svh" + `include "uvm_macros.svh" + import uvm_pkg::*; +`endif + + bit drive_shadowed_rst_en; + logic shadowed_rst_n; + + // If set `drive_shadowed_rst_en` bit to 0, the `rst_shadowed_n` output will be the same as IP + // level reset pin. + function automatic void reconnect_shadowed_rst_n_to_rst_n(); + drive_shadowed_rst_en = 0; + endfunction + + task automatic drive_shadow_rst_pin(logic val); + shadowed_rst_n = val; + drive_shadowed_rst_en = 1; + endtask + + assign rst_shadowed_n = drive_shadowed_rst_en ? shadowed_rst_n : rst_n; + +endinterface diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/README.md b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/README.md new file mode 100644 index 0000000..9136e8e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/README.md @@ -0,0 +1,134 @@ +# CSR utilities + +This folder implements CSR related methods and test sequences for DV to share across all testbenches. + +## CSR utility package + +`csr_utils_pkg` provides common methods and properties to support and manage CSR accesses and CSR related test sequences. + +### Global types and variables + +All common types and variables are defined at this package level. Examples are: +```systemverilog + uint outstanding_accesses = 0; + uint default_timeout_ns = 1_000_000; +``` + +### Outstanding_accesses + +Historically, `csr_utils_pkg` has used an internal variable to count accesses (read or write) that have not yet completed. +One intended use for this was to avoid injecting resets when CSR accesses were in flight. +This didn't really work very well, so most blocks' testbenches are being ported to avoid worrying about that. +The mechanism is also unaware of register accesses that are not made through this package. + +Sequences that wish to maintain the counter can do so with the following functions: +```systemverilog + function automatic void increment_outstanding_access(); + outstanding_accesses++; + endfunction + + function automatic void decrement_outstanding_access(); + outstanding_accesses--; + endfunction + + task automatic wait_no_outstanding_access(); + wait(outstanding_accesses == 0); + endtask + + function automatic void clear_outstanding_access(); + outstanding_accesses = 0; + endfunction +``` + +### CSR spinwait + +One of the commonly used tasks in `csr_utils_pkg` is `csr_spinwait`. +This task can poll a register or field continuously or periodically until it reads out the expected value. +This task also has a timeout check to fail the test more quickly if the target never returns the expected value. +The following example uses `csr_spinwait` to wait until the `FIFO_FULL` field of the `STATUS` CSR becomes zero: +```systemverilog +csr_spinwait(.ptr(ral.status.fifo_full), .exp_data(1'b0)); +``` + +### Read and check all CSRs + +This task reads all the CSRs in a register block and checks they return their predicted values. +It is primarily intended for after reset, to check CSRs are being reset to the correct values. + +### Reset state + +Because `csr_utils_pkg` is not connected to any interface, methods inside this package are not able to get reset information. +An internal `under_reset` bit can be kept up to date with two functions: +```systemverilog +function automatic void reset_asserted(); + under_reset = 1; +endfunction + +function automatic void reset_deasserted(); + under_reset = 0; +endfunction +``` +This reset information is tracked by `dv_base_scoreboard` (using its `monitor_reset` task). +When that task sees a reset, it calls `reset_asserted` or `reset_deasserted` in its environment config. +That function, in turn, calls the `csr_utils_pkg` function. + +### Global CSR util methods +#### Global methods for CSR and MEM attributes +This package provides methods to access CSR or Memory attributes, such as address, +value, etc. Examples are: + * `get_mem_addr_ranges` + * `decode_csr_or_field` + +The CSR access methods are based on `uvm_reg` methods, such as `uvm_reg::read()`, `uvm_reg::write()`, `uvm_reg::update()`. +For all CSR methods, user can pass either a register or a field handle. +Examples are: + * `csr_rd_check`: + This task takes a register or field does a register read to get the value. + The value returned will then be compared against a prediction for the argument field or register. + To pass the prediction explicitly, leave `compare_vs_ral = 0` and set `compare_value` to the prediction. + If `compare_vs_ral` is true, the task compares against the prediction the register model. + + * `csr_update`: + Perform a register write to update a register or field to the desired value. + +These tasks can be used in blocking or non-blocking mode and also have timeouts. + * In blocking mode, the task will not finish until the CSR access completes. + * Non-blocking mode allows multiple CSR accesses to be issued back-to-back without waiting for responses. + * The tasks run with a timeout in nanoseconds. + If the time runs out, the task will disable the thread making the access and will raise a UVM error. + +## CSR sequence library + +`csr_seq_lib.sv` provides common CSR related test sequences to share across all testbenches. +These test sequences build on the standard sequences provided in UVM1.2 RAL. +The parent class (DUT-specific test or sequence class) that creates them needs to provide a RAL model. +The list of CSRs is extracted from the RAL model to perform the checks. + +In addition, the test sequences provide an ability to exclude a CSR from writes or reads (or both). +This is explained more in the [CSR exclusion methodology](#csr-exclusion-methodology) section below. +All CSR accesses in these sequences are non-blocking to ensure back-to-back scenarios are exercised. + +Supported CSR test sequences are: + * `csr_hw_reset_seq`: + Write all CSRs with random values and then reset the DUT. + After reset, read all CSRs and compare with expected values + + * `csr_rw`: + Write random values to each register in a list, then read the registers back again. + This compares against predictions from the register model. + The predictions are either generated by the sequence or by an external scoreboard. + + * `csr_bit_bash`: + Perform a bit-bash test on each register in a list. + That test, in turn, performs a bit-bash test on each bit in the register. + The bit-bash test for a bit is to write each value (0 and 1) and read it back to check the write worked. + + * `csr_aliasing`: + Perform an aliasing test for each register in a list. + This test writes a random value to the register and then reads every register back again. + The selected register should have the predicted value after the write. + All other registers should have the values they had before the write. + This checks that there is no aliasing between registers in the block. + + * `mem_walk`: + Run `uvm_mem_walk_seq` on every `dv_base_reg_block`. diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_aliasing_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_aliasing_seq.sv new file mode 100644 index 0000000..71465d5 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_aliasing_seq.sv @@ -0,0 +1,172 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// For each CSR, this sequence writes a random value to it and reads ALL CSRs back. The read value +// of the CSR that was written is checked for correctness while adhering to its access policies. The +// read value of all other CSRs are compared against their previous values. This verifies that there +// is no aliasing across the address bits within the valid CSR space. + +class csr_aliasing_seq extends csr_base_seq; + `uvm_object_utils(csr_aliasing_seq) + + // A queue of uvm_reg objects + typedef uvm_reg reg_queue_t[$]; + + // The size of "register chunk" to use in the test. + // + // The list of CSRs to test (test_csrs) is checked in chunks of this size (writing a random value + // to each register in a chunk, then reading back every register in the design to check that there + // was no aliasing). + int unsigned m_chunk_size = 10; + + // The number of registers to read after writing a chunk of registers, looking for values that + // have changed unexpectedly. + int unsigned m_reads_per_chunk = 100; + + extern function new(string name=""); + extern task body(); + + // Write a random value to csr, after applying any write exclusion that has been defined for the + // register. + extern local task randomize_register(uvm_reg csr); + + // Write random values to each register in the list, running the sequences in parallel for maximum + // throughput. + extern local task randomize_chunk(const ref uvm_reg registers[$]); + + // Read back csr using csr_rd_check and checking against the register model. Mask the comparison + // using get_mask_excl_fields (to avoid checking the values of fields that are not modelled). + extern local task read_back_register(uvm_reg csr); + + // Read back every register in the list, using csr_rd_check and checking against the register + // model. + // + // Comparisons are masked using get_mask_excl_fields (to avoid checking the values of fields that + // are not modelled). + extern local task read_back_chunk(uvm_reg registers[$]); + + // Write random values to each register in write_list, then read all the registers in read_list + extern local task test_chunk(uvm_reg write_list[$], uvm_reg read_list[$]); + + // Return a random subset of reg_queue with m_reads_per_chunk registers (or the entire list if + // there aren't that many) + extern local function reg_queue_t sample_reg_list(const ref uvm_reg reg_queue[$]); +endclass + +function csr_aliasing_seq::new(string name=""); + super.new(name); +endfunction + +task csr_aliasing_seq::body(); + uvm_reg total_list[$]; + int unsigned num_chunks; + + // The subset of test_csrs consisting of registers that do not have the CsrExclWrite exclusion. + // This will be split into chunks of size m_chunk_size. + uvm_reg regs_to_write[$]; + + // The subset of test_csrs consisting of registers that do not have the CsrExclInitCheck or + // CsrExclWriteCheck exclusion. Since test_csrs is just a section of all_csrs, this list is + // probably much larger than regs_to_write. + // + // A random sample of m_reads_per_chunk of these registers will be read back for each chunk. + uvm_reg regs_to_read[$]; + + foreach(test_csrs[i]) begin + if (!is_excl(test_csrs[i], CsrExclWrite, CsrAliasingTest)) begin + regs_to_write.push_back(test_csrs[i]); + end + end + foreach (all_csrs[i]) begin + if (!(is_excl(test_csrs[i], CsrExclInitCheck, CsrAliasingTest) || + is_excl(test_csrs[i], CsrExclWriteCheck, CsrAliasingTest))) begin + regs_to_read.push_back(test_csrs[i]); + end + end + + `uvm_info(get_full_name(), + $sformatf({"Aliasing test with list of %0d writable and %0d readable registers ", + "(from a group of %0d registers selected from the %0d that are visible)"}, + regs_to_write.size(), regs_to_read.size(), + test_csrs.size(), all_csrs.size()), + UVM_LOW) + + // The test will break the registers that get written into chunks, of size m_chunk_size. + num_chunks = (regs_to_write.size() + m_chunk_size - 1) / m_chunk_size; + + for (int unsigned i = 0; i < num_chunks; i++) begin + // The [start_idx:end_idx] range is [i*m_chunk_size, (i+1)*m_chunk_size - 1], intersected with + // the set of valid indices for regs_to_write. + int unsigned start_idx = i * m_chunk_size; + int unsigned end_idx = start_idx + m_chunk_size - 1; + + if (end_idx >= regs_to_write.size()) begin + end_idx = regs_to_write.size() - 1; + end + + `uvm_info(get_full_name(), + $sformatf("Testing aliasing with chunk %0d/%0d", i + 1, num_chunks), + UVM_LOW) + for (int unsigned j = start_idx; j <= end_idx; j++) begin + `uvm_info(get_full_name(), $sformatf(" - %0s", regs_to_write[j].get_name()), UVM_MEDIUM) + end + + test_chunk(regs_to_write[start_idx:end_idx], sample_reg_list(regs_to_read)); + end +endtask + +task csr_aliasing_seq::randomize_register(uvm_reg csr); + uvm_reg_data_t wdata; + + if (!std::randomize(wdata)) begin + `uvm_fatal(get_full_name(), "Failed to randomize wdata.") + end + + wdata = get_csr_wdata_with_write_excl(csr, wdata, CsrAliasingTest); + csr_wr(.ptr(csr), .value(wdata), .predict(!external_checker)); +endtask + +task csr_aliasing_seq::randomize_chunk(const ref uvm_reg registers[$]); + fork : isolation_fork begin + foreach (registers[i]) begin + automatic uvm_reg _reg = registers[i]; + fork + randomize_register(_reg); + join_none + end + wait fork; + end join +endtask + +task csr_aliasing_seq::read_back_register(uvm_reg csr); + csr_rd_check(.ptr (csr), + .compare (!external_checker), + .compare_vs_ral(1'b1), + .compare_mask (get_mask_excl_fields(csr, CsrExclWriteCheck, CsrAliasingTest))); +endtask + +task csr_aliasing_seq::read_back_chunk(uvm_reg registers[$]); + fork : isolation_fork begin + foreach (registers[i]) begin + automatic uvm_reg _reg = registers[i]; + fork + read_back_register(_reg); + join_none + end + wait fork; + end join +endtask + +task csr_aliasing_seq::test_chunk(uvm_reg write_list[$], uvm_reg read_list[$]); + randomize_chunk(write_list); + read_back_chunk(read_list); +endtask + +function csr_aliasing_seq::reg_queue_t + csr_aliasing_seq::sample_reg_list(const ref uvm_reg reg_queue[$]); + + uvm_reg ret[$] = reg_queue; + ret.shuffle(); + return (reg_queue.size() < m_reads_per_chunk) ? ret[0:m_reads_per_chunk - 1] : ret; +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_base_seq.sv new file mode 100644 index 0000000..396dbb8 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_base_seq.sv @@ -0,0 +1,239 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// The base class for CSR sequences, deriving from uvm_reg_sequence +// +// To use this sequence, create the object and then populate models, external_checker, and +// num_test_csrs. Run the sequence by calling the start() task. +// +// Any subclass of this sequence performs tests across a set of registers in the design. The +// complete list of available registers is computed just before the sequence body (in the pre_start +// task), but a test may wish to check a smaller subset of these registers. +// +// To make that possible there is a plusarg-based mechanism: +// +// +num_test_csrs= +// +// If num_test_csrs is a positive number, the list of CSRs in all_csrs is divided into +// contiguous chunks of that length and then the sequence operates on some randomly chosen chunk +// from that list. +// +// If max_num_test_csrs has been set to a positive number after creating the sequence, it is +// used as another upper bound on the number of CSRs in a chunk for the sequence. + +class csr_base_seq extends uvm_reg_sequence #(uvm_sequence #(uvm_reg_item)); + `uvm_object_utils(csr_base_seq) + + // A queue of register models (UVM register blocks), whose registers will be added to the lists of + // CSRs (all_csrs and test_csrs) in pre_start. + dv_base_reg_block models[$]; + + // A flag that is true if there is some external checker (scoreboard). + // + // If it is false then each register write is followed by a call to that register's predict + // function in order to update the mirrored value. Similarly, reads are checked against the + // register's mirrored value (using the by passing a true "compare" argument to the csr_rd_check + // task). + // + // If the flag is true, the sequence doesn't do predict and compare, instead leaving that to the + // scoreboard. + // + // In either case, the prediction and comparison happen as part of the register write/read, which + // means that this sequence can do completely non-blocking writes and reads. + bit external_checker; + + // An upper bound on the number of CSRs that are tested by this sequence. It can be set by the + // creator before starting the sequence. If not overridden, this will be zero (meaning there is no + // upper bound). + int unsigned max_num_test_csrs; + + // A queue holding every register across the blocks in models. + protected uvm_reg all_csrs[$]; + + // A queue of the CSR registers that have been selected for this test. These are contained in + // all_csrs, but may be a proper subset if set_csr_test_range has picked only some of them (as + // instructed by max_num_test_csrs). They will also be shuffled into a random order. + // + // The queue gets populated by set_csr_test_range, which is called by the pre_start task. It is + // then cleared by post_start, to ensure that it will be re-populated if the sequence is run + // again. + protected uvm_reg test_csrs[$]; + + extern function new (string name=""); + + // The pre_start task overrides that of uvm_sequence_base. + // + // It is run just before the body task and is in charge of selecting a subset of all_csrs on which + // the sequence will operate. This subset is written to test_csrs. + extern task pre_start(); + + // The post_start task overrides that of uvm_sequence_base. + // + // It is run just after the body task. In the body task, the sequence will have requested a stream + // of CSR accesses, but the implementation doesn't necessarily wait for the accesses to complete. + // To make sure they have actually done so, the post_start task waits for a period with no + // outstanding CSR accesses (which would mean that each access is done). + // + // The task also clears test_csrs, which means that the same sequence can be run another time and + // the randomisation in set_csr_test_range might pick a different set of test CSRs. + extern task post_start(); + + // Pick a subset of all_csrs and write that to test_csrs. The function's behaviour is described in + // the comment about plusargs before the class. + extern local function void set_csr_test_range(); + + // Return true if this is a CSR or field that has been excluded from the test described in + // csr_test_type by some exclusion (that ultimately came from the hjson register description). + extern function bit is_excl(uvm_object obj, + csr_excl_type_e csr_excl_type, + csr_test_type_e csr_test_type); + + // Return true if this CSR should be excluded by the current sequence. The base class always + // returns false, but this allows more specialised sequences to work over more evenly sized + // chunks. + extern virtual protected function bit csr_excluded(uvm_reg csr); +endclass + +function csr_base_seq::new (string name=""); + super.new(name); +endfunction + +task csr_base_seq::pre_start(); + super.pre_start(); + + // Create test_csrs list only if it is empty. Note that this won't actually do anything if the + // entries in the models array don't have any registers. + if (test_csrs.size() == 0) begin + set_csr_test_range(); + end +endtask + +task csr_base_seq::post_start(); + super.post_start(); + wait_no_outstanding_access(); + test_csrs.delete(); +endtask + +function void csr_base_seq::set_csr_test_range(); + bit has_ntc, has_tcc; + + int unsigned num_csrs; + int num_test_csrs; + + int unsigned start_idx, end_idx; + + // Extract all csrs from the model. If this sequence has specialised the csr_excluded function, + // some CSRs might be skipped. This should help to keep chunks with similar testing times. + all_csrs.delete(); + foreach (models[i]) begin + uvm_reg model_csrs[$]; + models[i].get_registers(model_csrs); + foreach (model_csrs[j]) begin + if (!csr_excluded(model_csrs[j])) begin + all_csrs.push_back(model_csrs[j]); + end else begin + `uvm_info(`gtn, + $sformatf("Skipping register %0s due to exclusion", + model_csrs[j].get_full_name()), + UVM_MEDIUM) + end + end + end + + num_csrs = all_csrs.size(); + if (!num_csrs) return; + + // Has the num_test_csrs plusarg been supplied to give the maximum size of a chunk? + if ($value$plusargs("num_test_csrs=%0d", num_test_csrs)) begin + // Check that the user hasn't requested chunks of less than one: that wouldn't make much sense. + // Generate a UVM error and ignore the plusarg. + if (num_test_csrs < 1) begin + `uvm_error(`gtn, $sformatf("+num_test_csrs=%0d, which is not positive.", num_test_csrs)) + end else begin + has_ntc = 1; + + // If num_test_csrs is greater than the total number of CSRs, clip it to what is available. + if (num_test_csrs > num_csrs) begin + num_test_csrs = num_csrs; + end + end + end + + if (has_ntc || max_num_test_csrs > 0) begin + int unsigned num_chunks, chunk_size, chunk_idx; + + // Take the smaller supplied value of num_test_csrs and max_num_test_csrs to give an upper bound + // on the size of a chunk. + int unsigned max_chunk_size; + if (max_num_test_csrs > 0) begin + if (has_ntc) begin + max_chunk_size = (max_num_test_csrs < num_test_csrs) ? max_num_test_csrs : num_test_csrs; + end else begin + max_chunk_size = max_num_test_csrs; + end + end else begin + max_chunk_size = num_test_csrs; + end + + // Now divide the total number of CSRs by that bound. Rounding up gives enough chunks to be able + // to cover the whole list. + num_chunks = (num_csrs + max_chunk_size - 1) / max_chunk_size; + + // Given the number of chunks, we can now divide the number of CSRs by that to get the size of a + // chunk. Note that this will be at most max_chunk_size but may be much smaller. + // + // For example, if max_chunk_size = 50 and num_csrs = 51 then we will get 2 = ceil(51/50) chunks + // but then assign ceil(51/2) = 26 tests to each chunk, which gets "maximum parallelism" by + // avoiding dramatic differences between the size of chunks. + chunk_size = (num_csrs + num_chunks - 1) / num_chunks; + + // Pick a chunk index (less than num_chunks) at random + chunk_idx = $urandom_range(num_chunks - 1); + + // Finally, convert that into a pair of CSR indices (where end_idx is strictly past the end) + start_idx = chunk_idx * chunk_size; + end_idx = start_idx + chunk_size - 1; + end else begin + // If neither value was provided, we work on the entire list of CSRs at once. + start_idx = 0; + end_idx = num_csrs - 1; + end + + // At this point, start_idx and end_idx should have been chosen, with start_idx < end_idx. Convert + // the end index to an inclusive limit, by clipping to the number of CSRs. + end_idx = (end_idx >= num_csrs) ? num_csrs - 1 : end_idx; + + // At this point, we should have 0 <= start_idx <= end_idx < num_csrs. If that isn't true, there + // was a bug in the code above. + `DV_CHECK_FATAL(start_idx <= end_idx && end_idx < num_csrs) + + // Replace any existing list of CSRs with the chosen chunk in a random order. + test_csrs.delete(); + for (int i = start_idx; i <= end_idx; i++) begin + test_csrs.push_back(all_csrs[i]); + `uvm_info(`gtn, $sformatf("Testing CSR %0s, reset: 0x%0x.", all_csrs[i].get_full_name(), + all_csrs[i].get_mirrored_value()), UVM_HIGH) + end + `uvm_info(`gtn, + $sformatf("Testing %0d csrs [%0d - %0d] from supplied models.", + test_csrs.size(), start_idx, end_idx), + UVM_MEDIUM) + + test_csrs.shuffle(); +endfunction + +function bit csr_base_seq::is_excl(uvm_object obj, + csr_excl_type_e csr_excl_type, + csr_test_type_e csr_test_type); + csr_excl_item csr_excl = get_excl_item(obj); + if (csr_excl == null) begin + return 0; + end else begin + return csr_excl.is_excl(obj, csr_excl_type, csr_test_type); + end +endfunction + +function bit csr_base_seq::csr_excluded(uvm_reg csr); + return 1'b0; +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_hw_reset_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_hw_reset_seq.sv new file mode 100644 index 0000000..f91003b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_hw_reset_seq.sv @@ -0,0 +1,65 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// This sequence reads all CSRs and checks their values against the reset value provided in the RAL +// specification. Note that this does not sufficiently qualify as the CSR HW reset test. The 'full' +// CSR HW reset test is constructed externally by running csr_write_seq first, issuing reset and +// only then running this sequence. + +class csr_hw_reset_seq extends csr_base_seq; + `uvm_object_utils(csr_hw_reset_seq) + + extern function new (string name=""); + + // Read all CSRs, expecting their values to match their reset values in the register block. + extern task body(); + + // Read the given CSR if it is not excluded and check its value matches the expected reset value. + // If the register has an HDL path, use two reads, starting with a backdoor one. + extern local task test_one_csr(uvm_reg csr); + + // Return true if the CSR should be skipped by this sequence + extern protected function bit csr_excluded(uvm_reg csr); +endclass + +function csr_hw_reset_seq::new (string name=""); + super.new(name); +endfunction + +task csr_hw_reset_seq::body(); + foreach (test_csrs[i]) begin + test_one_csr(test_csrs[i]); + end +endtask + +task csr_hw_reset_seq::test_one_csr(uvm_reg csr); + uvm_reg_data_t compare_mask = get_mask_excl_fields(csr, CsrExclInitCheck, CsrHwResetTest); + + `uvm_info(`gtn, + $sformatf("Verifying reset value of register %0s", csr.get_full_name()), + UVM_MEDIUM) + + // Read CSR twice, one from backdoor (if path available), the other from frontdoor. + if (csr.has_hdl_path()) begin + // Reading from backdoor can ensure that we deposit value into the storage rather than just a + // net. If we mistakenly deposit to a net, reset can't clear it and this check will fail. + csr_rd_check(.ptr (csr), + .backdoor (1), + .compare (!external_checker), + .compare_vs_ral(1'b1), + .compare_mask (compare_mask)); + end + + // Read and check value via frontdoor. + csr_rd_check(.ptr (csr), + .backdoor (0), + .blocking (0), + .compare (!external_checker), + .compare_vs_ral(1'b1), + .compare_mask (compare_mask)); +endtask + +function bit csr_hw_reset_seq::csr_excluded(uvm_reg csr); + return is_excl(csr, CsrExclInitCheck, CsrHwResetTest); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_seq_lib.sv b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_seq_lib.sv new file mode 100644 index 0000000..0ba9fc8 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_seq_lib.sv @@ -0,0 +1,340 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// CSR suite of sequences that do writes and reads to CSRs +// includes hw_reset, rw, bit_bash and aliasing tests for CSRs, and mem_walk for uvm_mems +// The sequences perform csr writes and reads and follow the standard csr test suite. If external +// checker is enabled, then the external entity is required to update the mirrored value on +// writes. If not enabled, the sequences themselves call predict function to update the mirrored +// value. Consequently, the read values are checked against the mirrored value and not the +// previously written value. This approach is better since it takes care of special +// register and field access policies. Also, we use csr_rd_check task instead of csr_mirror to take +// field exclusions into account. +// +// Exclusions are to be provided using the csr_excl_item item (see class for more details). + +//-------------------------------------------------------------------------------------------------- +// Class: csr_write_seq +// Brief Description: This sequence writes a random value to all CSRs. It does not perform any +// checks. It is run as the first step of the CSR HW reset test. +//-------------------------------------------------------------------------------------------------- +class csr_write_seq extends csr_base_seq; + static bit test_backdoor_path_done; // only run once + bit en_rand_backdoor_write; + `uvm_object_utils(csr_write_seq) + + `uvm_object_new + + virtual task body(); + uvm_reg_data_t wdata; + + // check all hdl paths are valid + if (!test_backdoor_path_done) begin + foreach (models[i]) begin + bkdr_reg_path_e path_kind; + uvm_reg_mem_hdl_paths_seq hdl_check_seq; + + hdl_check_seq = uvm_reg_mem_hdl_paths_seq::type_id::create("hdl_check_seq"); + do begin + // Test the HDL paths for correctness if they exist. + if (models[i].has_hdl_path(path_kind.name)) begin + hdl_check_seq.abstractions.push_back(path_kind.name); + end + path_kind = path_kind.next; + end while (path_kind != path_kind.first); + hdl_check_seq.model = models[i]; + hdl_check_seq.start(null); + end + test_backdoor_path_done = 1; + end + + foreach (test_csrs[i]) begin + dv_base_reg dv_csr; + bit backdoor; + // check if parent block or register is excluded from write + if (is_excl(test_csrs[i], CsrExclWrite, CsrHwResetTest)) begin + `uvm_info(`gtn, $sformatf("Skipping register %0s due to CsrExclWrite exclusion", + test_csrs[i].get_full_name()), UVM_MEDIUM) + continue; + end + + `uvm_info(`gtn, $sformatf("Writing random data to register %0s", + test_csrs[i].get_full_name()), UVM_MEDIUM) + + `DV_CHECK_STD_RANDOMIZE_FATAL(wdata) + wdata = get_csr_wdata_with_write_excl(test_csrs[i], wdata, CsrHwResetTest); + + `downcast(dv_csr, test_csrs[i]) + if (en_rand_backdoor_write && test_csrs[i].has_hdl_path() && !dv_csr.get_is_ext_reg()) begin + `DV_CHECK_STD_RANDOMIZE_WITH_FATAL(backdoor, backdoor dist {0 :/ 7, 1 :/ 3};) + end + + if (backdoor) begin + string str_kinds[$]; + + test_csrs[i].get_hdl_path_kinds(str_kinds); + str_kinds.shuffle(); + + foreach (str_kinds[j]) begin + bkdr_reg_path_e enum_kind; + // Convert string name to an enum + `DV_CHECK_FATAL(uvm_enum_wrapper#(bkdr_reg_path_e)::from_name(str_kinds[j], enum_kind)) + + csr_poke(.ptr(test_csrs[i]), .value(wdata), .kind(enum_kind)); + + `DV_CHECK_STD_RANDOMIZE_FATAL(wdata) + wdata = get_csr_wdata_with_write_excl(test_csrs[i], wdata, CsrHwResetTest); + end + end else begin + csr_wr(.ptr(test_csrs[i]), .value(wdata), .blocking(0)); + end + end + endtask + +endclass + + +//-------------------------------------------------------------------------------------------------- +// Class: csr_rw_seq +// Brief Description: This seq writes a random value to a CSR and reads it back. The read value +// is checked for correctness while adhering to its access policies. A random choice is made between +// reading back the CSR as a whole or reading fields individually, so that partial accesses are made +// into the DUT as well. +//-------------------------------------------------------------------------------------------------- +class csr_rw_seq extends csr_base_seq; + `uvm_object_utils(csr_rw_seq) + + `uvm_object_new + + virtual task body(); + foreach (test_csrs[i]) begin + uvm_reg_data_t wdata; + uvm_reg_field test_fields[$]; + dv_base_reg test_dv_csr; + bit supports_byte_enable; + bit do_field_rd_check; + + // The test_csrs list may be jumbled from different RAL models. Hence, we find at runtime, if + // the interface supports byte_accesses. + begin + uvm_reg_map map = test_csrs[i].get_default_map(); + uvm_reg_adapter adapter = map.get_adapter(); + if (adapter != null) begin + supports_byte_enable = adapter.supports_byte_enable; + end + end + + // check if parent block or register is excluded from write + if (is_excl(test_csrs[i], CsrExclWrite, CsrRwTest)) begin + `uvm_info(`gtn, $sformatf("Skipping register %0s due to CsrExclWrite exclusion", + test_csrs[i].get_full_name()), UVM_MEDIUM) + continue; + end + + `uvm_info(`gtn, $sformatf("Verifying register read/write for %0s", + test_csrs[i].get_full_name()), UVM_MEDIUM) + + `DV_CHECK_STD_RANDOMIZE_FATAL(wdata) + wdata = get_csr_wdata_with_write_excl(test_csrs[i], wdata, CsrRwTest); + + // if external checker is not enabled and writes are made non-blocking, then we need to + // pre-predict so that the mirrored value will be updated. if we dont, then csr_rd_check task + // might pick up stale mirrored value + // the pre-predict also needs to happen after the register is being written, to make sure the + // register is getting the updated access information. + csr_wr(.ptr(test_csrs[i]), .value(wdata), .blocking(0), .predict(!external_checker)); + + // Shadow register requires two writes with the same value to write registers into DUT. + // In `csr_wr` task, the `predict` task is triggered after two shadow writes are done. + // To avoid non-blocking access where shadow register read might be triggered between two + // consecutive shadow register write, we will wait until all outstanding accesses finish, + // then issue a shadow register read. + `downcast(test_dv_csr, test_csrs[i]) + if (test_dv_csr.get_is_shadowed) wait_no_outstanding_access(); + + `DV_CHECK_STD_RANDOMIZE_WITH_FATAL(do_field_rd_check, + !supports_byte_enable -> !do_field_rd_check;) + do_check_csr_or_field_rd(.csr(test_csrs[i]), + .blocking(0), + .compare(!external_checker), + .compare_vs_ral(1), + .do_csr_field_rd_check(do_field_rd_check), + .csr_excl_type(CsrExclWriteCheck), + .csr_test_type(CsrRwTest)); + + wait_if_max_outstanding_accesses_reached(); + end + endtask + +endclass + +//-------------------------------------------------------------------------------------------------- +// Class: csr_bit_bash_seq +// Brief Description: This sequence walks a 1 through each CSR by writing one bit at a time and +// reading the CSR back. The read value is checked for correctness while adhering to its access +// policies. This verifies that there is no aliasing within the fields / bits of a CSR. +//-------------------------------------------------------------------------------------------------- +class csr_bit_bash_seq extends csr_base_seq; + `uvm_object_utils(csr_bit_bash_seq) + + `uvm_object_new + + virtual task body(); + int unsigned total_count = test_csrs.size(); + int unsigned done_count = 0; + + `uvm_info(`gtn, + $sformatf("Running bit bash sequence for %0d registers", total_count), + UVM_MEDIUM) + foreach (test_csrs[i]) begin + done_count++; + `uvm_info(`gtn, + $sformatf("Verifying register bit bash for %0s (register %0d/%0d)", + test_csrs[i].get_full_name(), done_count, total_count), + UVM_MEDIUM) + + // check if parent block or register is excluded from write + if (is_excl(test_csrs[i], CsrExclWrite, CsrBitBashTest) || + is_excl(test_csrs[i], CsrExclWriteCheck, CsrBitBashTest)) begin + `uvm_info(`gtn, $sformatf("Skipping register %0s due to CsrExclWrite/WriteCheck exclusion", + test_csrs[i].get_full_name()), UVM_MEDIUM) + continue; + end + + bash_register(test_csrs[i]); + end + + endtask + + // Run bit bash test on the given register. + // + // The basic idea is that we test each bit of the register with the bash_kth_bit task, checking + // that we can set and clear the register as expected. This task takes field exclusions and + // read/write masks into account when calculating how to run the bash_kth_bit task across the + // register. + virtual task bash_register(uvm_reg csr); + uvm_reg_field fields[$]; + string mode[`UVM_REG_DATA_WIDTH]; + uvm_reg_data_t dc_mask; // dont write or read + uvm_reg_data_t no_cmp_mask; // read but dont compare + int n_bits; + string field_access; + int next_lsb; + + n_bits = csr.get_n_bytes() * 8; + + // Let's see what kind of bits we have... + csr.get_fields(fields); + + next_lsb = 0; + dc_mask = 0; + no_cmp_mask = 0; + + foreach (fields[j]) begin + int lsb, w, dc, no_cmp; + + field_access = fields[j].get_access(csr.get_default_map()); + no_cmp = (fields[j].get_compare() == UVM_NO_CHECK); + lsb = fields[j].get_lsb_pos(); + w = fields[j].get_n_bits(); + + // Exclude write-only fields from compare because you are not supposed to read them + case (field_access) + "WO", "WOC", "WOS", "WO1", "NOACCESS", "": no_cmp = 1; + default: no_cmp = 0; + endcase + + // skip fields that are wr-excluded + if (is_excl(fields[j], CsrExclWrite, CsrBitBashTest)) begin + `uvm_info(`gtn, $sformatf("Skipping field %0s due to CsrExclWrite exclusion", + fields[j].get_full_name()), UVM_MEDIUM) + dc = 1; + end + + // ignore fields that are init or rd-excluded + no_cmp = is_excl(fields[j], CsrExclInitCheck, CsrBitBashTest) || + is_excl(fields[j], CsrExclWriteCheck, CsrBitBashTest) ; + + // Any unused bits below the LSB of this field? + while (next_lsb < lsb) mode[next_lsb++] = "RO"; + + repeat (w) begin + mode[next_lsb] = field_access; + dc_mask[next_lsb] = dc; + no_cmp_mask[next_lsb] = no_cmp; + next_lsb++; + end + end + + // Any unused bits above the top field, but that we will still look at with bash_kth_bit? + while (next_lsb < n_bits) begin + mode[next_lsb++] = "RO"; + end + + // Bash the kth bit + for (int k = 0; k < n_bits; k++) begin + // Cannot test unpredictable bit behavior + if (dc_mask[k]) continue; + bash_kth_bit(csr, k, mode[k], no_cmp_mask); + end + endtask + + // A bit bashing sequence for bit k of register rg. + // + // This works by writing the bit as one value and reading it back, then writing the other value + // and reading that back, checking that each write sets the value as expected. + // + // The mask argument gives bits that won't be compared when reading the value back. Note that this + // task is still worth running even if the k'th bit of mask is set: it might be that writes to + // that bit of the register mess up other bits/fields in the register, and this task will spot if + // that happens. + task bash_kth_bit(uvm_reg rg, + int k, + string mode, + uvm_reg_data_t mask); + + uvm_reg_data_t val; + string err_msg; + + `uvm_info(`gtn, $sformatf("bashing %0s bit #%0d", mode, k), UVM_HIGH) + repeat (2) begin + val = rg.get(); + val[k] = ~val[k]; + err_msg = $sformatf("Wrote %0s[%0d]: %0b", rg.get_full_name(), k, val[k]); + csr_wr(.ptr(rg), .value(val), .blocking(1), .predict(!external_checker)); + + // uvm_reg waits until transaction is completed, before start another read/write in same reg + csr_rd_check(.ptr (rg), + .blocking (0), + .compare (!external_checker), + .compare_vs_ral(1'b1), + .compare_mask (~mask), + .err_msg (err_msg)); + end + endtask: bash_kth_bit + +endclass + +//-------------------------------------------------------------------------------------------------- +// Class: csr_mem_walk_seq +// Brief Description: This seq walks through each address of the memory by running the default +// UVM mem walk sequence. +//-------------------------------------------------------------------------------------------------- +class csr_mem_walk_seq extends csr_base_seq; + uvm_mem_walk_seq mem_walk_seq; + + `uvm_object_utils(csr_mem_walk_seq) + + `uvm_object_new + + virtual task body(); + mem_walk_seq = uvm_mem_walk_seq::type_id::create("mem_walk_seq"); + foreach (models[i]) begin + `uvm_info(`gfn, $sformatf("Testing model %0s", models[i].get_full_name()), UVM_LOW) + mem_walk_seq.model = models[i]; + mem_walk_seq.start(null); + end + endtask : body + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils.core b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils.core new file mode 100644 index 0000000..bbe14c8 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils.core @@ -0,0 +1,24 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:csr_utils" +description: "CSR utilities" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_utils + - lowrisc:dv:dv_base_reg + files: + - csr_utils_pkg.sv + - csr_base_seq.sv: {is_include_file: true} + - csr_hw_reset_seq.sv: {is_include_file: true} + - csr_aliasing_seq.sv: {is_include_file: true} + - csr_seq_lib.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv new file mode 100644 index 0000000..1e1b4f2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv @@ -0,0 +1,868 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package csr_utils_pkg; + // dep packages + import uvm_pkg::*; + import dv_utils_pkg::*; + import dv_base_reg_pkg::*; + export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + // local types and variables + uint outstanding_accesses = 0; + uint default_timeout_ns = 2_000_000; // 2ms + uint default_spinwait_timeout_ns = 10_000_000; // 10ms + bit default_csr_blocking = 1; + uvm_check_e default_csr_check = UVM_CHECK; + bit under_reset = 0; + int max_outstanding_accesses = 100; + uvm_reg_frontdoor default_user_frontdoor = null; + + function automatic void increment_outstanding_access(); + outstanding_accesses++; + `uvm_info($sformatf("%m"), $sformatf("%0d", outstanding_accesses), UVM_HIGH) + endfunction + + function automatic void decrement_outstanding_access(); + outstanding_accesses--; + `uvm_info($sformatf("%m"), $sformatf("%0d", outstanding_accesses), UVM_HIGH) + endfunction + + task automatic wait_no_outstanding_access(); + wait(outstanding_accesses == 0); + endtask + + function automatic void clear_outstanding_access(); + outstanding_accesses = 0; + endfunction + + function automatic bit has_outstanding_access(); + return outstanding_accesses > 0; + endfunction + + // timeout may happen if we issue too many non-blocking accesses at once + // limit the nonblocking items to be up to max outstanding + task automatic wait_if_max_outstanding_accesses_reached(int max = max_outstanding_accesses); + wait(outstanding_accesses <= max); + endtask + + function automatic void reset_asserted(); + under_reset = 1; + endfunction + + function automatic void reset_deasserted(); + under_reset = 0; + endfunction + + // get mem object from address + function automatic uvm_mem get_mem_by_addr(uvm_reg_block ral, uvm_reg_addr_t addr); + uvm_mem mem; + addr[1:0] = 0; + mem = ral.default_map.get_mem_by_offset(addr); + + if (mem == null) begin + `uvm_fatal($sformatf("%m"), + $sformatf("Cannot find a memory at offset 0x%0h in reg_block '%0s'.", + addr, ral.get_name())) + end + + return mem; + endfunction + + // get mem access like RW, RO + function automatic string get_mem_access_by_addr(uvm_reg_block ral, uvm_reg_addr_t addr); + uvm_mem mem = get_mem_by_addr(ral, addr); + return mem.get_access(); + endfunction + + // This function return mirrored value of reg/field of given RAL + function automatic uvm_reg_data_t get_reg_fld_mirror_value(uvm_reg_block ral, + string reg_name, + string field_name = ""); + uvm_reg csr; + uvm_reg_field fld; + uvm_reg_data_t result; + csr = ral.get_reg_by_name(reg_name); + `DV_CHECK_NE_FATAL(csr, null, "", $sformatf("%m")) + // return field mirror value if field_name is passed, else return reg mirror value + if (field_name != "") begin + fld = csr.get_field_by_name(field_name); + `DV_CHECK_NE_FATAL(fld, null, "", $sformatf("%m")) + result = fld.get_mirrored_value(); + end + else begin + result = csr.get_mirrored_value(); + end + return result; + endfunction : get_reg_fld_mirror_value + + // get updated reg value by using new specific field value + function automatic uvm_reg_data_t get_csr_val_with_updated_field(uvm_reg_field field, + uvm_reg_data_t csr_value, + uvm_reg_data_t field_value); + uvm_reg_data_t mask = (1 << field.get_n_bits()) - 1; + uint shift = field.get_lsb_pos(); + csr_value = csr_value & ~(mask << shift) | ((mask & field_value) << shift); + return csr_value; + endfunction + + // wait until current csr op is complete + task automatic csr_wait(input uvm_reg csr); + `uvm_info($sformatf("%m"), $sformatf("%0s: wait_busy: %0b", + csr.get_full_name(), csr.m_is_busy), UVM_HIGH) + wait(csr.m_is_busy == 1'b0); + `uvm_info($sformatf("%m"), $sformatf("%0s: done wait_busy: %0b", + csr.get_full_name(), csr.m_is_busy), UVM_HIGH) + endtask + + // Use `csr_wr` to construct `csr_update` to avoid replicated codes to handle nonblocking, + // shadow writes etc + task automatic csr_update(input uvm_reg csr, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input bit blocking = default_csr_blocking, + input uint timeout_ns = default_timeout_ns, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor, + input bit en_shadow_wr = 1); + uvm_reg_field fields[$]; + uvm_reg_data_t value; + + // below is partial replication of the uvm_reg_field::update() logic in UVM1.2 source code + if (!csr.needs_update()) return; + csr.get_fields(fields); + // Concatenate the write-to-update values from each field + // Fields are stored in LSB or MSB order + value = 0; + foreach (fields[i]) begin + value |= fields[i].XupdateX() << fields[i].get_lsb_pos(); + end + + csr_wr(.ptr(csr), .value(value), .check(check), .path(path), .blocking(blocking), .backdoor(0), + .timeout_ns(timeout_ns), .predict(0), .map(map), .user_ftdr(user_ftdr), + .en_shadow_wr(en_shadow_wr)); + endtask + + task automatic csr_wr(input uvm_object ptr, + input uvm_reg_data_t value, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input bit blocking = default_csr_blocking, + input bit backdoor = 0, + input uint timeout_ns = default_timeout_ns, + input bit predict = 0, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor, + input bit en_shadow_wr = 1); + if (backdoor) begin + csr_poke(ptr, value, check, predict); + end else begin + csr_field_t csr_or_fld = decode_csr_or_field(ptr); + + // if it's a field write, still do full CSR write and use mirrored value for the other fields + if (csr_or_fld.field != null) begin + // get full CSR value + value = get_csr_val_with_updated_field(csr_or_fld.field, `gmv(csr_or_fld.csr), value); + end + + if (blocking) begin + csr_wr_sub(csr_or_fld.csr, value, check, path, timeout_ns, predict, map, user_ftdr, + en_shadow_wr); + end else begin + fork + begin + csr_wr_sub(csr_or_fld.csr, value, check, path, timeout_ns, predict, map, user_ftdr, + en_shadow_wr); + end + join_none + // Add #0 to ensure that this thread starts executing before any subsequent call + #0; + end + end + endtask + + // subroutine of csr_wr, don't use it directly + task automatic csr_wr_sub(input uvm_reg csr, + input uvm_reg_data_t value, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uint timeout_ns = default_timeout_ns, + input bit predict = 0, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor, + input bit en_shadow_wr = 1); + fork + begin : isolation_fork + fork + begin + dv_base_reg dv_reg; + `downcast(dv_reg, csr, "", fatal, $sformatf("%m")) + + increment_outstanding_access(); + csr_pre_write_sub(csr, en_shadow_wr); + + csr_wr_and_predict_sub(.csr(csr), .value(value), .check(check), .path(path), + .predict(predict), .map(map), .user_ftdr(user_ftdr)); + if (en_shadow_wr && dv_reg.get_is_shadowed()) begin + csr_wr_and_predict_sub(.csr(csr), .value(value), .check(check), .path(path), + .predict(predict), .map(map), .user_ftdr(user_ftdr)); + end + + csr_post_write_sub(csr, en_shadow_wr); + decrement_outstanding_access(); + end + begin + `DV_WAIT_TIMEOUT(timeout_ns, $sformatf("%m"), + $sformatf("Timeout waiting to csr_wr %0s (addr=0x%0h)", + csr.get_full_name(), csr.get_address())) + end + join_any + disable fork; + end : isolation_fork + join + endtask + + // internal task, don't use it directly + task automatic csr_wr_and_predict_sub(uvm_reg csr, + uvm_reg_data_t value, + uvm_check_e check, + uvm_path_e path, + bit predict, + uvm_reg_map map, + uvm_reg_frontdoor user_ftdr); + uvm_status_e status; + + if (user_ftdr != null) csr.set_frontdoor(user_ftdr); + csr.write(.status(status), .value(value), .path(path), .map(map), .prior(100)); + // TODO: need to remove the frontdoor to switch back to the default, + // but this doesn't work: if (user_ftdr != null) ptr.set_frontdoor(null); + + if (under_reset) return; + if (check == UVM_CHECK) begin + `DV_CHECK_EQ(status, UVM_IS_OK, + $sformatf("trying to write csr %0s", csr.get_full_name()), + error, $sformatf("%m")) + end + // Only update the predicted value if status is ok (otherwise the write isn't completed + // successfully and the design shouldn't have accepted the written value) + if (status == UVM_IS_OK && predict) begin + void'(csr.predict(.value(value), .kind(UVM_PREDICT_WRITE))); + end + endtask + + task automatic csr_pre_write_sub(uvm_reg csr, bit en_shadow_wr); + dv_base_reg dv_reg; + `downcast(dv_reg, csr, "", fatal, $sformatf("%m")) + if (dv_reg.get_is_shadowed() && en_shadow_wr) begin + dv_reg.atomic_en_shadow_wr.get(1); + end + endtask + + task automatic csr_post_write_sub(uvm_reg csr, bit en_shadow_wr); + dv_base_reg dv_reg; + `downcast(dv_reg, csr, "", fatal, $sformatf("%m")) + if (dv_reg.get_is_shadowed() && en_shadow_wr) begin + dv_reg.atomic_en_shadow_wr.put(1); + end + endtask + + // backdoor write csr + task automatic csr_poke(input uvm_object ptr, + input uvm_reg_data_t value, + input uvm_check_e check = default_csr_check, + input bit predict = 0, + input bkdr_reg_path_e kind = BkdrRegPathRtl); + csr_field_t csr_or_fld = decode_csr_or_field(ptr); + uvm_status_e status; + uvm_reg_data_t old_mirrored_val; + + if (csr_or_fld.field != null) begin + old_mirrored_val = csr_or_fld.field.get_mirrored_value(); + csr_or_fld.field.poke(.status(status), .value(value), .kind(kind.name)); + end else begin + old_mirrored_val = csr_or_fld.csr.get_mirrored_value(); + csr_or_fld.csr.poke(.status(status), .value(value), .kind(kind.name)); + end + if (check == UVM_CHECK && status != UVM_IS_OK) begin + string str; + uvm_hdl_path_concat paths[$]; + csr_or_fld.csr.get_full_hdl_path(paths, kind.name); + foreach (paths[0].slices[i]) str = $sformatf("%0s\n%0s", str, paths[0].slices[i].path); + `uvm_fatal($sformatf("%m"), $sformatf("poke failed for %0s, check below paths %0s", + ptr.get_full_name(), str)) + end + // poke always updates predict value, if predict == 0, revert back to old mirrored value + if (!predict || kind == BkdrRegPathRtlShadow) begin + if (csr_or_fld.field != null) begin + void'(csr_or_fld.field.predict(.value(old_mirrored_val), .kind(UVM_PREDICT_DIRECT), + .path(UVM_BACKDOOR))); + end else begin + void'(csr_or_fld.csr.predict(.value(old_mirrored_val), .kind(UVM_PREDICT_DIRECT), + .path(UVM_BACKDOOR))); + end + end + endtask + + task automatic csr_rd(input uvm_object ptr, // accept reg or field + output uvm_reg_data_t value, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input bit blocking = default_csr_blocking, + input bit backdoor = 0, + input uint timeout_ns = default_timeout_ns, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + uvm_status_e status; + if (blocking) begin + csr_rd_sub(.ptr(ptr), .value(value), .status(status), .check(check), .path(path), + .backdoor(backdoor), .timeout_ns(timeout_ns), .map(map), .user_ftdr(user_ftdr)); + end else begin + if (backdoor) `uvm_error($sformatf("%m"), "Non-blocking backdoor access doesn't make sense.") + fork + csr_rd_sub(.ptr(ptr), .value(value), .status(status), .check(check), .path(path), + .backdoor(backdoor), .timeout_ns(timeout_ns), .map(map), .user_ftdr(user_ftdr)); + join_none + // Add #0 to ensure that this thread starts executing before any subsequent call + #0; + end + endtask + + // subroutine of csr_rd, don't use it directly + task automatic csr_rd_sub(input uvm_object ptr, // accept reg or field + output uvm_reg_data_t value, + output uvm_status_e status, + input bit backdoor = 0, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uint timeout_ns = default_timeout_ns, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + if (backdoor) begin + value = csr_peek(ptr, check); + status = UVM_IS_OK; + return; + end + fork + begin : isolation_fork + csr_field_t csr_or_fld; + fork + begin + increment_outstanding_access(); + csr_or_fld = decode_csr_or_field(ptr); + if (user_ftdr != null) csr_or_fld.csr.set_frontdoor(user_ftdr); + if (csr_or_fld.field != null) begin + csr_or_fld.field.read(.status(status), .value(value), .path(path), .map(map), + .prior(100)); + end else begin + csr_or_fld.csr.read(.status(status), .value(value), .path(path), .map(map), + .prior(100)); + end + // TODO: need to remove the frontdoor to switch back to the default, + // but this doesn't work: if (user_ftdr != null) ptr.set_frontdoor(null); + if (check == UVM_CHECK && !under_reset) begin + `DV_CHECK_EQ(status, UVM_IS_OK, + $sformatf("trying to read csr/field %0s", ptr.get_full_name()), + error, $sformatf("%m")) + end + decrement_outstanding_access(); + end + begin + `DV_WAIT_TIMEOUT(timeout_ns, $sformatf("%m"), + $sformatf("Timeout waiting to csr_rd %0s (addr=0x%0h)", + ptr.get_full_name(), csr_or_fld.csr.get_address())) + end + join_any + disable fork; + end : isolation_fork + join + endtask + + // backdoor read csr + // uvm_reg::peek() returns a 2-state value, directly get data from hdl path + function automatic uvm_reg_data_t csr_peek(uvm_object ptr, + uvm_check_e check = default_csr_check, + bkdr_reg_path_e kind = BkdrRegPathRtl); + csr_field_t csr_or_fld = decode_csr_or_field(ptr); + uvm_reg csr = csr_or_fld.csr; + uvm_reg_data_t value = 0; + + uvm_hdl_path_concat paths[$]; + csr.get_full_hdl_path(paths, kind.name); + + `DV_CHECK_FATAL(paths.size() > 0, + $sformatf("No backdoor defined for %0s path's %0s", + csr.get_full_name(), kind.name), + $sformatf("%m")) + + foreach (paths[0].slices[i]) begin + uvm_reg_data_t field_val; + `DV_CHECK_FATAL(uvm_hdl_read(paths[0].slices[i].path, field_val), + $sformatf("Failed to read %s, slice %d, at path %s", + csr.get_full_name(), i, paths[0].slices[i].path), + $sformatf("%m")) + if (check == UVM_CHECK) `DV_CHECK_EQ($isunknown(field_val), 0, "", error, $sformatf("%m")) + + value |= field_val << paths[0].slices[i].offset; + end + + // We now have the contents of the field or register in value. If ptr was a sub-field of some + // register, it will be laid out in the same way as the field is laid out in the register. + // That's no problem: we can just extract the relevant field from the laid-out value here. + if (csr_or_fld.field != null) value = get_field_val(csr_or_fld.field, value); + + return value; + endfunction + + task automatic csr_rd_check(input uvm_object ptr, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input bit blocking = default_csr_blocking, + input bit backdoor = 0, + input uint timeout_ns = default_timeout_ns, + input bit compare = 1'b1, + input bit compare_vs_ral = 1'b0, + input uvm_reg_data_t compare_mask = '1, + input uvm_reg_data_t compare_value = 0, + input string err_msg = "", + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + fork + begin : isolation_fork + fork + begin + csr_field_t csr_or_fld; + uvm_status_e status; + uvm_reg_data_t obs; + uvm_reg_data_t exp; + uvm_reg_data_t reset_val; + + csr_or_fld = decode_csr_or_field(ptr); + + csr_rd_sub(.ptr(ptr), .value(obs), .status(status), .check(check), .path(path), + .backdoor(backdoor), .timeout_ns(timeout_ns), .map(map), + .user_ftdr(user_ftdr)); + + // get mirrored value after read to make sure the read reg access is updated + if (csr_or_fld.field != null) begin + exp = csr_or_fld.field.get_mirrored_value(); + reset_val = csr_or_fld.field.get_reset(); + end else begin + exp = csr_or_fld.csr.get_mirrored_value(); + reset_val = csr_or_fld.csr.get_reset(); + end + if (compare && status == UVM_IS_OK && !under_reset) begin + obs = obs & compare_mask; + exp = (compare_vs_ral ? exp : compare_value) & compare_mask; + `DV_CHECK_EQ(obs, exp, $sformatf("Regname: %0s reset value: 0x%0h %0s", + ptr.get_full_name(), reset_val, err_msg), + error, $sformatf("%m")) + end + end + join_none + if (blocking) wait fork; + // Add #0 to ensure that this thread starts executing before any subsequent call + else #0; + end : isolation_fork + join + endtask + + // task to read all csrs and check against ral expected value. Mainly used after reset + task automatic read_and_check_all_csrs(input uvm_reg_block ral); + uvm_reg ral_csrs[$]; + ral.get_registers(ral_csrs); + ral_csrs.shuffle(); + + foreach (ral_csrs[i]) csr_rd_check(.ptr(ral_csrs[i]), .compare_vs_ral(1)); + endtask + + // Checks the csr value against predicted value by reading the whole CSR or individual CSR + // fields. + // This task will skip read check if the CSR field is excluded. + task automatic do_check_csr_or_field_rd(input uvm_reg csr, + input bit do_csr_field_rd_check = $urandom(), + input bit blocking = 0, + input bit compare = 1, + input bit compare_vs_ral = 1, + input csr_excl_type_e csr_excl_type = CsrNoExcl, + input csr_test_type_e csr_test_type = CsrRwTest, + input csr_excl_item csr_excl_item = get_excl_item(csr)); + uvm_reg_data_t compare_mask; + + // Check if parent block or register is excluded from read-check + if (csr_excl_item != null && csr_excl_item.is_excl(csr, csr_excl_type, csr_test_type)) begin + `uvm_info($sformatf("%m"), + $sformatf("Skipping register %0s due to CsrExclWriteCheck exclusion", + csr.get_full_name()), UVM_MEDIUM) + return; + end + + compare_mask = get_mask_excl_fields(csr, csr_excl_type, csr_test_type, csr_excl_item); + + if (!do_csr_field_rd_check) begin + csr_rd_check(.ptr (csr), + .blocking (blocking), + .compare (compare), + .compare_vs_ral(compare_vs_ral), + .compare_mask (compare_mask)); + end else begin + uvm_reg_field test_fields[$]; + csr.get_fields(test_fields); + test_fields.shuffle(); + foreach (test_fields[i]) begin + bit field_compare = 1; + if (csr_excl_item != null) begin + field_compare = !csr_excl_item.is_excl(test_fields[i], csr_excl_type, csr_test_type); + end + csr_rd_check(.ptr (test_fields[i]), + .blocking (blocking), + .compare (field_compare && compare), + .compare_vs_ral(compare_vs_ral)); + end + end + endtask + + // Poll a csr or csr field continuously until its value is as expected. + // + // The CSR or field is polled by performing reads at the given ptr and its current value is + // compared with exp_data using the comparison in compare_op. The task exits when the comparison + // becomes true. + // + // To avoid this task waiting forever, there is an upper bound given with timeout_ns. If the task + // does not finish for another reason in that time, the test will fail. + // + // CSR reads are performed using frontdoor access. If the backdoor argument is true, then they + // will be performed with a backdoor access instead. + // + // Successive CSR reads are back-to-back unless spinwait_delay_ns is positive. If backdoor is + // true, the delay between successive reads is made to be at least 1ns. + task automatic csr_spinwait(input uvm_object ptr, + input uvm_reg_data_t exp_data, + input uvm_check_e check = default_csr_check, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor, + input uint spinwait_delay_ns = 0, + input uint timeout_ns = default_spinwait_timeout_ns, + input compare_op_e compare_op = CompareOpEq, + input bit backdoor = 0, + input uvm_verbosity verbosity = UVM_HIGH); + static int count; + automatic int lcount; + + // Increment count so that each call to csr_spinwait has a different index (to help debugging) + count++; + + // Take an (automatic) copy of lcount. This will act as a snapshot of the value that the count + // had when this task started, giving the index of *this* call. + lcount = count; + + `uvm_info($sformatf("%m"), $sformatf( + "- (call_count=%0d, backdoor=%0d, exp_data=%0d, ptr=%s)", + lcount, backdoor, exp_data, ptr.get_name()), verbosity) + fork + begin : isolation_fork + csr_field_t csr_or_fld; + uvm_reg_data_t read_data; + + csr_or_fld = decode_csr_or_field(ptr); + if (backdoor && spinwait_delay_ns == 0) spinwait_delay_ns = 1; + fork + // Repeatedly do reads of the value at path and stop when the value satisfies the supplied + // comparison. If it is positive, wait spinwait_delay_ns nanoseconds between reads. If we + // enter reset, stop immediately (once the current csr_rd call has finished). + forever begin + `uvm_info($sformatf("%m"), $sformatf("In csr_spinwait - call_count = %0d", lcount), + verbosity) + + // Wait spinwait_delay_ns nanoseconds between each read (and before the first one), but + // stop waiting immediately if we see a reset. Note that we can't wait for a reset in + // parallel with the csr_rd below, because we use disable fork when a process finishes + // and csr_rd has internal state that it must clean up without being killed. + if (spinwait_delay_ns) begin + fork begin : iso_fork + fork + #(spinwait_delay_ns * 1ns); + wait (under_reset); + join_any + disable fork; + end : iso_fork join + end + + // If we are in reset, stop the wait immediately. + if (under_reset) break; + + csr_rd(.ptr(ptr), .value(read_data), .check(check), .path(path), + .blocking(1), .map(map), .user_ftdr(user_ftdr), .backdoor(backdoor)); + `uvm_info($sformatf("%m"), + $sformatf("ptr %0s == 0x%0h", ptr.get_full_name(), read_data), verbosity) + case (compare_op) + CompareOpEq: if (read_data == exp_data) break; + CompareOpCaseEq: if (read_data === exp_data) break; + CompareOpNe: if (read_data != exp_data) break; + CompareOpCaseNe: if (read_data !== exp_data) break; + CompareOpGt: if (read_data > exp_data) break; + CompareOpGe: if (read_data >= exp_data) break; + CompareOpLt: if (read_data < exp_data) break; + CompareOpLe: if (read_data <= exp_data) break; + default: begin + `uvm_fatal(ptr.get_full_name(), $sformatf("invalid operator:%0s", compare_op)) + end + endcase + end + // Wait for timeout_ns nanoseconds and then fail with an error (because this process + // should have been killed before then) + `DV_WAIT_TIMEOUT(timeout_ns, $sformatf("%m"), + $sformatf({"timeout %0s (addr=0x%0h, Comparison=%s, ", + "exp_data=0x%0h, call_count=%0d)"}, + ptr.get_full_name(), csr_or_fld.csr.get_address(), + compare_op.name, exp_data, lcount)) + join_any + disable fork; + end : isolation_fork + join + endtask + + task automatic mem_rd(input uvm_mem ptr, + input int offset, + output bit[31:0] data, + input uvm_check_e check = default_csr_check, + input bit blocking = default_csr_blocking, + input uint timeout_ns = default_timeout_ns, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + if (blocking) begin + mem_rd_sub(ptr, offset, data, check, timeout_ns, map, user_ftdr); + end else begin + fork + mem_rd_sub(ptr, offset, data, check, timeout_ns, map, user_ftdr); + join_none + // Add #0 to ensure that this thread starts executing before any subsequent call + #0; + end + endtask : mem_rd + + task automatic mem_rd_sub(input uvm_mem ptr, + input int offset, + output bit[31:0] data, + input uvm_check_e check = default_csr_check, + input uint timeout_ns = default_timeout_ns, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + fork + begin : isolating_fork + uvm_status_e status; + + fork + begin + increment_outstanding_access(); + if (user_ftdr != null) ptr.set_frontdoor(user_ftdr); + ptr.read(.status(status), .offset(offset), .value(data), .map(map), .prior(100)); + // TODO: need to remove the frontdoor to switch back to the default, + // but this doesn't work: if (user_ftdr != null) ptr.set_frontdoor(null); + if (check == UVM_CHECK && !under_reset) begin + `DV_CHECK_EQ(status, UVM_IS_OK, + $sformatf("trying to read mem %0s", ptr.get_full_name()), + error, $sformatf("%m")) + end + decrement_outstanding_access(); + end + begin : mem_rd_timeout + `DV_WAIT_TIMEOUT(timeout_ns, $sformatf("%m"), + $sformatf("Timeout waiting to mem_rd %0s (addr=0x%0h)", + ptr.get_full_name(), offset)) + end + join_any + disable fork; + end : isolating_fork + join + endtask : mem_rd_sub + + task automatic mem_wr(input uvm_mem ptr, + input int offset, + input bit[31:0] data, + input bit blocking = default_csr_blocking, + input uint timeout_ns = default_timeout_ns, + input uvm_check_e check = default_csr_check, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + if (blocking) begin + mem_wr_sub(ptr, offset, data, timeout_ns, check, map, user_ftdr); + end else begin + fork + mem_wr_sub(ptr, offset, data, timeout_ns, check, map, user_ftdr); + join_none + // Add #0 to ensure that this thread starts executing before any subsequent call + #0; + end + endtask : mem_wr + + task automatic mem_wr_sub(input uvm_mem ptr, + input int offset, + input bit[31:0] data, + input uint timeout_ns = default_timeout_ns, + input uvm_check_e check = default_csr_check, + input uvm_reg_map map = null, + input uvm_reg_frontdoor user_ftdr = default_user_frontdoor); + fork + begin : isolation_fork + uvm_status_e status; + + fork + begin + increment_outstanding_access(); + if (user_ftdr != null) ptr.set_frontdoor(user_ftdr); + ptr.write(.status(status), .offset(offset), .value(data), .map(map), .prior(100)); + // TODO: need to remove the frontdoor to switch back to the default, + // but this doesn't work: if (user_ftdr != null) ptr.set_frontdoor(null); + if (check == UVM_CHECK && !under_reset) begin + `DV_CHECK_EQ(status, UVM_IS_OK, + $sformatf("trying to write mem %0s", ptr.get_full_name()), + error, $sformatf("%m")) + end + decrement_outstanding_access(); + end + begin + `DV_WAIT_TIMEOUT(timeout_ns, $sformatf("%m"), + $sformatf("Timeout waiting to mem_wr %0s (addr=0x%0h)", + ptr.get_full_name(), offset)) + end + join_any + disable fork; + end : isolation_fork + join + endtask : mem_wr_sub + + // Fields could be excluded from writes & reads - This function zeros out the excluded fields + function automatic uvm_reg_data_t get_mask_excl_fields(uvm_reg csr, + csr_excl_type_e csr_excl_type, + csr_test_type_e csr_test_type, + csr_excl_item m_csr_excl_item = + get_excl_item(csr)); + uvm_reg_field flds[$]; + csr.get_fields(flds); + get_mask_excl_fields = '1; + + if (m_csr_excl_item != null) begin + foreach (flds[i]) begin + if (m_csr_excl_item.is_excl(flds[i], csr_excl_type, csr_test_type)) begin + csr_field_t fld_params = decode_csr_or_field(flds[i]); + `uvm_info($sformatf("%m"), $sformatf("Skipping field %0s due to %0s exclusion", + flds[i].get_full_name(), csr_excl_type.name()), UVM_HIGH) + get_mask_excl_fields &= ~(fld_params.mask << fld_params.shift); + end + end + end + endfunction + + // Returns the write data value masked with excluded fields. + // + // Some fields in the CSR may be excluded from writes. In that case, we need to revert those + // fields to their mirrored values and write the rest of the fields with the given value. + function automatic uvm_reg_data_t get_csr_wdata_with_write_excl( + uvm_reg csr, + uvm_reg_data_t wdata, + csr_test_type_e csr_test_type, + csr_excl_item m_csr_excl_item = get_excl_item(csr) + ); + uvm_reg_field flds[$]; + csr.get_fields(flds); + + foreach (flds[i]) begin + if (m_csr_excl_item.is_excl(flds[i], CsrExclWrite, csr_test_type)) begin + `uvm_info($sformatf("%m"), + $sformatf("Retain mirrored 0x%0h for field %0s due to CsrExclWrite exclusion", + `gmv(flds[i]), flds[i].get_full_name()), UVM_MEDIUM) + wdata = get_csr_val_with_updated_field(flds[i], wdata, `gmv(flds[i])); + end + end + return wdata; + endfunction + + // Returns the CSR exclusion item associated with the provided object. + // + // If an exclusion item for the immediate block (parent of the CSR if ptr is a CSR or a field) is + // not found, it recurses through the block's ancestors to find an available exclusion item. + // arg ptr: An extension of one of dv_base_reg{, _block or _field} classes. + function automatic csr_excl_item get_excl_item(uvm_object ptr); + dv_base_reg_block blk; + + // Attempt cast to blk. If it fails, then attempt to cast to CSR or field. + if (!$cast(blk, ptr)) begin + csr_field_t csr_or_fld = decode_csr_or_field(ptr); + `downcast(blk, csr_or_fld.csr.get_parent(), , , $sformatf("%m")) + end + + // Recurse through block's ancestors. + do begin + csr_excl_item csr_excl = blk.get_excl_item(); + if (csr_excl != null) return csr_excl; + `downcast(blk, blk.get_parent(), , , $sformatf("%m")) + end while (blk != null); + return null; + endfunction + + // Clone a UVM address map + function automatic uvm_reg_map clone_reg_map( + string name, uvm_reg_map map, uvm_reg_addr_t base_addr = 0, int n_bytes = 4, + uvm_endianness_e endian = UVM_LITTLE_ENDIAN, bit byte_addressing = 1); + uvm_reg_map clone; + uvm_reg_map submaps[$]; + uvm_reg regs[$]; + uvm_reg_block blk; + uvm_mem mems[$]; + + // Clone the map + blk = map.get_parent(); + clone = blk.create_map( + .name(name), + .base_addr(base_addr), + .n_bytes(n_bytes), + .endian(endian), + .byte_addressing(byte_addressing) + ); + + // Clone the submaps by calling this function recursively + map.get_submaps(submaps); + while (submaps.size()) begin + uvm_reg_map submap, submap_clone; + submap = submaps.pop_front(); + submap_clone = clone_reg_map(.name(name), .map(submap), .base_addr(submap.get_base_addr()), + // Use `UVM_NO_HIER` argument to get the n_bytes from the submap instead of the system + // level value. + .n_bytes(submap.get_n_bytes(UVM_NO_HIER)), .endian(endian)); + clone.add_submap(.child_map(submap_clone), .offset(map.get_submap_offset(submap))); + end + + // Clone the registers + map.get_registers(regs, UVM_NO_HIER); + while (regs.size()) begin + uvm_reg rg; + rg = regs.pop_front(); + clone.add_reg(.rg(rg), .offset(rg.get_offset(map)), .rights(rg.get_rights(map)), .unmapped(0), + .frontdoor(null)); + end + + // Clone the memories + map.get_memories(mems, UVM_NO_HIER); + while (mems.size()) begin + uvm_mem mem; + mem = mems.pop_front(); + clone.add_mem(.mem(mem), .offset(mem.get_offset(0, map)), .rights(mem.get_rights(map)), + .unmapped(0), .frontdoor(null)); + end + return clone; + + endfunction + + // sources + `include "csr_base_seq.sv" + `include "csr_hw_reset_seq.sv" + `include "csr_aliasing_seq.sv" + `include "csr_seq_lib.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.core b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.core new file mode 100644 index 0000000..5b531e6 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.core @@ -0,0 +1,32 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_base_agent" +description: "DV base agent" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_utils + files: + - dv_base_agent_pkg.sv + + - dv_base_agent_cfg.sv: {is_include_file: true} + - dv_base_agent_cov.sv: {is_include_file: true} + - dv_base_monitor.sv: {is_include_file: true} + - dv_base_sequencer.sv: {is_include_file: true} + - dv_base_driver.sv: {is_include_file: true} + - dv_base_agent.sv: {is_include_file: true} + - dv_base_seq.sv: {is_include_file: true} + + - dv_reactive_agent_cfg.sv: {is_include_file: true} + - dv_reactive_monitor.sv: {is_include_file: true} + - dv_reactive_sequencer.sv: {is_include_file: true} + - dv_reactive_agent.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.sv new file mode 100644 index 0000000..6845194 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent.sv @@ -0,0 +1,86 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A base agent class +// +// CFG_T: The type of the configuration object. This should be a subclass of +// dv_base_agent_cfg +// +// DRIVER_T: The type of the driver. This should be a subclass of dv_base_driver. +// +// HOST_DRIVER_T The type of the driver when the agent configured with if_mode set to Host. This +// should be a subclass of DRIVER_T. +// +// DEVICE_DRIVER_T The type of the driver when the agent configured with if_mode set to Device. +// This should be a subclass of DRIVER_T. +// +// SEQUENCER_T The type of the sequencer. This should be a subclass of dv_base_sequencer. +// +// MONITOR_T The type of the monitor. This should be a subclass of dv_base_monitor. +// +// COV_T The type of the object that monitors coverage. This should be a subclass of +// dv_base_agent_cov. + +class dv_base_agent #(type CFG_T = dv_base_agent_cfg, + type DRIVER_T = dv_base_driver, + type HOST_DRIVER_T = DRIVER_T, + type DEVICE_DRIVER_T = DRIVER_T, + type SEQUENCER_T = dv_base_sequencer, + type MONITOR_T = dv_base_monitor, + type COV_T = dv_base_agent_cov) extends uvm_agent; + + `uvm_component_param_utils(dv_base_agent #(CFG_T, DRIVER_T, HOST_DRIVER_T, DEVICE_DRIVER_T, + SEQUENCER_T, MONITOR_T, COV_T)) + + CFG_T cfg; + COV_T cov; + DRIVER_T driver; + SEQUENCER_T sequencer; + MONITOR_T monitor; + + extern function new (string name, uvm_component parent); + + extern function void build_phase(uvm_phase phase); + extern function void connect_phase(uvm_phase phase); +endclass + +function dv_base_agent::new (string name, uvm_component parent); + super.new(name, parent); +endfunction + +function void dv_base_agent::build_phase(uvm_phase phase); + super.build_phase(phase); + + if (cfg == null && !uvm_config_db#(CFG_T)::get(this, "", "cfg", cfg)) begin + `uvm_fatal(`gfn, $sformatf("failed to get %s from uvm_config_db", cfg.get_type_name())) + end + `uvm_info(`gfn, $sformatf("\n%0s", cfg.sprint()), UVM_HIGH) + + if (cfg.en_cov) begin + cov = COV_T ::type_id::create("cov", this); + cov.cfg = cfg; + end + + monitor = MONITOR_T::type_id::create("monitor", this); + monitor.cfg = cfg; + monitor.cov = cov; + + if (cfg.is_active) begin + sequencer = SEQUENCER_T::type_id::create("sequencer", this); + sequencer.cfg = cfg; + + if (cfg.has_driver) begin + if (cfg.if_mode == Host) driver = HOST_DRIVER_T::type_id::create("driver", this); + else driver = DEVICE_DRIVER_T::type_id::create("driver", this); + driver.cfg = cfg; + end + end +endfunction + +function void dv_base_agent::connect_phase(uvm_phase phase); + super.connect_phase(phase); + if (cfg.is_active && cfg.has_driver) begin + driver.seq_item_port.connect(sequencer.seq_item_export); + end +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cfg.sv new file mode 100644 index 0000000..bf6e54c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cfg.sv @@ -0,0 +1,53 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// The base config object for an agent + +class dv_base_agent_cfg extends uvm_object; + + // True if this is an active agent, so has a driver and sequencer. If false, this is a passive + // agent and only uses a monitor. + bit is_active = 1'b1; + + // True if the agent should enable a monitor (perhaps for a scoreboard) + bit en_monitor = 1'b1; + + // True if the agent should collect functional coverage + bit en_cov = 1'b1; + + // Relevant for an agent that acts on a communication bus. This is the interface mode of the agent + // on the bus. If if_mode == dv_utils_pkg::Device, the dut is assumed to be a host to which the + // agent responds. If if_mode == dv_utils_pkg::Host, the dut is assumed to be a device which will + // respond to transactions from the agent. + if_mode_e if_mode; + + // True if the agent has its own driver, which should be attached to the sequencer. If this is + // false, the agent can work by connecting to some lower-level agent to send multiple items. + bit has_driver = 1'b1; + + // The minimum time in ns that the monitor expects to see ok_to_end be high before it drops an + // objection that stopped the run_phase ending. + int ok_to_end_delay_ns = 1000; + + // Indicates that the interface is under reset. The derived monitor detects and maintains it. Note + // that this is distinct from the under_reset flag in dv_base_env_cfg: the interface of an agent + // can be in reset even if the environment as a whole is not. + bit in_reset; + + `uvm_object_utils_begin(dv_base_agent_cfg) + `uvm_field_int (is_active, UVM_DEFAULT) + `uvm_field_int (en_monitor, UVM_DEFAULT) + `uvm_field_int (en_cov, UVM_DEFAULT) + `uvm_field_enum(if_mode_e, if_mode, UVM_DEFAULT) + `uvm_field_int (has_driver, UVM_DEFAULT) + `uvm_field_int (ok_to_end_delay_ns, UVM_DEFAULT) + `uvm_field_int (in_reset, UVM_DEFAULT) + `uvm_object_utils_end + + extern function new (string name=""); +endclass + +function dv_base_agent_cfg::new (string name=""); + super.new(name); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cov.sv new file mode 100644 index 0000000..d47eaca --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_cov.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A generic coverage component for an agent. An instance of some subclass will be instantiated in +// as the coverage object in the agent's monitor. + +class dv_base_agent_cov #(type CFG_T = dv_base_agent_cfg) extends uvm_component; + `uvm_component_param_utils(dv_base_agent_cov #(CFG_T)) + + CFG_T cfg; + + extern function new (string name="", uvm_component parent=null); +endclass + +function dv_base_agent_cov::new (string name="", uvm_component parent=null); + super.new(name, parent); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_pkg.sv new file mode 100644 index 0000000..b2923d4 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_agent_pkg.sv @@ -0,0 +1,33 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package dv_base_agent_pkg; + // dep packages + import uvm_pkg::*; + import dv_utils_pkg::*; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + // package variables + string msg_id = "dv_base_agent_pkg"; + + // package sources + `include "dv_base_agent_cfg.sv" + `include "dv_base_agent_cov.sv" + `include "dv_base_monitor.sv" + `include "dv_base_sequencer.sv" + `include "dv_base_driver.sv" + `include "dv_base_agent.sv" + + `include "dv_reactive_agent_cfg.sv" + `include "dv_reactive_monitor.sv" + `include "dv_reactive_sequencer.sv" + `include "dv_reactive_agent.sv" + + // base seq + `include "dv_base_seq.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_driver.sv new file mode 100644 index 0000000..f37dec5 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_driver.sv @@ -0,0 +1,91 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A base class for a driver. This drives sequence items of type ITEM_T. If the subclass is designed +// to do so, it responds with items of type RSP_ITEM_T. +// +// NOTE: This class would make more sense as an abstract base class (with a pure virtual +// implementation of get_and_drive). Unfortunately, this isn't possible at the moment because +// dv_base_agent ends up needing to instantiate a uvm_driver instance unless parameters are +// overridden. This would be reasonable except that uvm_driver::create is not implemented in +// UVM 1.2 (the version that OpenTitan currently depends on). +// +// If we bump the UVM version past 1800.2-2020, we can switch this over to an abstract base +// class. + +class dv_base_driver #(type ITEM_T = uvm_sequence_item, + type CFG_T = dv_base_agent_cfg, + type RSP_ITEM_T = ITEM_T) + extends uvm_driver #(.REQ(ITEM_T), .RSP(RSP_ITEM_T)); + + `uvm_component_param_utils(dv_base_driver #(.ITEM_T (ITEM_T), + .CFG_T (CFG_T), + .RSP_ITEM_T (RSP_ITEM_T))) + + CFG_T cfg; + + extern function new (string name, uvm_component parent); + + // The run_phase task runs reset_signals() and get_and_drive() (described below) in parallel. + // Subclasses might not need to implement run_phase directly. + extern task run_phase(uvm_phase phase); + + // A task that runs forever, monitoring the cfg.in_reset flag and calling on_enter_reset when it + // becomes true. Subclasses shouldn't normally need to override this. + extern virtual task reset_signals(); + + // The get_and_drive task should be implemented in any subclass. It must repeatedly call + // get_next_item to consume items from the sequencer and, driving each. + // + // NOTE: Any implementation must implement this or fail at runtime. See note above for why this + // can't be enforced at build time. + extern virtual task get_and_drive(); + + // A task that is run at the start of any reset. It can be implemented by any subclass to clear + // any driven signals back to their "reset value". + // + // Note that this task should not consume any simulation time: it is a task to allow it to + // interact properly with clocking blocks. + extern virtual task on_enter_reset(); + + // A function that is run at the end of any reset. It may be implemented by any subclass and gives + // the class an opportunity to set up values before the start of a run, but without a race + // condition at the start of the reset. + extern virtual function void on_leave_reset(); +endclass + +function dv_base_driver::new (string name, uvm_component parent); + super.new(name, parent); +endfunction + +task dv_base_driver::run_phase(uvm_phase phase); + super.run_phase(phase); + fork + reset_signals(); + get_and_drive(); + join +endtask + +task dv_base_driver::reset_signals(); + forever begin + `uvm_info(get_full_name(), "Driver entering reset", UVM_HIGH) + on_enter_reset(); + wait(!cfg.in_reset); + `uvm_info(get_full_name(), "Driver leaving reset", UVM_HIGH) + on_leave_reset(); + wait(cfg.in_reset); + end +endtask + +task dv_base_driver::get_and_drive(); + `uvm_fatal(get_full_name(), "This task must be implemented by base classes.") +endtask + +task dv_base_driver::on_enter_reset(); + // The default behaviour of this task is to do nothing +endtask + +function void dv_base_driver::on_leave_reset(); + // The default behaviour of this function is to do nothing +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_monitor.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_monitor.sv new file mode 100644 index 0000000..65200b6 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_monitor.sv @@ -0,0 +1,110 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_monitor #(type ITEM_T = uvm_sequence_item, + type CFG_T = dv_base_agent_cfg, + type COV_T = dv_base_agent_cov) extends uvm_monitor; + `uvm_component_param_utils(dv_base_monitor #(ITEM_T, CFG_T, COV_T)) + + CFG_T cfg; + COV_T cov; + + // Indicates activity on the interface, driven only within the `monitor_ready_to_end()` task. + protected bit ok_to_end = 1; + + // Used to ensure we run the watchdog exactly once at the end of the run phase. Cleared at start + // of run phase. Set once watchdog_ok_to_end has been started at the end of the run_phase. + protected bit phase_ready_to_end_invoked = 0; + + // Analysis port for the collected transfer. + uvm_analysis_port #(ITEM_T) analysis_port; + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + analysis_port = new("analysis_port", this); + endfunction + + virtual task run_phase(uvm_phase phase); + super.run_phase(phase); + fork + collect_trans(); + join + endtask + + // collect transactions forever + virtual protected task collect_trans(); + // Empty - to be overridden in the child class + endtask + + // UVM callback which is invoked during phase sequencing. + virtual function void phase_ready_to_end(uvm_phase phase); + if (!phase.is(uvm_run_phase::get())) return; + if (phase_ready_to_end_invoked) return; + + phase_ready_to_end_invoked = 1; + fork + monitor_ready_to_end(); + watchdog_ok_to_end(phase); + join_none + endfunction + + // Ensures that ok_to_end when asserted, stays asserted for 1 ok_to_end_delay_ns period. + // + // If ok_to_end de-asserts before the watchdog expires, it waits for it to assert again + // and restarts the timer. This ensures that there is sufficient drain time to allow the + // simulation to end gracefully. It raises and drops the objection at the appropriate times. + virtual task watchdog_ok_to_end(uvm_phase run_phase); + bit objection_raised; + bit watchdog_done; + uint watchdog_restart_count = 1; + + forever begin + if (!objection_raised) begin + `uvm_info(`gfn, "watchdog_ok_to_end: raising objection", UVM_MEDIUM) + run_phase.raise_objection(this, {`gfn, " objection raised"}); + objection_raised = 1'b1; + end + + // Start the timer only when ok_to_end is asserted. + wait (ok_to_end); + `uvm_info(`gfn, $sformatf("watchdog_ok_to_end: starting the timer (count: %0d)", + watchdog_restart_count++), UVM_MEDIUM) + fork + begin: isolation_fork + fork + begin + watchdog_done = 1'b0; + #(cfg.ok_to_end_delay_ns * 1ns); + watchdog_done = 1'b1; + end + wait (!ok_to_end); + join_any + disable fork; + end: isolation_fork + join + + // If ok_to_end stayed high throughout the watchdog timer expiry, then drop the objection. + if (ok_to_end && watchdog_done) begin + `uvm_info(`gfn, "watchdog_ok_to_end: dropping objection", UVM_MEDIUM) + run_phase.drop_objection(this, {`gfn, " objection dropped"}); + objection_raised = 1'b0; + + // Wait for ok_to_end to de-assert again in future. + wait (!ok_to_end); + end + end + endtask + + // Asserts/de-asserts ok_to_end to indicate bus activity. + // + // This task is invoked in a forked thread within `phase_ready_to_end()`, which is callback + // invoked by UVM at the end of the phase. The forked thread does not join. Hence, the extended + // monitor needs to override this function and assert ok_to_end based on the activity on the bus + // (assert it when idle, de-assert when its not) in a forever loop. + virtual task monitor_ready_to_end(); + endtask + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_seq.sv new file mode 100644 index 0000000..616b47f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_seq.sv @@ -0,0 +1,25 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_seq #(type REQ = uvm_sequence_item, + type RSP = REQ, + type CFG_T = dv_base_agent_cfg, + type SEQUENCER_T = dv_base_sequencer) extends uvm_sequence#(REQ, RSP); + `uvm_object_param_utils(dv_base_seq #(REQ, RSP, CFG_T, SEQUENCER_T)) + `uvm_declare_p_sequencer(SEQUENCER_T) + + CFG_T cfg; + + `uvm_object_new + + task pre_start(); + super.pre_start(); + cfg = p_sequencer.cfg; + endtask + + task body(); + `uvm_fatal(`gtn, "Need to override this when you extend from this class!") + endtask : body + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_sequencer.sv new file mode 100644 index 0000000..ec35114 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_base_sequencer.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_sequencer #(type ITEM_T = uvm_sequence_item, + type CFG_T = dv_base_agent_cfg, + type RSP_ITEM_T = ITEM_T) + extends uvm_sequencer #(.REQ(ITEM_T), .RSP(RSP_ITEM_T)); + + `uvm_component_param_utils(dv_base_sequencer #(.ITEM_T (ITEM_T), + .CFG_T (CFG_T), + .RSP_ITEM_T (RSP_ITEM_T))) + CFG_T cfg; + + function new(string name, uvm_component parent); + super.new(name, parent); + endfunction +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent.sv new file mode 100644 index 0000000..4b323be --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent.sv @@ -0,0 +1,59 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// An extension of the base agent class that connects the monitor to the sequencer in order to allow +// the agent to run sequences that react to items collected by the monitor. +// +// CFG_T: The type of the configuration object. This should be a subclass of +// dv_reactive_agent_cfg +// +// DRIVER_T: The type of the driver. This should be a subclass of dv_base_driver. +// +// HOST_DRIVER_T The type of the driver when the agent configured with if_mode set to Host. This +// should be a subclass of DRIVER_T. +// +// DEVICE_DRIVER_T The type of the driver when the agent configured with if_mode set to Device. +// This should be a subclass of DRIVER_T. +// +// SEQUENCER_T The type of the sequencer. This should be a subclass of dv_reactive_sequencer. +// +// MONITOR_T The type of the monitor. This should be a subclass of dv_reactive_monitor. +// +// COV_T The type of the object that monitors coverage. This should be a subclass of +// dv_base_agent_cov. + +class dv_reactive_agent #(type CFG_T = dv_reactive_agent_cfg, + type DRIVER_T = dv_base_driver, + type HOST_DRIVER_T = DRIVER_T, + type DEVICE_DRIVER_T = DRIVER_T, + type SEQUENCER_T = dv_reactive_sequencer, + type MONITOR_T = dv_reactive_monitor, + type COV_T = dv_base_agent_cov) + extends dv_base_agent #(.CFG_T(CFG_T), + .DRIVER_T(DRIVER_T), + .HOST_DRIVER_T(HOST_DRIVER_T), .DEVICE_DRIVER_T(DEVICE_DRIVER_T), + .SEQUENCER_T(SEQUENCER_T), + .MONITOR_T(MONITOR_T), + .COV_T(COV_T)); + + `uvm_component_param_utils(dv_reactive_agent #(CFG_T, DRIVER_T, HOST_DRIVER_T, DEVICE_DRIVER_T, + SEQUENCER_T, MONITOR_T, COV_T)) + + extern function new (string name, uvm_component parent); + extern function void connect_phase(uvm_phase phase); +endclass + +function dv_reactive_agent::new (string name, uvm_component parent); + super.new(name, parent); +endfunction + +function void dv_reactive_agent::connect_phase(uvm_phase phase); + super.connect_phase(phase); + if (cfg.has_req_fifo) begin + monitor.req_analysis_port.connect(sequencer.req_analysis_fifo.analysis_export); + end + if (cfg.has_rsp_fifo) begin + monitor.rsp_analysis_port.connect(sequencer.rsp_analysis_fifo.analysis_export); + end +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent_cfg.sv new file mode 100644 index 0000000..e41a93d --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_agent_cfg.sv @@ -0,0 +1,27 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// The base config object for a reactive agent + +class dv_reactive_agent_cfg extends dv_base_agent_cfg; + + // True if agent's sequencer has a request fifo. If so, the agent will connect its monitor's + // req_analysis_port to the sequencer's request fifo. + bit has_req_fifo = 1'b0; + + // True if agent's sequencer has a response fifo. If so, the agent will connect its monitor's + // req_analysis_port to the sequencer's response fifo. + bit has_rsp_fifo = 1'b0; + + `uvm_object_utils_begin(dv_reactive_agent_cfg) + `uvm_field_int (has_req_fifo, UVM_DEFAULT) + `uvm_field_int (has_rsp_fifo, UVM_DEFAULT) + `uvm_object_utils_end + + extern function new (string name=""); +endclass + +function dv_reactive_agent_cfg::new (string name=""); + super.new(name); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_monitor.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_monitor.sv new file mode 100644 index 0000000..c9891b1 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_monitor.sv @@ -0,0 +1,31 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_reactive_monitor #(type ITEM_T = uvm_sequence_item, + type REQ_ITEM_T = ITEM_T, + type RSP_ITEM_T = ITEM_T, + type CFG_T = dv_base_agent_cfg, + type COV_T = dv_base_agent_cov) + extends dv_base_monitor #(.ITEM_T(ITEM_T), .CFG_T(CFG_T), .COV_T(COV_T)); + + `uvm_component_param_utils(dv_reactive_monitor #(ITEM_T, REQ_ITEM_T, RSP_ITEM_T, CFG_T, COV_T)) + + // item will be sent to this port for seq when req phase is done (last is set) + uvm_analysis_port #(REQ_ITEM_T) req_analysis_port; + // item will be sent to this port for seq when rsp phase is done (rsp_done is set) + uvm_analysis_port #(RSP_ITEM_T) rsp_analysis_port; + + extern function new (string name, uvm_component parent); + extern function void build_phase(uvm_phase phase); +endclass + +function dv_reactive_monitor::new (string name, uvm_component parent); + super.new(name, parent); +endfunction + +function void dv_reactive_monitor::build_phase(uvm_phase phase); + super.build_phase(phase); + req_analysis_port = new("req_analysis_port", this); + rsp_analysis_port = new("rsp_analysis_port", this); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_sequencer.sv new file mode 100644 index 0000000..95ba161 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_agent/dv_reactive_sequencer.sv @@ -0,0 +1,38 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_reactive_sequencer #(type ITEM_T = uvm_sequence_item, + type CFG_T = dv_reactive_agent_cfg, + type RSP_ITEM_T = ITEM_T) + extends dv_base_sequencer #(.ITEM_T(ITEM_T), .CFG_T(CFG_T), .RSP_ITEM_T(RSP_ITEM_T)); + + `uvm_component_param_utils(dv_reactive_sequencer #(.ITEM_T (ITEM_T), + .CFG_T (CFG_T), + .RSP_ITEM_T (RSP_ITEM_T))) + + // These FIFOs collect items when req/rsp is received, which are used to communicate between + // monitor and sequences. These FIFOs are only created if has_req_fifo / has_rsp_fifo is true in + // the agent config. + // + // When device is reactive, it gets items from req_analysis_fifo and send rsp to driver When this + // is a high-level agent, monitors put items to these 2 FIFOs for high-level seq + uvm_tlm_analysis_fifo #(ITEM_T) req_analysis_fifo; + uvm_tlm_analysis_fifo #(RSP_ITEM_T) rsp_analysis_fifo; + + extern function new(string name, uvm_component parent); + extern function void build_phase(uvm_phase phase); +endclass + +function dv_reactive_sequencer::new(string name, uvm_component parent); + super.new(name, parent); +endfunction + +function void dv_reactive_sequencer::build_phase(uvm_phase phase); + super.build_phase(phase); + + if (cfg == null) `uvm_fatal(get_full_name(), "agent cfg not provided.") + + if (cfg.has_req_fifo) req_analysis_fifo = new("req_analysis_fifo", this); + if (cfg.has_rsp_fifo) rsp_analysis_fifo = new("rsp_analysis_fifo", this); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/csr_excl_item.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/csr_excl_item.sv new file mode 100644 index 0000000..49847a9 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/csr_excl_item.sv @@ -0,0 +1,161 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Class: csr_excl_item +// Description: CSR exclusion item that holds exclusions applied for a given set of blocks / +// registers / fields provided and maintained as strings. +class csr_excl_item extends uvm_object; + `uvm_object_utils(csr_excl_item) + + typedef struct { + bit enable; + int csr_test_type; + csr_excl_type_e csr_excl_type; + } csr_excl_s; + local csr_excl_s exclusions[string]; + + `uvm_object_new + + // Adds an exclusion for an individual block, register or field. + // + // arg obj: Hierarchical path to the block, csr or field as string. Passing * and ? wildcards for + // glob style matching is allowed. User needs to take care the wildcards don't match more + // than desired. For example, for the ral.ctrl.tx field: + // obj = "ral.ctrl.tx" or "*.ctrl.tx" should work; "*.tx" might be too generic. + // arg csr_excl_type: The desired exclusion type. + // arg csr_test_type: The desired test type for which the exclusion is in effect. + virtual function void add_excl(string obj, + csr_excl_type_e csr_excl_type, + csr_test_type_e csr_test_type = CsrAllTests); + bit [2:0] val = CsrNoExcl; + bit [NUM_CSR_TESTS-1:0] test = CsrInvalidTest; + + `DV_CHECK_NE_FATAL(csr_test_type, CsrInvalidTest, + $sformatf("Test type not specified for the exclusion of %0s.", obj)) + + if (!exclusions.exists(obj)) begin + exclusions[obj] = '{enable:1'b1, csr_test_type:csr_test_type, csr_excl_type:csr_excl_type}; + return; + end + + val = csr_excl_type | exclusions[obj].csr_excl_type; + test = csr_test_type | exclusions[obj].csr_test_type; + exclusions[obj].csr_excl_type = csr_excl_type_e'(val); + exclusions[obj].csr_test_type = test; + endfunction + + // Turns exclusion on or off for a block, register or field. + // + // The originally set exclusions are untouched. This method only enables or disables the + // application of the exclusions temporarily. + // + // obj: The hierarchical path to block, register or field. + // enable: Bit indicating whether to enable or disable the application of exclusion. + // throw_error: Bit indicating whether to throw error if exclusions associated with obj do not + // exist. + virtual function void enable_excl(string obj, bit enable = 1'b1, bit throw_error = 1'b1); + string index; + if (get_excl_index(obj, index)) begin + exclusions[index].enable = enable; + return; + end + if (throw_error) begin + `uvm_fatal(`gfn, $sformatf("No exclusions found for %0s.", obj)) + end + endfunction + + // Checks if the given block, register or field is excluded. + // + // arg obj: The given block, register or field. + // arg csr_excl_type: The exclusion checked against. + // arg csr_test_type: The type of test for which the exclusion is in effect. + function bit is_excl(uvm_object obj, + csr_excl_type_e csr_excl_type, + csr_test_type_e csr_test_type); + uvm_reg_block blk; + + // Attempt cast to block. If it fails, then attempt to cast to CSR or field. + if (!$cast(blk, obj)) begin + csr_field_t csr_or_fld = decode_csr_or_field(obj); + if (csr_or_fld.field != null) begin + if (has_excl(csr_or_fld.field.`gfn, csr_excl_type, csr_test_type, is_excl)) return is_excl; + end else begin + if (has_excl(csr_or_fld.csr.`gfn, csr_excl_type, csr_test_type, is_excl)) return is_excl; + end + `downcast(blk, csr_or_fld.csr.get_parent(), , , `gfn) + end + + // Recurse through block's ancestors. + do begin + if (has_excl(blk.`gfn, csr_excl_type, csr_test_type, is_excl)) return is_excl; + blk = blk.get_parent(); + end while (blk != null); + return 1'b0; + endfunction + + // Retrieves the string index of the exclusions data structure. + // + // The provided object for lookup is a string itself. It however, may or may + // not exist verbatim as an associative array index in the `exclusions` data + // structure, since glob-style wildcards are supported when adding the + // exclusions. The provided object must hence be a fully resolved + // hierarchical path to the CSR block, register or field. + // + // Returns 1 if index is found, else 0. + // Returns the actual index as output arg. + local function bit get_excl_index(input string obj, output string index); + // If obj is a index of exclusions, return it, else loop through available + // keys to find a glob match. + if (exclusions.exists(obj)) begin + index = obj; + return 1'b1; + end else begin + foreach (exclusions[str]) begin + if (!uvm_re_match(str, obj)) begin + index = str; + return 1'b1; + end + end + end + return 1'b0; + endfunction + + // Checks if a particular exclusion for an object for a test is in effect. + // + // arg obj: The given block, register or field as string lookup. + // arg csr_excl_type: The exclusion checked against. + // arg csr_test_type: The type of test for which the exclusion is in effect. + // arg is_excl: Bit indicating the object is excluded. + // + // Returns 1 if an associated exclusion is found, else 0. + local function bit has_excl(input string obj, + input csr_excl_type_e csr_excl_type, + input csr_test_type_e csr_test_type, + output bit is_excl); + string index; + if (get_excl_index(obj, index)) begin + is_excl = exclusions[index].enable && + ((exclusions[index].csr_test_type & csr_test_type) != CsrInvalidTest) && + ((exclusions[index].csr_excl_type & csr_excl_type) != CsrNoExcl); + return 1'b1; + end + return 1'b0; + endfunction + + // Prints all exclusions for ease of debug. + virtual function void print_exclusions(uvm_verbosity verbosity = UVM_HIGH); + string test_names; + for (int i = NUM_CSR_TESTS - 1; i >= 0; i--) begin + csr_test_type_e csr_test = csr_test_type_e'(1 << i); + test_names = {test_names, csr_test.name(), (i > 0) ? " " : ""}; + end + foreach (exclusions[item]) begin + string enabled = exclusions[item].enable ? "[enabled]" : "[disabled]"; + `uvm_info(`gfn, $sformatf("CSR/field [%s] exclusion %s %s in csr_tests: {%s} = {%0b}", + item, exclusions[item].csr_excl_type.name(), enabled, test_names, + exclusions[item].csr_test_type), verbosity) + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_lockable_field_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_lockable_field_cov.sv new file mode 100644 index 0000000..62e8c9d --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_lockable_field_cov.sv @@ -0,0 +1,50 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// coverage object of lockable CSR field and its regwen +class dv_base_lockable_field_cov extends uvm_object; + // mirrored value of the lockable field, which is used to know if new value is written. + uvm_reg_data_t field_mirrored_val; + // when new written value is different from mirrored value, this will be set. + bit is_new_val_written; + // latched the regwen value when a new value is written to this lockable CSR. + bit regwen_val_when_new_value_written; + + `uvm_object_utils(dv_base_lockable_field_cov) + + // Cover these 2 cases + // 1. When regwen = 1, write a non-mirrored value to lockable CSR and read it back + // 2. When regwen = 0, write a non-mirrored value to lockable CSR and read it back + covergroup regwen_val_when_new_value_written_cg(string name) with function sample(); + option.per_instance = 1; + option.name = name; + + cp_regwen: coverpoint regwen_val_when_new_value_written; + endgroup : regwen_val_when_new_value_written_cg + + // use reg_field name as this name + function new(string name = ""); + regwen_val_when_new_value_written_cg = new($sformatf("lockable_field_cov_of_%s", name)); + endfunction : new + + virtual function void reset(uvm_reg_data_t reset_val); + field_mirrored_val = reset_val; + is_new_val_written = 0; + endfunction + + // invoke at dv_base_reg_field::post_write + virtual function void post_write(uvm_reg_data_t new_val, bit regwen_val); + if (field_mirrored_val != new_val) begin + is_new_val_written = 1; + regwen_val_when_new_value_written = regwen_val; + field_mirrored_val = new_val; + end + endfunction + + // invoke at dv_base_reg_field::post_read + virtual function void post_read(); + if (is_new_val_written) regwen_val_when_new_value_written_cg.sample(); + endfunction + +endclass : dv_base_lockable_field_cov diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mem.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mem.sv new file mode 100644 index 0000000..330991f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mem.sv @@ -0,0 +1,93 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Specialised version of uvm_mem for OpenTitan +// +// The specialised version adds the possibilities that a memory: +// +// - might not support partial writes (even if the bus would otherwise support them). +// +// - might store integrity data but not check it (merely passing it through to the next read). + +class dv_base_mem extends uvm_mem; + // If true, the memory supports partial writes. If not, any partial write will get an error + // response (d_error=1 in TileLink). + local bit mem_partial_write_support; + + // If true, mem stores integrity along with data but it won't check the data integrity + local bit data_intg_passthru; + + // Create a new instance of the memory abstraction class. + // + // The only access types supported are RW, RO and WO. + extern function new(string name, + longint unsigned size, + int unsigned n_bits, + string access = "RW", + int has_coverage = UVM_NO_COVERAGE); + + extern function void set_mem_partial_write_support(bit enable); + extern function bit get_mem_partial_write_support(); + + extern function void set_data_intg_passthru(bit enable); + extern function bit get_data_intg_passthru(); + + // This overrides uvm_mem::configure (which is *not* a virtual function), removing the check that + // the requested "access" is RW or RO, because we want to support WO as well. + // + // *That* check is now done in the constructor, where we can see the requested "access". + extern function void configure(uvm_reg_block parent, string hdl_path=""); +endclass + +function dv_base_mem::new(string name, + longint unsigned size, + int unsigned n_bits, + string access = "RW", + int has_coverage = UVM_NO_COVERAGE); + super.new(name, size, n_bits, access, has_coverage); + if (!(access inside {"RW", "RO", "WO"})) + `uvm_error(`gfn, $sformatf("Memory can only be RW, RO or WO (saw %s)", access)) +endfunction + +function void dv_base_mem::set_mem_partial_write_support(bit enable); + mem_partial_write_support = enable; +endfunction + +function bit dv_base_mem::get_mem_partial_write_support(); + return mem_partial_write_support; +endfunction + +function void dv_base_mem::set_data_intg_passthru(bit enable); + data_intg_passthru = enable; +endfunction + +function bit dv_base_mem::get_data_intg_passthru(); + return data_intg_passthru; +endfunction + +// Note: This is a copied version of uvm_mem::configure, but tweaked to remove the check on m_access +// (loosened slightly and now moved to the constructor) +function void dv_base_mem::configure(uvm_reg_block parent, string hdl_path=""); + if (parent == null) + `uvm_fatal(`gfn, "configure: parent argument is null") + + set_parent(parent); + + begin + uvm_mem_mam_cfg cfg = new; + + cfg.n_bytes = ((get_n_bits() - 1) / 8) + 1; + cfg.start_offset = 0; + cfg.end_offset = get_size() - 1; + + cfg.mode = uvm_mem_mam::GREEDY; + cfg.locality = uvm_mem_mam::BROAD; + + mam = new(get_full_name(), cfg, this); + end + + parent.add_mem(this); + + if (hdl_path != "") add_hdl_path_slice(hdl_path, -1, -1); +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv new file mode 100644 index 0000000..a4ce2ff --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_mubi_cov.sv @@ -0,0 +1,136 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// coverage object for a fixed width mubi +class mubi_cov #(parameter int Width = 4, + parameter int unsigned ValueTrue = prim_mubi_pkg::MuBi4True, + parameter int unsigned ValueFalse = prim_mubi_pkg::MuBi4False) extends uvm_object; + `uvm_object_param_utils(mubi_cov #(Width, ValueTrue, ValueFalse)) + + // Collect true, false and at least N other values (N = Width) + covergroup mubi_cg(string name) with function sample(bit [Width-1:0] value); + option.per_instance = 1; + option.name = name; + + cp_value: coverpoint value { + bins true = {ValueTrue}; + bins false = {ValueFalse}; + bins others[Width] = {[0:{Width{1'b1}}]} with (!(item inside {ValueTrue, ValueFalse})); + } + endgroup : mubi_cg + + // use reg_field name as this name + function new(string name = ""); + mubi_cg = new($sformatf("mubi%0d_cov_of_%s", Width, name)); + endfunction : new + + virtual function void sample(bit [Width-1:0] value); + mubi_cg.sample(value); + endfunction : sample +endclass : mubi_cov + +// TODO(#24142): This is a bit silly: it's just mubi_cov above, specialised to Width=32. But that +// doesn't work properly with VCS (tried with version 2023.03) because it ends up creating an +// enormous number of bins. Setting an explicit width here works around the problem. Fix this up +// properly if we change tool version. +class mubi32_cov extends uvm_object; + `uvm_object_utils(mubi32_cov) + + // Collect true, false and at least N other values (N = 32) + covergroup mubi_cg(string name) with function sample(bit [32-1:0] value); + option.per_instance = 1; + option.name = name; + + cp_value: coverpoint value { + bins true = {prim_mubi_pkg::MuBi32True}; + bins false = {prim_mubi_pkg::MuBi32False}; + bins others[32] = {[0:{32{1'b1}}]} with (!(item inside {prim_mubi_pkg::MuBi32True, + prim_mubi_pkg::MuBi32False})); + } + endgroup : mubi_cg + + // use reg_field name as this name + function new(string name = ""); + mubi_cg = new($sformatf("mubi%0d_cov_of_%s", 32, name)); + endfunction : new + + virtual function void sample(bit [32-1:0] value); + mubi_cg.sample(value); + endfunction : sample +endclass + +typedef mubi_cov #(.Width(4), + .ValueTrue(prim_mubi_pkg::MuBi4True), + .ValueFalse(prim_mubi_pkg::MuBi4False)) mubi4_cov; +typedef mubi_cov #(.Width(8), + .ValueTrue(prim_mubi_pkg::MuBi8True), + .ValueFalse(prim_mubi_pkg::MuBi8False)) mubi8_cov; +typedef mubi_cov #(.Width(12), + .ValueTrue(prim_mubi_pkg::MuBi12True), + .ValueFalse(prim_mubi_pkg::MuBi12False)) mubi12_cov; +typedef mubi_cov #(.Width(16), + .ValueTrue(prim_mubi_pkg::MuBi16True), + .ValueFalse(prim_mubi_pkg::MuBi16False)) mubi16_cov; +typedef mubi_cov #(.Width(20), + .ValueTrue(prim_mubi_pkg::MuBi20True), + .ValueFalse(prim_mubi_pkg::MuBi20False)) mubi20_cov; +typedef mubi_cov #(.Width(24), + .ValueTrue(prim_mubi_pkg::MuBi24True), + .ValueFalse(prim_mubi_pkg::MuBi24False)) mubi24_cov; +typedef mubi_cov #(.Width(28), + .ValueTrue(prim_mubi_pkg::MuBi28True), + .ValueFalse(prim_mubi_pkg::MuBi28False)) mubi28_cov; + +// a mubi coverage object, which allows to dynamically select the width of mubi +class dv_base_mubi_cov extends uvm_object; + int mubi_width = 0; + + // declare all mubi types, but only one will be created + mubi4_cov m_mubi4_cov; + mubi8_cov m_mubi8_cov; + mubi12_cov m_mubi12_cov; + mubi16_cov m_mubi16_cov; + mubi20_cov m_mubi20_cov; + mubi24_cov m_mubi24_cov; + mubi28_cov m_mubi28_cov; + mubi32_cov m_mubi32_cov; + + `uvm_object_utils(dv_base_mubi_cov) + `uvm_object_new + + // use reg_field name as this name + function void create_cov(int mubi_width); + string cov_name = $sformatf("mubi%0d_cov_of_%s", mubi_width, `gfn); + + // create_cov can be invoked only once + `DV_CHECK_EQ(this.mubi_width, 0) + this.mubi_width = mubi_width; + + case (mubi_width) + 4: m_mubi4_cov = mubi4_cov::type_id::create(cov_name); + 8: m_mubi8_cov = mubi8_cov::type_id::create(cov_name); + 12: m_mubi12_cov = mubi12_cov::type_id::create(cov_name); + 16: m_mubi16_cov = mubi16_cov::type_id::create(cov_name); + 20: m_mubi20_cov = mubi20_cov::type_id::create(cov_name); + 24: m_mubi24_cov = mubi24_cov::type_id::create(cov_name); + 28: m_mubi28_cov = mubi28_cov::type_id::create(cov_name); + 32: m_mubi32_cov = mubi32_cov::type_id::create(cov_name); + default: `uvm_fatal(`gfn, $sformatf("Unsupported mubi width (%0d) is used", mubi_width)) + endcase + endfunction : create_cov + + virtual function void sample(int value); + case (mubi_width) + 4: m_mubi4_cov.sample(value); + 8: m_mubi8_cov.sample(value); + 12: m_mubi12_cov.sample(value); + 16: m_mubi16_cov.sample(value); + 20: m_mubi20_cov.sample(value); + 24: m_mubi24_cov.sample(value); + 28: m_mubi28_cov.sample(value); + 32: m_mubi32_cov.sample(value); + default: `uvm_fatal(`gfn, $sformatf("Unsupported mubi width (%0d) is used", mubi_width)) + endcase + endfunction : sample +endclass : dv_base_mubi_cov diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.core b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.core new file mode 100644 index 0000000..b6b3cd1 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.core @@ -0,0 +1,29 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_base_reg" +description: "DV base reg/mem library" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_utils + - lowrisc:prim:mubi_pkg + files: + - dv_base_reg_pkg.sv + - csr_excl_item.sv: {is_include_file: true} + - dv_base_reg_field.sv: {is_include_file: true} + - dv_base_reg.sv: {is_include_file: true} + - dv_base_mem.sv: {is_include_file: true} + - dv_base_reg_block.sv: {is_include_file: true} + - dv_base_reg_map.sv: {is_include_file: true} + - dv_base_lockable_field_cov.sv: {is_include_file: true} + - dv_base_shadowed_field_cov.sv: {is_include_file: true} + - dv_base_mubi_cov.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.sv new file mode 100644 index 0000000..e3dc212 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg.sv @@ -0,0 +1,591 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// base register class which will be used to generate the reg +class dv_base_reg extends uvm_reg; + // external reg doesn't have storage in reg module, which may connect to some combinational logic + // hence, backdoor write isn't available + local bit is_ext_reg; + + local bit is_shadowed; + local bit shadow_wr_staged; // stage the first shadow reg write + local bit shadow_update_err; + local bit backdoor_write_shadow_val; // flag to avoid predict `shadow_wr_staged` + // Update internal shadow committed and shadowed values when register access is not `RW`. + local bit do_update_shadow_vals; + // In certain shadow reg (e.g. in AES), fatal error can lock write access. + local bit shadow_fatal_lock; + local string update_err_alert_name; + local string storage_err_alert_name; + + // This should be set if the register can be affected by a write even if that write also causes an + // error (because of an invalid mask, for example). + // + // TODO: This is really here as a workaround for a minor RTL bug, tracked in issue #24053. Once + // that issue is closed, remove this flag again. + bit writes_ignore_errors; + + // This is used for get_alias_name + string alias_name = ""; + // Lookup table for alias fields (used for get_field_by_name) + string field_alias_lookup[string]; + + // atomic_en_shadow_wr: semaphore to guarantee setting or resetting en_shadow_wr is unchanged + // through the 1st/2nd (or both) writes + semaphore atomic_en_shadow_wr; + + // A semaphore that's used to control processes that wish to write to the register (using + // uvm_reg::write). This was originally a workaround for a rather silly UVM bug that was only + // fixed in version 2020-2.0. It caused multiple processes to collide in a critical section if + // more than two are trying to write a register at once. + // + // Note that this semaphore controls reads as well as writes, because both operations use the + // m_is_busy flag. + // + // However, the lock is also useful if a process wishes to use predict(), in which case the + // m_is_busy flag should be false. To allow sequences to do that safely, the take_lock and + // release_lock methods that control this lock are not local. + local semaphore access_lock; + + function new(string name = "", + int unsigned n_bits, + int has_coverage); + super.new(name, n_bits, has_coverage); + atomic_en_shadow_wr = new(1); + access_lock = new(1); + endfunction : new + + // Create this register and its fields' IP-specific functional coverage. + function void create_cov(); + dv_base_reg_field fields[$]; + get_dv_base_reg_fields(fields); + foreach(fields[i]) fields[i].create_cov(); + // Create register-specific covergroups here. + endfunction + + // this is similar to get_name, but it gets the + // simple name of the aliased register instead. + function string get_alias_name (); + return this.alias_name; + endfunction: get_alias_name + + // this is similar to set_name, but it sets the + // simple name of the aliased register instead. + function void set_alias_name (string alias_name); + dv_base_reg_block reg_block; + `downcast(reg_block, get_parent()) + reg_block.register_alias_lookup[alias_name] = this.get_name(); + this.alias_name = alias_name; + endfunction: set_alias_name + + function void get_dv_base_reg_fields(ref dv_base_reg_field dv_fields[$]); + foreach (m_fields[i]) `downcast(dv_fields[i], m_fields[i]) + endfunction + + function dv_base_reg_block get_dv_base_reg_block(); + `downcast(get_dv_base_reg_block, get_parent()) + endfunction + + function uvm_reg_data_t get_predicted_mask(); + uvm_reg_data_t mask = 0; + dv_base_reg_field fields_q[$]; + this.get_dv_base_reg_fields(fields_q); + + foreach (fields_q[i]) begin + if (fields_q[i].has_prediction) begin + for (int j = 0; j < fields_q[i].get_n_bits(); j++) + mask[j+fields_q[i].get_lsb_pos()] = 1'b1; + end + end + + return mask; + endfunction + + // get_n_bits will return number of all the bits in the csr + // while this function will return actual number of bits used in reg field + function uint get_n_used_bits(); + foreach (m_fields[i]) get_n_used_bits += m_fields[i].get_n_bits(); + endfunction + + // loop all the fields to find the msb position of this reg + function uint get_msb_pos(); + foreach (m_fields[i]) begin + uint field_msb_pos = m_fields[i].get_lsb_pos() + m_fields[i].get_n_bits() - 1; + if (field_msb_pos > get_msb_pos) get_msb_pos = field_msb_pos; + end + endfunction + + virtual function dv_base_reg_field get_dv_base_reg_field_by_name(string fld_name, + bit check_fld_exist = 1'b1); + uvm_reg_field fld = get_field_by_name(fld_name); + dv_base_reg_field dv_fld; + + `downcast(dv_fld, fld) + if (check_fld_exist) begin + `DV_CHECK_NE_FATAL(dv_fld, null, + $sformatf("%0s does not exist in reg %0s", fld_name, get_full_name())) + end + return dv_fld; + endfunction + + // Return a mask of valid bits in the register. + virtual function uvm_reg_data_t get_reg_mask(); + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + get_reg_mask |= flds[i].get_field_mask(); + end + endfunction + + // Return a mask of read-only bits in the register. + virtual function uvm_reg_data_t get_ro_mask(); + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + get_ro_mask |= flds[i].get_ro_mask(); + end + endfunction + + // this function can only be called when this reg is intr_state reg + // Example: ral.intr_state.get_intr_pins_exp_value(). And it returns value of + // intr_state & intr_enable, which represents value of interrupt pins + virtual function uvm_reg_data_t get_intr_pins_exp_value(); + uvm_reg_block blk = get_parent(); + uvm_reg intr_enable_csr; + string intr_enable_csr_name; + bit is_intr_state_csr = !(uvm_re_match("intr_state*", get_name())); + + `DV_CHECK_EQ_FATAL(is_intr_state_csr, 1) + + // intr_enable and intr_state have the same suffix + intr_enable_csr_name = str_utils_pkg::str_replace(get_name(), "state", "enable"); + + intr_enable_csr = blk.get_reg_by_name(intr_enable_csr_name); + + // some interrupts may not have intr_enable + if (intr_enable_csr != null) begin + return get_mirrored_value() & intr_enable_csr.get_mirrored_value(); + end else begin + return get_mirrored_value(); + end + endfunction + + // Wen reg/fld can lock specific groups of fields' write access. The lockable fields are called + // lockable flds. + function void add_lockable_reg_or_fld(uvm_object lockable_obj); + dv_base_reg_field wen_fld; + `DV_CHECK_FATAL(m_fields.size(), 1, "This register has more than one field.\ + Please use register field's add_lockable_reg_or_fld() method instead.") + `downcast(wen_fld, m_fields[0]) + wen_fld.add_lockable_reg_or_fld(lockable_obj); + endfunction + + // Returns true if this register/field can lock the specified register/field, else return false. + function bit locks_reg_or_fld(uvm_object obj); + dv_base_reg_field wen_fld; + `DV_CHECK_FATAL(m_fields.size(), 1, "This register has more than one field.\ + Please use register field's locks_reg_or_fld() method instead.") + `downcast(wen_fld, m_fields[0]) + return wen_fld.locks_reg_or_fld(obj); + endfunction + + // Even though user can add lockable register or field via `add_lockable_reg_or_fld` method, the + // get_lockable_flds function will always return a queue of lockable fields. + function void get_lockable_flds(ref dv_base_reg_field lockable_flds_q[$]); + dv_base_reg_field wen_fld; + `DV_CHECK_FATAL(m_fields.size(), 1, "This register has more than one field.\ + Please use register field's get_lockable_flds() method instead.") + `downcast(wen_fld, m_fields[0]) + wen_fld.get_lockable_flds(lockable_flds_q); + endfunction + + // The register is a write enable register (wen_reg) if its fields are wen_flds. + function bit is_wen_reg(); + foreach (m_fields[i]) begin + dv_base_reg_field fld; + `downcast(fld, m_fields[i]) + if (fld.is_wen_fld()) return 1; + end + return 0; + endfunction + + function bit is_staged(); + return shadow_wr_staged; + endfunction + + // is_shadowed bit is only one-time programmable + // once this function is called in RAL auto-generated class, it cannot be changed + function void set_is_shadowed(); + is_shadowed = 1; + endfunction + + // A helper function for shadow register or field read to clear the `shadow_wr_staged` flag. + virtual function void clear_shadow_wr_staged(); + if (is_shadowed) begin + if (shadow_wr_staged) `uvm_info(`gfn, "clear shadow_wr_staged", UVM_HIGH) + shadow_wr_staged = 0; + clear_shadow_update_err(); + end + endfunction + + function bit get_is_shadowed(); + return is_shadowed; + endfunction + + function bit get_shadow_update_err(); + return shadow_update_err; + endfunction + + function bit get_shadow_storage_err(); + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + get_shadow_storage_err |= flds[i].get_shadow_storage_err(); + end + endfunction + + virtual function void clear_shadow_update_err(); + shadow_update_err = 0; + endfunction + + // do_predict callback to handle special regs. This function doesn't update mirror values, but + // update local variables used for the special regs. + // - shadow register: shadow reg won't be updated until the second write has no error + // - lock register: if wen_fld is set to 0, change access policy to all the lockable_flds + virtual function void pre_do_predict(uvm_reg_item rw, uvm_predict_e kind); + + // Skip updating shadow value or access type if: + // 1). Access is not OK, as access is aborted. + // 2). The operation is not write. + // 3). The update is triggered by backdoor poke. + if (rw.status != UVM_IS_OK || kind != UVM_PREDICT_WRITE || backdoor_write_shadow_val) return; + + if (is_shadowed && !shadow_fatal_lock) begin + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + + foreach (flds[i]) begin + // `rw.value` is a dynamic array. + uvm_reg_data_t wr_data = get_field_val(flds[i], rw.value[0]); + + // Skip updating shadow value or access type for this field if: + // 1). A storage error is triggered, which means the field is locked to error status. + // 2). The register is "RO". This condition is used to cover enable register locks shadowed + // register's write access. + if (flds[i].get_shadow_storage_err() || flds[i].get_access() == "RO") continue; + + // first write + if (!shadow_wr_staged) begin + flds[i].update_staged_val(wr_data); + continue; + end begin + // second write + if (flds[i].get_staged_val() == wr_data) begin + flds[i].update_committed_val(wr_data); + flds[i].update_shadowed_val(~wr_data); + end else begin + shadow_update_err = 1; + flds[i].sample_shadow_field_cov(.update_err(1)); + end + end + end + if (!shadow_wr_staged) shadow_wr_staged = 1; + else shadow_wr_staged = 0; + + // Update committed and shadowed values if the field access is not "RW". + // Used for register with special access policy such as `RW1S`. + if (!shadow_wr_staged && flds[0].get_access() != "RW") do_update_shadow_vals = 1; + end + endfunction + + // shadow register read will clear its phase tracker + virtual task post_read(uvm_reg_item rw); + if (rw.status == UVM_IS_OK) clear_shadow_wr_staged(); + endtask + + virtual function void set_is_ext_reg(bit is_ext); + is_ext_reg = is_ext; + endfunction + + virtual function bit get_is_ext_reg(); + return is_ext_reg; + endfunction + + // Override do_predict function to support shadow_reg. + // Skip predict in one of the following conditions: + // 1). It is shadow_reg's first write. + // 2). The shadow_reg is locked due to fatal storage error and it is not a backdoor write. + // Note that if shadow_register write has update error, we only update the value with correct + // fields. + virtual function void do_predict(uvm_reg_item rw, + uvm_predict_e kind = UVM_PREDICT_DIRECT, + uvm_reg_byte_en_t be = -1); + pre_do_predict(rw, kind); + if (is_shadowed && kind != UVM_PREDICT_READ) begin + if (shadow_wr_staged || (shadow_fatal_lock && rw.path != UVM_BACKDOOR)) begin + `uvm_info(`gfn, $sformatf( + "skip predict %s: due to shadow_reg_first_wr=%0b, shadow_fatal_lock=%0b", + get_name(), shadow_wr_staged, shadow_fatal_lock), UVM_HIGH) + return; + end else begin + `uvm_info(`gfn, $sformatf( + "Update shadow reg %0s rw.value from %0h to %0h", + get_name(), rw.value[0], get_committed_val()), UVM_HIGH) + rw.value[0] = get_committed_val(); + end + end + super.do_predict(rw, kind, be); + + // For register with special access policies, update committed and shadowed value again with + // the actual predicted value. + if (do_update_shadow_vals) begin + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + if (!flds[i].get_shadow_storage_err()) begin + flds[i].update_committed_val(`gmv(flds[i])); + flds[i].update_shadowed_val(~`gmv(flds[i])); + end + end + do_update_shadow_vals = 0; + end + lock_lockable_flds(rw.value[0], kind); + endfunction + + // This function is used for wen_reg to lock its lockable flds by changing the lockable flds' + // access policy. For register write via csr_wr(), this function is included in post_write(). + // For register write via tl_access(), user will need to call this function manually. + virtual function void lock_lockable_flds(uvm_reg_data_t val, uvm_predict_e kind); + if (!is_wen_reg()) return; + + foreach (m_fields[i]) begin + dv_base_reg_field fld; + `downcast(fld, m_fields[i]) + + if (fld.is_wen_fld()) begin + uvm_reg_data_t field_val = val & fld.get_field_mask(); + string field_access = fld.get_access(); + + // Check whether this field of the regwen is writeable at all (the regwen might not be + // writeable by software, in which case we can ignore it) + if (field_access == "RO") + continue; + + if (fld.get_mubi_width() == 0) begin + // This field is not encoded with a mubi value, and the only access type that we support + // is W0C. Check that it has been set up properly. + if (field_access != "W0C") begin + `uvm_fatal(`gfn, $sformatf("Field has access %0s (not W0C) and is not a mubi type.", + field_access)) + end + + // Because this field is W0C, software is allowed to clear it (disabling the write-enable) + // by writing a zero. Writing any other value will have no effect. + // + // A UVM_PREDICT_DIRECT prediction is a way for DV code to directly inform the RAL of a + // write coming through (not necessarily from software). This works by setting each bit if + // that bit of the write value is zero. + if (kind == UVM_PREDICT_WRITE && field_val == 1'b0) begin + fld.set_lockable_flds_access(1); + end else if (kind == UVM_PREDICT_DIRECT) begin + fld.set_lockable_flds_access((~field_val) & fld.get_field_mask()); + end + end else begin + // This field is encoded as a mubi value of the given width. + uvm_reg_data_t encoded_true; + + // Mubi fields only support the RW access value in UVM (because the bitwise operation to + // clear a mubi will set some bits and clear others!) + if (field_access != "RW") begin + `uvm_fatal(`gfn, $sformatf("Field has access %0s (not RW) but is a mubi type.", + field_access)) + end + + case (fld.get_mubi_width()) + 4: encoded_true = prim_mubi_pkg::MuBi4True; + 8: encoded_true = prim_mubi_pkg::MuBi8True; + 16: encoded_true = prim_mubi_pkg::MuBi16True; + 32: encoded_true = prim_mubi_pkg::MuBi32True; + default: `uvm_fatal(`gfn, $sformatf("Unknown mubi width: %0d", fld.get_mubi_width())) + endcase + + // Process the write as having locked the field if the value being written is anything + // other than encoded_true. A write of encoded_true is a nop. + if (field_val != encoded_true) begin + fld.set_lockable_flds_access(1); + end + end + end + end + endfunction + + virtual task poke(output uvm_status_e status, + input uvm_reg_data_t value, + input string kind = "BkdrRegPathRtl", + input uvm_sequence_base parent = null, + input uvm_object extension = null, + input string fname = "", + input int lineno = 0); + + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + if (kind == "BkdrRegPathRtlShadow") begin + flds[i].update_shadowed_val(get_field_val(flds[i], value)); + backdoor_write_shadow_val = 1; + end else if (kind == "BkdrRegPathRtl") begin + flds[i].update_committed_val(get_field_val(flds[i], value)); + backdoor_write_shadow_val = 1; + end + end + take_lock(); + super.poke(status, value, kind, parent, extension, fname, lineno); + release_lock(); + backdoor_write_shadow_val = 0; + endtask + + virtual function uvm_reg_data_t get_committed_val(); + dv_base_reg_field flds[$]; + this.get_dv_base_reg_fields(flds); + foreach (flds[i]) begin + get_committed_val |= flds[i].get_committed_val() << flds[i].get_lsb_pos(); + end + endfunction + + virtual function void reset(string kind = "HARD"); + super.reset(kind); + if (is_shadowed) begin + shadow_update_err = 0; + shadow_wr_staged = 0; + shadow_fatal_lock = 0; + // Make a new copy of the shadow write semaphore, so that we don't need a shadowed write + // operation to complete if a reset happens in the middle of one. + atomic_en_shadow_wr = new(1); + end + endfunction + + function void add_update_err_alert(string name); + if (update_err_alert_name == "") update_err_alert_name = name; + endfunction + + function void add_storage_err_alert(string name); + if (storage_err_alert_name == "") storage_err_alert_name = name; + endfunction + + function string get_update_err_alert_name(); + // block level alert name is input alert name from hjson + if (get_parent().get_parent() == null) return update_err_alert_name; + + // top-level alert name is ${ip_name} + alert name from hjson + return ($sformatf("%0s_%0s", get_dv_base_reg_block().get_ip_name(), update_err_alert_name)); + endfunction + + function void lock_shadow_reg(); + shadow_fatal_lock = 1; + endfunction + + function bit shadow_reg_is_locked(); + return shadow_fatal_lock; + endfunction + + function string get_storage_err_alert_name(); + string ip_name; + + // block level alert name is input alert name from hjson + if (get_parent().get_parent() == null) return storage_err_alert_name; + + // top-level alert name is ${ip_name} + alert name from hjson + return ($sformatf("%0s_%0s", get_dv_base_reg_block().get_ip_name(), storage_err_alert_name)); + endfunction + + // this overrides the get_field_by_name function + function dv_base_reg_field get_field_by_name(string name); + dv_base_reg_field retval; + if (field_alias_lookup.exists(name)) begin + `downcast(retval, super.get_field_by_name(field_alias_lookup[name])) + end else begin + `downcast(retval, super.get_field_by_name(name)) + end + return retval; + endfunction + + // Take the register's lock (see the documentation above access_lock for more details) + // + // This is mostly used in the wrappers around read, write etc. (working around a UVM bug). But the + // task is not local, because another class might want to use the predict method, which musn't + // overlap with the m_is_busy flag in uvm_reg. Taking this lock ensures it won't. + task take_lock(); + access_lock.get(); + endtask + + // Release the register's lock (see the documentation above access_lock for more details). This + // should only be called by a process that has already taken the lock with take_lock. + function void release_lock(); + access_lock.put(); + endfunction + + // A thin wrapper around uvm_reg::write that takes access_lock. See notes above access_lock that + // explain why it's needed. + task write(output uvm_status_e status, + input uvm_reg_data_t value, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uvm_reg_map map = null, + input uvm_sequence_base parent = null, + input int prior = -1, + input uvm_object extension = null, + input string fname = "", + input int lineno = 0); + take_lock(); + super.write(status, value, path, map, parent, prior, extension, fname, lineno); + release_lock(); + endtask + + // A thin wrapper around uvm_reg::read that takes access_lock. See notes above access_lock that + // explain why it's needed. + task read(output uvm_status_e status, + output uvm_reg_data_t value, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uvm_reg_map map = null, + input uvm_sequence_base parent = null, + input int prior = -1, + input uvm_object extension = null, + input string fname = "", + input int lineno = 0); + take_lock(); + super.read(status, value, path, map, parent, prior, extension, fname, lineno); + release_lock(); + endtask + + // A thin wrapper around uvm_reg::peek that takes access_lock. See notes above access_lock that + // explain why it's needed. + task peek(output uvm_status_e status, + output uvm_reg_data_t value, + input string kind = "", + input uvm_sequence_base parent = null, + input uvm_object extension = null, + input string fname = "", + input int lineno = 0); + take_lock(); + super.peek(status, value, kind, parent, extension, fname, lineno); + release_lock(); + endtask + + // A thin wrapper around uvm_reg::mirror that takes access_lock. See notes above access_lock that + // explain why it's needed. + task mirror(output uvm_status_e status, + input uvm_check_e check = UVM_NO_CHECK, + input uvm_path_e path = UVM_DEFAULT_PATH, + input uvm_reg_map map = null, + input uvm_sequence_base parent = null, + input int prior = -1, + input uvm_object extension = null, + input string fname = "", + input int lineno = 0); + take_lock(); + super.mirror(status, check, path, map, parent, prior, extension, fname, lineno); + release_lock(); + endtask + + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_block.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_block.sv new file mode 100644 index 0000000..76900b2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_block.sv @@ -0,0 +1,616 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// base register block class which will be used to generate the reg blocks +class dv_base_reg_block extends uvm_reg_block; + `m_uvm_get_type_name_func(dv_base_reg_block) + + // The default addr, data and byte widths. + // + // The UVM reg data structures are built on `UVM_REG_ADDR|DATA|BYTEENABLE_WIDTH settings which + // are compile time, i.e. fixed for all RAL models across the project. What if we have multiple + // RAL models that have different width needs? The solution is to let the UVM data structures be + // created with large enough widths to accommodate a heterogeneous set of RAL models, and use + // these runtime settings below instead, to perform associated computations. Values retrieved + // for comparisons, such as uvm_reg::get_mirrored_value() may return data that is wider than + // needed. It would then be upto the testbench to cast it to the appropriate width if necessary. + // + // These are configured with build() function. + protected int unsigned m_addr_width; + protected int unsigned m_data_width; + protected int unsigned m_be_width; + + // Since an IP may contains more than one reg block we construct reg_block name as + // {ip_name}_{reg_interface_name}. + // All the reg_blocks in the IP share the same alert. In top-level, We construct the alert + // name as {ip_name}_{alert_name}. Hence, we need this ip_name in reg_block + local string ip_name; + + // CSR exclusion object that holds exclusion tags for the sub-blocks, CSRs and fields. + protected csr_excl_item csr_excl; + + // The address mask for the register block specific to a map. This will be (1 << K) - 1 for some + // K. All relative offsets in the register block have addresses less than (1 << K), so an address + // decoder that starts by discarding all higher bits will work correctly so long as the chosen + // base address of the register block has no bits in common with this mask. + // + // This is set by compute_addr_mask(), which must run after locking the model. + protected uvm_reg_addr_t addr_mask[uvm_reg_map]; + + // A list of all ranges associated with memories, ordered by increasing start address. + // + // To get the list of memory ranges, use get_mem_ranges (which is memoized). + local addr_range_t m_mem_ranges[$]; + + // A flag showing that m_mem_ranges has been computed by a previous call to get_mem_ranges + local bit m_mem_ranges_known; + + // A list of all ranges that are associated with either a memory or a register + // + // This is populated by compute_mapped_addr_ranges, which builds it from the result of + // get_mem_ranges together with the ranges formed by iterating over the registers and the range of + // each. This is sorted in ascending order based on start_addr. + addr_range_t mapped_addr_ranges[$]; + + // Indicates whether accesses to unmapped regions of this block returns an error response (0). + protected bit unmapped_access_ok; + + // Indicates whether byte writes are supported (enabled by default). + // TODO: Remove this in future - this is really a property of the physical interface that is used + // to access design through this RAL model (a.k.a, the map & adapter), and not the RAL model + // itself. This information should be sought using uvm_reg_adapter::supports_byte_enable instead. + // This is added for ease of rv_dm testbench development. + protected bit supports_byte_enable = 1'b1; + + // Indicates whether an instruction fetch is allowed from a CSR. This isn't something you'd + // normally expect, but it allows us to model a block that contains both registers and memory and + // doesn't make a distinction between read and fetch. + local bit allows_csr_fetch = 1'b0; + + // Custom RAL models may support sub-word CSR writes smaller than CSR width. + protected bit supports_sub_word_csr_writes = 1'b0; + + // Enables functional coverage of comportable IP-specific specialized registers, such as regwen + // and mubi. This flag can only be disabled before invoking `create_dv_reg_cov`. + protected bit en_dv_reg_cov = 1; + + bit has_unmapped_addrs; + + // A queue of all the unmapped address ranges. All mapped addresses for this block are between the + // base address (using the default map) and that plus the maximum address representable with the + // address mask. + // + // Unmapped addresses are the addresses in that range that don't point at a register of part of a + // memory. This variable holds those addresses, grouped into ranges and sorted in ascending order + // of start_addr. + addr_range_t unmapped_addr_ranges[$]; + + // Lookup table for alias registers and fields. + string register_alias_lookup[string]; + string field_alias_lookup[string]; + + function new (string name = "", int has_coverage = UVM_NO_COVERAGE); + super.new(name, has_coverage); + endfunction + + function void set_ip_name(string name); + ip_name = name; + endfunction + + function string get_ip_name(); + // `DV_CHECK_FATAL can't take "" as an input + string empty_str = ""; + `DV_CHECK_FATAL(ip_name != empty_str, "ip_name hasn't been set yet") + return ip_name; + endfunction + + // Returns the CSR exclusion item attached to the block. + virtual function csr_excl_item get_excl_item(); + return csr_excl; + endfunction + + function void set_unmapped_access_ok(bit ok); + unmapped_access_ok = ok; + endfunction + + function bit get_unmapped_access_ok(); + return unmapped_access_ok; + endfunction + + function void set_supports_byte_enable(bit enable); + supports_byte_enable = enable; + endfunction + + function bit get_supports_byte_enable(); + return supports_byte_enable; + endfunction + + function void set_supports_sub_word_csr_writes(bit enable); + supports_sub_word_csr_writes = enable; + endfunction + + function bit get_supports_sub_word_csr_writes(); + return supports_sub_word_csr_writes; + endfunction + + function void set_allows_csr_fetch(bit allowed); + allows_csr_fetch = allowed; + endfunction + + function bit get_allows_csr_fetch(); + return allows_csr_fetch; + endfunction + + // provide build function to supply base addr + virtual function void build(uvm_reg_addr_t base_addr, + csr_excl_item csr_excl, + int unsigned addr_width, + int unsigned data_width, + int unsigned be_width); + m_addr_width = addr_width; + m_data_width = data_width; + m_be_width = be_width; + endfunction + + // This function is invoked at the end of `build` method in uvm_reg_base.sv template to create + // IP-specific functional coverage for this block and its registers and fields. + function void create_cov(); + dv_base_reg_block blks[$]; + dv_base_reg regs[$]; + + get_dv_base_reg_blocks(blks); + foreach (blks[i]) blks[i].create_cov(); + + get_dv_base_regs(regs); + foreach (regs[i]) regs[i].create_cov(); + // Create block-specific covergroups here. + endfunction + + function void get_dv_base_reg_blocks(ref dv_base_reg_block blks[$]); + uvm_reg_block uvm_blks[$]; + this.get_blocks(uvm_blks); + foreach (uvm_blks[i]) `downcast(blks[i], uvm_blks[i]) + endfunction + + function void get_dv_base_regs(ref dv_base_reg dv_regs[$]); + uvm_reg ral_regs[$]; + // if the ral has hier, this function will recursively includes the registers in the sub-blocks + this.get_registers(ral_regs); + foreach (ral_regs[i]) `downcast(dv_regs[i], ral_regs[i]) + endfunction + + function dv_base_reg get_dv_base_reg_by_name(string csr_name, bit check_csr_exist = 1'b1); + uvm_reg csr = get_reg_by_name(csr_name); + `downcast(get_dv_base_reg_by_name, csr) + if (check_csr_exist) begin + `DV_CHECK_NE_FATAL(get_dv_base_reg_by_name, null, + $sformatf("%0s does not exist in block %0s",csr_name, get_name())) + end + endfunction + + virtual function void get_shadowed_regs(ref dv_base_reg shadowed_regs[$]); + dv_base_reg all_regs[$]; + this.get_dv_base_regs(all_regs); + foreach (all_regs[i]) begin + if (all_regs[i].get_is_shadowed()) shadowed_regs.push_back(all_regs[i]); + end + endfunction + + function bit has_shadowed_regs(); + dv_base_reg regs[$]; + get_shadowed_regs(regs); + return (regs.size() > 0); + endfunction + + // Internal function, used to compute the address mask for this register block. + // + // This is quite an expensive computation, so we memoize the results in addr_mask[map]. + // Use below to get the addr map size #3317 + // max2(biggest_reg_offset+reg_size, biggest_mem_offset+mem_size) and then round up to 2**N + protected function void compute_addr_mask(uvm_reg_map map); + uvm_reg_addr_t max_offset; + uvm_reg_block blocks[$]; + int unsigned alignment; + + // Assumption: + // Only chip-level RAL has multiple sub reg_blocks. Its addr_mask is '1 + // In block-level, we have one RAL for one TLUL interface. We don't put multiple reg_block in a + // RAL, as UVM RAL can't handle the case that each sub-block uses a different map: + // - ral.blk1 -> use map_TL1 + // - ral.blk2 -> use map_TL2 + get_blocks(blocks); + if (blocks.size > 0) begin // if true, this is a chip-level RAL + addr_mask[map] = '1; + return; + end + + max_offset = get_max_offset(map); + + // Set alignment to be ceil(log2(biggest_offset)) + alignment = 0; + while (max_offset > 0) begin + alignment++; + max_offset = max_offset >> 1; + end + + // Note that we know alignment > 0 (because we've already checked that we have at least one + // register or memory). + `DV_CHECK_GT_FATAL(alignment, 0) + + // Finally, extract a mask corresponding to the alignment + addr_mask[map] = (1 << alignment) - 1; + + // Computed mask must be non-zero. + `DV_CHECK_FATAL(addr_mask[map]) + endfunction + + // Internal function, used to get a list of all valid memory ranges + // + // Note that the block might not have any memories, in which case m_mem_ranges will be empty after + // this function. + local function void ensure_mem_ranges(); + uvm_mem mems[$]; + + if (m_mem_ranges_known) return; + + // Get any memories associated with the uvm_reg_block. (There may be none) + get_memories(mems); + + // Clear any existing contents of m_mem_ranges and then project the memories we just found to + // their start / end addresses, writing the ranges to m_mem_ranges. + m_mem_ranges.delete(); + foreach (mems[i]) begin + addr_range_t range; + range.start_addr = mems[i].get_address(); + range.end_addr = range.start_addr + mems[i].get_size() * mems[i].get_n_bytes() - 1; + m_mem_ranges.push_back(range); + end + + // Sort m_mem_ranges by start_addr, ensuring that the ordering in the list only depends on the + // addresses of the ranges (rather than the order in which they were defined in the + // configuration) + if (m_mem_ranges.size() > 0) begin + m_mem_ranges.sort() with (item.start_addr); + end + + m_mem_ranges_known = 1; + + // Add a UVM_HIGH print to report what memory ranges are in the block (which will happen once + // per call to set_base_addr because this code only runs when m_mem_ranges_known is false). + // + // This block has no effect on the simulation, so is gated by a check that the messages will be + // printed (to avoid iterating through the list of ranges if not). + if (uvm_report_enabled(UVM_HIGH, UVM_INFO, "ensure_mem_ranges()")) begin + `uvm_info("ensure_mem_ranges()", + $sformatf("%0s has %0d memory ranges%0s", + get_name(), m_mem_ranges.size(), (m_mem_ranges.size() > 0) ? ":" : "."), + UVM_HIGH) + foreach(m_mem_ranges[i]) begin + `uvm_info("ensure_mem_ranges()", + $sformatf("Range %2d: 0x%08h .. 0x%08h", + i, m_mem_ranges[i].start_addr, m_mem_ranges[i].end_addr), + UVM_HIGH) + end + end + endfunction + + // Write the list of address ranges associated with memory to the ranges output argument. + // + // This result is memoized. + function void get_mem_ranges(output addr_range_t ranges[$]); + ensure_mem_ranges(); + ranges = m_mem_ranges; + endfunction + + // Return the number of memories in this reg_block. + // + // This is quick because it uses the same memoization as get_mem_ranges. + function int unsigned get_num_memories(); + ensure_mem_ranges(); + return m_mem_ranges.size(); + endfunction + + // Compute CSR addresses, memory address ranges, and the list of all address ranges used by either + // memories or registers. + // + // This is idempotent and will re-calculate the same lists if called a second time. + local function void compute_mapped_addr_ranges(); + uvm_reg csrs[$]; + addr_range_t mem_ranges[$]; + + get_registers(csrs); + + // Compute all mem ranges known to this reg block + get_mem_ranges(mem_ranges); + + // Convert each CSR into an address range + mapped_addr_ranges.delete(); + foreach (csrs[i]) begin + addr_range_t csr_addr_range; + csr_addr_range.start_addr = csrs[i].get_address(); + csr_addr_range.end_addr = csr_addr_range.start_addr + csrs[i].get_n_bytes() - 1; + mapped_addr_ranges.push_back(csr_addr_range); + end + // Now append the ranges from memories + mapped_addr_ranges = {mapped_addr_ranges, mem_ranges}; + + // Sort the mapped address ranges in ascending order based on the start_addr of each range + mapped_addr_ranges.sort(m) with (m.start_addr); + + `uvm_info(`gfn, $sformatf("mapped_addr_ranges: %0p", mapped_addr_ranges), UVM_HIGH) + endfunction + + // Get a list of all invalid address ranges in this reg block + // + // This is idempotent and will re-calculate the same list if called a second time. + local function void compute_unmapped_addr_ranges(); + addr_range_t range; + + // convert the address mask into a relative address, + // this is the highest addressable location in the register block + uvm_reg_addr_t highest_addr = default_map.get_base_addr() + get_addr_mask(); + + unmapped_addr_ranges.delete(); + + // unmapped address ranges consist of: + // - any gaps in the address space between mapped address ranges + // - any space between the map base address and the first mapped address range + // - space between the last mapped address and the highest address mapped by the address mask + if (mapped_addr_ranges.size() == 0) begin + range.start_addr = default_map.get_base_addr(); + range.end_addr = highest_addr; + unmapped_addr_ranges.push_back(range); + end else begin + // 0 -> start_addr-1 + if (mapped_addr_ranges[0].start_addr - default_map.get_base_addr() > 0) begin + range.start_addr = default_map.get_base_addr(); + range.end_addr = mapped_addr_ranges[0].start_addr - 1; + unmapped_addr_ranges.push_back(range); + end + + // all address ranges in the "middle" - only applies if + // there are more than 1 mapped address ranges + if (mapped_addr_ranges.size() > 1) begin + for (int i = 0; i < mapped_addr_ranges.size() - 1; i++) begin + range.start_addr = mapped_addr_ranges[i].end_addr + 1; + range.end_addr = mapped_addr_ranges[i+1].start_addr - 1; + if (range.start_addr < range.end_addr) begin + unmapped_addr_ranges.push_back(range); + end + end + end + + // end_addr+1 -> highest_addr + if (mapped_addr_ranges[$].end_addr < highest_addr) begin + range.start_addr = mapped_addr_ranges[$].end_addr + 1; + range.end_addr = highest_addr; + unmapped_addr_ranges.push_back(range); + end + end + has_unmapped_addrs = (unmapped_addr_ranges.size() > 0); + `uvm_info(`gfn, $sformatf("unmapped_addr_ranges: %0p", unmapped_addr_ranges), UVM_HIGH) + endfunction + + // Return the offset of the highest byte contained in either a register or a memory + function uvm_reg_addr_t get_max_offset(uvm_reg_map map = null); + uvm_reg_addr_t max_offset; + uvm_reg regs[$]; + uvm_mem mems[$]; + + if (map == null) map = get_default_map(); + + get_registers(regs); + get_memories(mems); + `DV_CHECK_GT_FATAL(regs.size() + mems.size(), 0) + + // Walk the known registers and memories, calculating the largest byte address visible. Note + // that the get_offset() calls will return absolute addresses, including any base address in the + // specified register map. + max_offset = 0; + foreach (regs[i]) begin + max_offset = max2(regs[i].get_offset(map) + regs[i].get_n_bytes() - 1, max_offset); + end + + foreach (mems[i]) begin + uvm_reg_addr_t mem_size; + mem_size = mems[i].get_offset(.map(map)) + mems[i].get_size() * mems[i].get_n_bytes() - 1; + max_offset = max2(mem_size, max_offset); + end + + return max_offset; + endfunction + + // Get the address mask. This should only be called after locking the model (because it depends on + // the layout of registers and memories in the block). + function uvm_reg_addr_t get_addr_mask(uvm_reg_map map = null); + `DV_CHECK_FATAL(is_locked()) + if (map == null) map = get_default_map(); + if (!addr_mask.exists(map)) compute_addr_mask(map); + return addr_mask[map]; + endfunction + + // Set the base address for the given register map to a random value. + // + // The value is chosen to be aligned as required by the register block. If map is null, this sets + // the base address for the default register map. + function void set_randomized_base_addr(uvm_reg_map map = null); + uvm_reg_addr_t mask; + uvm_reg_addr_t base_addr; + + if (map == null) begin + map = get_default_map(); + end + + mask = get_addr_mask(map); + + if (!std::randomize(base_addr) with { + (base_addr & mask) == '0; + base_addr >> m_addr_width == 0; + }) begin + `uvm_fatal(get_name(), + $sformatf("Failed to randomise base address with mask 0x%0x and width %0d.", + mask, m_addr_width)) + end + + set_base_addr(base_addr, map); + endfunction + + // Set the base address for the given register map + // + // After setting the base address, this function clears m_mem_ranges_known then updates + // mapped_addr_ranges and unmapped_addr_ranges. + function void set_base_addr(uvm_reg_addr_t base_addr, uvm_reg_map map = null); + uvm_reg_addr_t mask; + + if (map == null) map = get_default_map(); + mask = get_addr_mask(map); + + // Check that the base address is appropriately aligned, based on the mask we computed from map. + if (base_addr & mask) begin + `uvm_error(get_name(), + $sformatf("Base address of 0x%0h is not aligned to mask 0x%0x.", + base_addr, mask)) + end + + // Check that the base address is actually representable with m_addr_width bits + if (base_addr >> m_addr_width) begin + `uvm_error(get_name(), + $sformatf("Base address of 0x%0h is not representable with %0d bits.", + base_addr, m_addr_width)) + end + + `uvm_info(get_name(), $sformatf("Setting register base address to 0x%0h", base_addr), UVM_HIGH) + map.set_base_addr(base_addr); + + m_mem_ranges_known = 0; + + compute_mapped_addr_ranges(); + compute_unmapped_addr_ranges(); + endfunction + + // Round the given address down to the start of the containing word. For example, if the address + // is 'h123, it will be rounded down to 'h120. + // + // This is useful if you have a possibly misaligned address and you want to know whether it hits a + // register (since get_reg_by_offset needs the aligned address for the start of the register). + function uvm_reg_addr_t get_word_aligned_addr(uvm_reg_addr_t byte_addr); + uvm_reg_addr_t shift = $clog2(m_be_width); + return (byte_addr >> shift) << shift; + endfunction + + // Get the absolute address (in the default register map) for the given offset. For example, if + // the base address is 'h100 and offset is 'h13, this will return 'h113 ('h110 if word_aligned is + // set). + function uvm_reg_addr_t get_addr_from_offset(uvm_reg_addr_t byte_offset, + bit word_aligned = 1'b1, + uvm_reg_map map = null); + if (map == null) map = get_default_map(); + return (word_aligned ? get_word_aligned_addr(byte_offset) : byte_offset) + map.get_base_addr(); + endfunction + + // The design ignores the address bits that aren't enabled by addr_mask. + // Normalize these ignored bits to enable locating which CSR/mem is at the returned address. + function uvm_reg_addr_t get_normalized_addr(uvm_reg_addr_t byte_addr, uvm_reg_map map = null); + if (map == null) map = get_default_map(); + return get_addr_from_offset(.byte_offset(byte_addr & get_addr_mask(map)), + .word_aligned(1), + .map(map)); + endfunction + + // Set default map for this block and all its sub-blocks by name. + // This function only works if user is setting default map for all blocks under the hierarchy + // with the same map name. + function void set_default_map_w_subblks_by_name(string map_name); + dv_base_reg_block subblks[$]; + uvm_reg_map map = this.get_map_by_name(map_name); + `DV_CHECK(map != null) + this.set_default_map(map); + + get_dv_base_reg_blocks(subblks); + foreach (subblks[i]) subblks[i].set_default_map_w_subblks_by_name(map_name); + endfunction + + // this overrides the get_reg_by_name function + function dv_base_reg get_reg_by_name(string name); + dv_base_reg retval; + if (register_alias_lookup.exists(name)) begin + `downcast(retval, super.get_reg_by_name(register_alias_lookup[name])) + end else begin + `downcast(retval, super.get_reg_by_name(name)) + end + return retval; + endfunction + + // this overrides the get_field_by_name function + // note however that this function is only meaningful if the fields are unique within a regblock! + function dv_base_reg_field get_field_by_name(string name); + dv_base_reg_field retval; + if (field_alias_lookup.exists(name)) begin + `downcast(retval, super.get_field_by_name(field_alias_lookup[name])) + end else begin + `downcast(retval, super.get_field_by_name(name)) + end + return retval; + endfunction + + function void set_en_dv_reg_cov(bit val); + uvm_reg csrs[$]; + get_registers(csrs); + `DV_CHECK_FATAL(!csrs.size(), + "Cannot set en_dv_base_reg_cov when covergroups are built already!") + en_dv_reg_cov = val; + endfunction + + function bit get_en_dv_reg_cov(); + return en_dv_reg_cov; + endfunction + + // Return true if there is at least one register in this reg block or a child block + // + // This is equivalent to calling get_registers with hier=UVM_HIER (so that it recurses). It is no + // more efficient, but is slightly more convenient because the call-site doesn't need to create a + // queue to be passed as a reference. + function bit has_csrs(); + uvm_reg regs[$]; + get_registers(regs, UVM_HIER); + return regs.size() > 0; + endfunction + + // Return true if a fetch from rg is allowed because the block that contains it, or one of that + // block's ancestors, has allows_csr_fetch set. + static function bit reg_allows_fetch(uvm_reg rg); + uvm_reg_block blk = rg.get_parent(); + dv_base_reg_block dv_blk; + + while (blk != null) begin + if ($cast(dv_blk, blk) && dv_blk.get_allows_csr_fetch()) return 1'b1; + blk = blk.get_parent(); + end + return 1'b0; + endfunction + + // Collect the registers in this reg block, or a child block, from which an instruction fetch is + // not allowed. + // + // Note that allows_csr_fetch is a property of the block that contains a register, so a + // hierarchical model like the one at chip level may contain a mixture of both sorts of register. + function void get_nofetch_csrs(ref uvm_reg regs[$]); + uvm_reg all_regs[$]; + + regs.delete(); + get_registers(all_regs, UVM_HIER); + foreach (all_regs[i]) begin + if (!reg_allows_fetch(all_regs[i])) regs.push_back(all_regs[i]); + end + endfunction + + // Return true if there is at least one register in this reg block or a child block from which an + // instruction fetch is not allowed. + function bit has_nofetch_csrs(); + uvm_reg regs[$]; + get_nofetch_csrs(regs); + return regs.size() > 0; + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_field.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_field.sv new file mode 100644 index 0000000..c0eae27 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_field.sv @@ -0,0 +1,381 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// base register reg class which will be used to generate the reg field +class dv_base_reg_field extends uvm_reg_field; + + // The access value that the field had when it was configured. If the field can be locked, its + // access value might change to "RO". This value can be used to restore the original access on + // reset. + local string m_original_access; + + local dv_base_reg_field lockable_flds[$]; + local bit is_intr_test_fld; + local uvm_reg_data_t staged_val, committed_val, shadowed_val; + + // if this is lockable field, here is its corresponding regwen object + // if not, below 2 object will be null + local dv_base_reg_field regwen_fld; + local dv_base_lockable_field_cov lockable_field_cov; + + // This is used for get_field_by_name + string alias_name = ""; + + // If this field encodes a mubi, this field encodes special access modes such as W1C that cannot + // be captured with the regular access configuration, since UVM does not model such access modes + // correctly for mubis. + string mubi_access = ""; + + // Default mubi_width = 0 indicates this register field is not a mubi type. + protected int mubi_width; + + // variable for mubi coverage, which is only created when this is a mubi reg + dv_base_mubi_cov mubi_cov; + + // variable for shadowed coverage, which is only created when this is a shadowed reg + local dv_base_shadowed_field_cov shadowed_cov; + + // Set to 1 if prediction is intended to be carried out in the cip_base_scoreboard + bit has_prediction = 0; + + `uvm_object_utils(dv_base_reg_field) + `uvm_object_new + + // this is similar to get_name, but it gets the + // simple name of the aliased field instead. + function string get_alias_name (); + return this.alias_name; + endfunction: get_alias_name + + // this is similar to set_name, but it sets the + // simple name of the aliased field instead. + function void set_alias_name (string alias_name); + dv_base_reg register; + dv_base_reg_block reg_block; + `downcast(register, this.get_parent()) + register.field_alias_lookup[alias_name] = this.get_name(); + // We also add the name to the lookup table inside the reg_block to enable get_field_by_name at + // that level. Note: in order for the get_field_by_name function of dv_base_reg_block to + // produce meaningful results, all field names within the reg block have to be unique - which + // cannot always guaranteed. If the fields are not unique at that level, the get_field_by_name + // of dv_base_reg should be used instead. + `downcast(reg_block, register.get_parent()) + reg_block.field_alias_lookup[alias_name] = this.get_name(); + this.alias_name = alias_name; + endfunction: set_alias_name + + // Issue #5105: UVM forces the value member to be non-randomizable for certain access policies. + // We restore it in this extended class. + virtual function void configure(uvm_reg parent, + int unsigned size, + int unsigned lsb_pos, + string access, + string mubi_access, + bit volatile, + uvm_reg_data_t reset, + bit has_reset, + bit is_rand, + bit individually_accessible); + super.configure(.parent (parent), + .size (size), + .lsb_pos (lsb_pos), + .access (access), + .volatile (volatile), + .reset (reset), + .has_reset(has_reset), + .is_rand (is_rand), + .individually_accessible(individually_accessible)); + value.rand_mode(is_rand); + this.mubi_access = mubi_access; + this.m_original_access = access; + is_intr_test_fld = !(uvm_re_match("intr_test*", get_parent().get_name())); + shadowed_val = ~committed_val; + endfunction + + virtual function dv_base_reg get_dv_base_reg_parent(); + uvm_reg csr = get_parent(); + `downcast(get_dv_base_reg_parent, csr) + endfunction + + // Local helper function to reduce code in do_predict further below. + function uvm_reg_data_t mubi_or_hi (uvm_reg_data_t a, uvm_reg_data_t b); + import prim_mubi_pkg::*; + uvm_reg_data_t out; + case (mubi_width) + 4: out = uvm_reg_data_t'(mubi4_or_hi(mubi4_t'(a), mubi4_t'(b))); + 8: out = uvm_reg_data_t'(mubi8_or_hi(mubi8_t'(a), mubi8_t'(b))); + 12: out = uvm_reg_data_t'(mubi12_or_hi(mubi12_t'(a), mubi12_t'(b))); + 16: out = uvm_reg_data_t'(mubi16_or_hi(mubi16_t'(a), mubi16_t'(b))); + default: $error("Unsupported mubi width %d.", mubi_width); + endcase + return out; + endfunction: mubi_or_hi + + // Local helper function to reduce code in do_predict further below. + function uvm_reg_data_t mubi_and_hi (uvm_reg_data_t a, uvm_reg_data_t b); + import prim_mubi_pkg::*; + uvm_reg_data_t out; + case (mubi_width) + 4: out = uvm_reg_data_t'(mubi4_and_hi(mubi4_t'(a), mubi4_t'(b))); + 8: out = uvm_reg_data_t'(mubi8_and_hi(mubi8_t'(a), mubi8_t'(b))); + 12: out = uvm_reg_data_t'(mubi12_and_hi(mubi12_t'(a), mubi12_t'(b))); + 16: out = uvm_reg_data_t'(mubi16_and_hi(mubi16_t'(a), mubi16_t'(b))); + default: $error("Unsupported mubi width: %d.", mubi_width); + endcase + return out; + endfunction: mubi_and_hi + + // Local helper function to reduce code in do_predict further below. + function uvm_reg_data_t mubi_false (); + import prim_mubi_pkg::*; + uvm_reg_data_t out; + case (mubi_width) + 4: out = uvm_reg_data_t'(MuBi4False); + 8: out = uvm_reg_data_t'(MuBi8False); + 12: out = uvm_reg_data_t'(MuBi12False); + 16: out = uvm_reg_data_t'(MuBi16False); + default: $error("Unsupported mubi width: %d.", mubi_width); + endcase + return out; + endfunction: mubi_false + + virtual function void do_predict (uvm_reg_item rw, + uvm_predict_e kind = UVM_PREDICT_DIRECT, + uvm_reg_byte_en_t be = -1); + uvm_reg_data_t field_val = rw.value[0] & ((1 << get_n_bits())-1); + string access = get_access(); + + // update intr_state mirrored value if this is an intr_test reg + // if kind is UVM_PREDICT_DIRECT or UVM_PREDICT_READ, super.do_predict can handle + if (kind == UVM_PREDICT_WRITE && is_intr_test_fld) begin + uvm_reg_field intr_state_fld = get_intr_state_field(); + uvm_reg_data_t predict_val; + if (intr_state_fld.get_access == "RO") begin // status interrupt + predict_val = field_val | intr_state_fld.get_reset(); + end else begin // regular W1C interrupt + `DV_CHECK_STREQ(intr_state_fld.get_access, "W1C") + predict_val = field_val | `gmv(intr_state_fld); + end + // use UVM_PREDICT_READ to avoid uvm_warning due to UVM_PREDICT_DIRECT + void'(intr_state_fld.predict(predict_val, .kind(UVM_PREDICT_READ))); + + end else if (kind == UVM_PREDICT_WRITE && mubi_access inside {"W1S", "W1C", "W0C"}) + begin + // Some smoke checking of the byte enables. RTL does not latch anything if not all affected + // bytes of the field are enabled. Note that we still use UVM_PREDICT_WRITE further below + // since the underlying access is set to RW in the RAL model. + if (mubi_width <= 8 && be[0] || mubi_width > 8 && mubi_width <= 16 && &be[1:0]) begin + // In case this is a clearable MUBI field, we have to interpret the write value correctly. + // ICEBOX(#9273): Note that this just uses bitwise functions to update the value and does + // not rectify incorrect mubi values. At a later point, we should discuss if and how to + // tighten this up, as discussed on the linked issue. + case (mubi_access) + "W1S": rw.value[0] = this.mubi_or_hi(rw.value[0], `gmv(this)); + "W1C": rw.value[0] = this.mubi_and_hi(~rw.value[0], `gmv(this)); + "W0C": rw.value[0] = this.mubi_and_hi(rw.value[0], `gmv(this)); + default: ; // unreachable + endcase + end + end else if (kind == UVM_PREDICT_READ && mubi_access == "RC") begin + rw.value[0] = this.mubi_false(); + end + super.do_predict(rw, kind, be); + endfunction + + // when use UVM_PREDICT_WRITE and the CSR access is WO, this function will return the default + // val of the register, rather than the written value + virtual function uvm_reg_data_t XpredictX(uvm_reg_data_t cur_val, + uvm_reg_data_t wr_val, + uvm_reg_map map); + + if (get_access(map) == "WO") return get_reset(); + else return super.XpredictX(cur_val, wr_val, map); + endfunction + + virtual function string get_original_access(); + return m_original_access; + endfunction + + // Return a mask of valid bits in the field. + virtual function uvm_reg_data_t get_field_mask(); + get_field_mask = (1'b1 << this.get_n_bits()) - 1; + get_field_mask = get_field_mask << this.get_lsb_pos(); + endfunction + + // Return a mask of read-only bits in the field. + virtual function uvm_reg_data_t get_ro_mask(); + bit is_ro = (this.get_access() == "RO"); + get_ro_mask = (is_ro << this.get_n_bits()) - is_ro; + get_ro_mask = get_ro_mask << this.get_lsb_pos(); + endfunction + + // Lock the write access to this field. + // This only pertains to a lockable field. It is invoked in the `set_lockable_flds_access()` + // method of its corresponding lock (wen) field. + local function void set_fld_access(bit lock); + if (lock) void'(this.set_access("RO")); + else void'(this.set_access(m_original_access)); + endfunction + + // If input is a reg, add all fields under the reg; if input is a field, add the specific field. + function void add_lockable_reg_or_fld(uvm_object lockable_obj); + dv_base_reg_field flds[$]; + uvm_reg_block ral = this.get_parent().get_parent(); + `DV_CHECK_EQ_FATAL(ral.is_locked(), 0, "RAL is locked, cannot add lockable reg or fld!") + get_flds_from_uvm_object(lockable_obj, `gfn, flds); + foreach (flds[i]) begin + lockable_flds.push_back(flds[i]); + flds[i].regwen_fld = this; + end + endfunction + + function void create_lockable_fld_cov(); + lockable_field_cov = dv_base_lockable_field_cov::type_id::create(`gfn); + endfunction + + function void create_mubi_cov(int width); + mubi_cov = dv_base_mubi_cov::type_id::create(`gfn); + mubi_cov.create_cov(width); + endfunction + + function void create_shadowed_fld_cov(); + shadowed_cov = dv_base_shadowed_field_cov::type_id::create(`gfn); + endfunction + + function void create_cov(); + string csr_name = this.get_parent().get_name(); + if (mubi_width > 0) create_mubi_cov(mubi_width); + if (regwen_fld != null) create_lockable_fld_cov(); + if (!uvm_re_match("*_shadowed", csr_name)) create_shadowed_fld_cov(); + endfunction + + // Returns true if this field can lock the specified register/field, else return false. + // If lockable register is partially lockable (only certain field is lockable), this method will + // still return true. + function bit locks_reg_or_fld(uvm_object obj); + dv_base_reg_field flds[$]; + get_flds_from_uvm_object(obj, `gfn, flds); + foreach (flds[i]) begin + if (flds[i] inside {lockable_flds}) return 1; + end + return 0; + endfunction + + function bit is_wen_fld(); + return (lockable_flds.size() > 0); + endfunction + + // If lock is set to 1, lockable fields access policy will be set to RO access. + // If lock resets to 0, lockable fields will be set back to their original accesses. + function void set_lockable_flds_access(bit lock); + foreach (lockable_flds[i]) lockable_flds[i].set_fld_access(lock); + endfunction + + function void get_lockable_flds(ref dv_base_reg_field lockable_flds_q[$]); + lockable_flds_q = lockable_flds; + endfunction + + // Return if the RAL block is locked or not. + function bit is_locked(); + uvm_reg_block blk = this.get_parent().get_parent(); + return blk.is_locked(); + endfunction + + // If the register field is a mubi type, set the mubi width before the RAL is locked. + function void set_mubi_width(int width); + if (is_locked()) `uvm_fatal(`gfn, "Cannot set mubi width when the block is locked") + mubi_width = width; + endfunction + + function int get_mubi_width(); + return mubi_width; + endfunction + + // shadow register field read will clear its phase tracker + virtual task post_read(uvm_reg_item rw); + if (rw.status == UVM_IS_OK) begin + dv_base_reg parent_csr = get_dv_base_reg_parent(); + parent_csr.clear_shadow_wr_staged(); + + if (lockable_field_cov != null) lockable_field_cov.post_read(); + end + endtask + + virtual task post_write(uvm_reg_item rw); + if (rw.status == UVM_IS_OK) begin + uvm_reg_data_t field_val = rw.value[0] & ((1 << get_n_bits()) - 1); + + if (lockable_field_cov != null) lockable_field_cov.post_write(field_val, `gmv(regwen_fld)); + + if (mubi_cov != null) mubi_cov.sample(field_val); + end + endtask + + function bit get_shadow_storage_err(); + uvm_reg_data_t mask = (1 << get_n_bits()) - 1; + uvm_reg_data_t shadowed_val_temp = (~shadowed_val) & mask; + uvm_reg_data_t committed_val_temp = committed_val & mask; + `uvm_info(`gfn, $sformatf("shadow_val %0h, commmit_val %0h", shadowed_val_temp, + committed_val_temp), UVM_HIGH) + sample_shadow_field_cov(.storage_err(1)); + return shadowed_val_temp != committed_val_temp; + endfunction + + function void sample_shadow_field_cov(bit update_err = 0, bit storage_err = 0); + if (shadowed_cov != null) shadowed_cov.shadow_field_errs_cg.sample(update_err, storage_err); + endfunction + + function void update_staged_val(uvm_reg_data_t val); + staged_val = val; + endfunction + + function uvm_reg_data_t get_staged_val(); + return staged_val; + endfunction + + function void update_shadowed_val(uvm_reg_data_t val); + shadowed_val = val; + endfunction + + function void update_committed_val(uvm_reg_data_t val); + committed_val = val; + endfunction + + function uvm_reg_data_t get_committed_val(); + return committed_val; + endfunction + + // override RAL's reset function to support enable registers + // when reset issued - the lockable field's access will be reset to original access + virtual function void reset(string kind = "HARD"); + super.reset(kind); + set_fld_access(0); + committed_val = get_mirrored_value(); + shadowed_val = ~committed_val; + if (lockable_field_cov != null) lockable_field_cov.reset(get_reset()); + endfunction + + // this function can only be called when this reg is intr_test reg + // Example: ral.intr_test.get_intr_state_field() + local function uvm_reg_field get_intr_state_field(); + uvm_reg_block blk = get_parent().get_parent(); + uvm_reg intr_state_csr; + uvm_reg_field fields[$]; + string intr_state_csr_name; + string intr_test_csr_name = get_parent().get_name(); + bit is_intr_state_csr = !(uvm_re_match("intr_test*", intr_test_csr_name)); + + `DV_CHECK_EQ_FATAL(is_intr_state_csr, 1) + + // intr_enable and intr_state have the same suffix + intr_state_csr_name = str_utils_pkg::str_replace(intr_test_csr_name, "test", "state"); + + intr_state_csr = blk.get_reg_by_name(intr_state_csr_name); + intr_state_csr.get_fields(fields); + + // the field location for intr_state and intr_test should be the same + return fields[get_lsb_pos()]; + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_map.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_map.sv new file mode 100644 index 0000000..ee748f5 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_map.sv @@ -0,0 +1,9 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// base register reg class which will be used to generate the reg map +class dv_base_reg_map extends uvm_reg_map; + `uvm_object_utils(dv_base_reg_map) + `uvm_object_new +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_pkg.sv new file mode 100644 index 0000000..e64f2de --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_reg_pkg.sv @@ -0,0 +1,145 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package dv_base_reg_pkg; + // dep packages + import uvm_pkg::*; + import dv_utils_pkg::*; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + // global paramters for number of csr tests (including memory test) + parameter uint NUM_CSR_TESTS = 4; + + // csr field struct - hold field specific params + typedef struct { + uvm_reg csr; + uvm_reg_field field; + uvm_reg_data_t mask; + uint shift; + } csr_field_t; + + // csr exclusion indications + typedef enum bit [2:0] { + CsrNoExcl = 3'b000, // no exclusions + CsrExclInitCheck = 3'b001, // exclude csr from init val check + CsrExclWriteCheck = 3'b010, // exclude csr from write-read check + CsrExclCheck = 3'b011, // exclude csr from init or write-read check + CsrExclWrite = 3'b100, // exclude csr from write + CsrExclAll = 3'b111 // exclude csr from init or write or write-read check + } csr_excl_type_e; + + // csr test types + typedef enum bit [NUM_CSR_TESTS-1:0] { + CsrInvalidTest = 4'h0, + // elementary test types + CsrHwResetTest = 4'h1, + CsrRwTest = 4'h2, + CsrBitBashTest = 4'h4, + CsrAliasingTest = 4'h8, + // combinational test types (combinations of the above), used for exclusion tagging + CsrNonInitTests = 4'he, // all but HwReset test + CsrAllTests = 4'hf // all tests + } csr_test_type_e; + + typedef enum bit[2:0] { + // If it's a shadow reg, BkdrRegPathRtl is the path to committed reg + BkdrRegPathRtl, // backdoor path for reg's val in RTL + BkdrRegPathRtlShadow, // backdoor path for shadow reg's shadow val in RTL + BkdrRegPathGls, // backdoor path for reg's val in GLS + BkdrRegPathGlsShdow // backdoor path for shadow reg's shadow val in GLS + } bkdr_reg_path_e; + + // Forward-declare class types for the functions below. + typedef class dv_base_reg_block; + typedef class dv_base_reg; + typedef class dv_base_reg_field; + + // This function attempts to cast a given uvm_object ptr into uvm_reg or uvm_reg_field. If cast + // is successful on either, then set the appropriate csr_field_t return values. + function automatic csr_field_t decode_csr_or_field(input uvm_object ptr); + uvm_reg csr; + uvm_reg_field fld; + csr_field_t result; + + if ($cast(csr, ptr)) begin + // return csr object with null field; set the mask to the width's all 1s and shift to 0 + result.csr = csr; + result.mask = (1 << csr.get_n_bits()) - 1; + result.shift = 0; + end + else if ($cast(fld, ptr)) begin + // return csr field object; return the appropriate mask and shift values + result.csr = fld.get_parent(); + result.field = fld; + result.mask = (1 << fld.get_n_bits()) - 1; + result.shift = fld.get_lsb_pos(); + end + else begin + `uvm_fatal($sformatf("%m"), $sformatf("ptr %0s is not of type uvm_reg or uvm_reg_field", + ptr.get_full_name())) + end + return result; + endfunction : decode_csr_or_field + + function automatic void get_flds_from_uvm_object(input uvm_object obj, + input string msg = "dv_base_reg_pkg", + ref dv_base_reg_field flds[$]); + dv_base_reg csr; + dv_base_reg_field fld; + + flds.delete(); + if ($cast(csr, obj)) begin + csr.get_dv_base_reg_fields(flds); + end else if ($cast(fld, obj)) begin + flds.push_back(fld); + end else begin + `uvm_fatal($sformatf("%m"), $sformatf("obj %0s is not of type uvm_reg or uvm_reg_field", + obj.get_full_name())) + end + endfunction : get_flds_from_uvm_object + + // mask and shift data to extract the value specific to that supplied field + function automatic uvm_reg_data_t get_field_val(uvm_reg_field field, + uvm_reg_data_t value); + uvm_reg_data_t mask = (1 << field.get_n_bits()) - 1; + uint shift = field.get_lsb_pos(); + get_field_val = (value >> shift) & mask; + endfunction : get_field_val + + // Returns a mask value from the provided fields. All fields must belong to the same CSR. + function automatic uvm_reg_data_t get_mask_from_fields(uvm_reg_field fields[$]); + uvm_reg_data_t mask = '0; + uvm_reg csr; + if (fields.size() == 0) return '1; + foreach (fields[i]) begin + uvm_reg_data_t fmask; + uint fshift; + if (csr == null) csr = fields[i].get_parent(); + else if (csr != fields[i].get_parent()) begin + `uvm_fatal($sformatf("%m") , $sformatf({"The provided fields belong to at least two" + ," different CSRs: ", + "%s, %s. All fields must belong to the same CSR"}, + fields[i-1].`gfn, fields[i].`gfn)) + end + fmask = (1 << fields[i].get_n_bits()) - 1; + fshift = fields[i].get_lsb_pos(); + mask |= fmask << fshift; + end + return mask; + endfunction + + `include "csr_excl_item.sv" + `include "dv_base_lockable_field_cov.sv" + `include "dv_base_shadowed_field_cov.sv" + `include "dv_base_mubi_cov.sv" + `include "dv_base_reg_field.sv" + `include "dv_base_reg.sv" + `include "dv_base_mem.sv" + `include "dv_base_reg_block.sv" + `include "dv_base_reg_map.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_shadowed_field_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_shadowed_field_cov.sv new file mode 100644 index 0000000..bae4a6a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_base_reg/dv_base_shadowed_field_cov.sv @@ -0,0 +1,29 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// coverage object of shadowed errors - update and storage errors. + +class dv_base_shadowed_field_cov extends uvm_object; + `uvm_object_utils(dv_base_shadowed_field_cov) + + covergroup shadow_field_errs_cg(string name) with function sample(bit update_err = 0, + bit storage_err = 0); + option.per_instance = 1; + option.name = name; + + cp_update_err: coverpoint update_err { + bins update_err = {1}; + } + + cp_storage_err: coverpoint storage_err { + bins storage_err = {1}; + } + endgroup + + // use reg_field name as this name + function new(string name = ""); + shadow_field_errs_cg = new($sformatf("%0s_shadowed_errs_cov", name)); + endfunction : new + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/README.md b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/README.md new file mode 100644 index 0000000..b2836f2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/README.md @@ -0,0 +1,52 @@ +# DV Library Classes + +# DV library classes + +## Overview +The DV library classes form the base layer / framework for constructing UVM +testbenches. These classes provide features (settings, methods, hooks and other +constructs used in verification) that are generic enough to be reused across +all testbenches. + +In this doc, we will capture some of the most salient / frequently used features +in extended classes. These classes are being updated frequently. So, for a more +detailed understanding, please read the class definitions directly. + +The DV library classes fall into 3 categories - UVM RAL (register abstraction +layer), UVM agent, and UVM environment extensions. + +### UVM RAL extensions +The RAL model generated using the [reggen](../../../../util/reggen/doc/setup_and_use.md) tool +extend from these classes. These themselves extend from the corresponding RAL +classes provided in UVM. + +#### `dv_base_reg_field` +Currently, this class does not provide any additional features. One of the +features planned for future is setting exclusion tags at the field level for the +CSR suite of tests that will be extracted automatically from the Hjson-based +IP CSR specification. + +#### `dv_base_reg` +This class provides the following functions to support verification: +* `gen_n_used_bits()`: This function returns the actual number of bits used in + the CSR (sum of all available field widths). +* `get_msb_pos()`: This function returns the MSB bit position of all available fields. + The CSR either ends at this bit or has reserved / invalid bits beyond this bit. + +#### `dv_base_reg_block` +* ` build(uvm_reg_addr_t base_addr)`: This function is implemented as a pseudo + pure virtual function (returns a fatal error if called directly). It is used + for building the complete RAL model. For a polymorphic approach, the DV user + can use this class handle to create the extended (IP specific) class instance + and call this function to build the actual RAL model. This is exactly how it + is done in [dv_base_env_cfg](#dv_base_env_cfg). + +#### `dv_base_reg_map` +Currently, this class does not provide any additional features. Having this +extension provides an opportunity to add common features in future. + +### UVM Agent extensions +TODO + +### UVM Environment extensions +TODO diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/bit_toggle_cg_wrap.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/bit_toggle_cg_wrap.sv new file mode 100644 index 0000000..d27bf01 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/bit_toggle_cg_wrap.sv @@ -0,0 +1,42 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A class wrapping a covergroup that tracks a single bit signal (and covers transitions with it +// toggling). +// +// Using a class like this allows the covergroup to be instantiated in multiple places (and in +// arrays). + +class bit_toggle_cg_wrap; + + // A covergroup that tracks the value of some single-bit value (with associated coverpoint + // cp_value). Tracking it explicitly with functional coverage allows transition bins (defined in + // cp_transitions). + // + // If toggle_cov_en is true, the transitions in cp_transitions have nonzero weight. + covergroup bit_toggle_cg(string name, bit toggle_cov_en = 1) + with function sample(bit value); + + option.per_instance = 1; + option.name = name; + + cp_value: coverpoint value; + cp_transitions: coverpoint value { + option.weight = toggle_cov_en; + bins rising = (0 => 1); + bins falling = (1 => 0); + } + endgroup : bit_toggle_cg + + function new(string name, bit toggle_cov_en = 1); + bit_toggle_cg = new(name, toggle_cov_en); + endfunction : new + + // A wrapper around bit_toggle_cg.sample, allowing code using this class to call + // the_class_instance.sample() in the same way as it would have sampled the underlying covergroup. + function void sample(bit value); + bit_toggle_cg.sample(value); + endfunction : sample + +endclass : bit_toggle_cg_wrap diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env.sv new file mode 100644 index 0000000..97716af --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env.sv @@ -0,0 +1,94 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_env #(type CFG_T = dv_base_env_cfg, + type VIRTUAL_SEQUENCER_T = dv_base_virtual_sequencer, + type SCOREBOARD_T = dv_base_scoreboard, + type COV_T = dv_base_env_cov) extends uvm_env; + `uvm_component_param_utils(dv_base_env #(CFG_T, VIRTUAL_SEQUENCER_T, SCOREBOARD_T, COV_T)) + + CFG_T cfg; + VIRTUAL_SEQUENCER_T virtual_sequencer; + SCOREBOARD_T scoreboard; + COV_T cov; + + `uvm_component_new + + virtual function void build_phase(uvm_phase phase); + string ral_models[$]; + + super.build_phase(phase); + + // Get an env_cfg. This may have actually already been supplied before this environment's + // build_phase. That might be done by the test or by higher-level environment (if this + // environment represents a block that is being used in a larger subsystem- or chip-level + // environment). If the cfg has not been supplied, look it up uvm_config_db. + if (cfg == null) begin + if (!uvm_config_db#(CFG_T)::get(this, "", "cfg", cfg)) begin + `uvm_fatal(`gfn, $sformatf("failed to get %s from uvm_config_db", cfg.get_type_name())) + end + end + + // Make sure the map in cfg from RAL name to clk_rst_if is populated. Copy the clock frequencies + // chosen by cfg to the interfaces. + ral_models = cfg.get_ral_model_names(); + if (ral_models.size() > 0) begin + string default_ral_name = cfg.ral.get_type_name(); + foreach (ral_models[i]) begin + string ral_name = ral_models[i]; + configure_clk_rst_vif(ral_name, (ral_name == default_ral_name)); + end + + // assign default clk_rst_vif + `DV_CHECK_FATAL(cfg.clk_rst_vifs.exists(default_ral_name)) + cfg.clk_rst_vif = cfg.clk_rst_vifs[default_ral_name]; + end else begin + // no RAL model, get the default clk_rst_vif for the block + // such as xbar, it doesn't has ral model, but it also needs a default clk_rst_vif + if (cfg.clk_rst_vif == null && + !uvm_config_db#(virtual clk_rst_if)::get(this, "", "clk_rst_vif", cfg.clk_rst_vif)) begin + `uvm_fatal(get_full_name(), "Failed to get clk_rst_if from uvm_config_db") + end + cfg.clk_rst_vif.set_freq_mhz(cfg.clk_freq_mhz); + end + + // create components + if (cfg.en_cov) begin + cov = COV_T::type_id::create("cov", this); + cov.cfg = cfg; + end + + if (cfg.is_active) begin + virtual_sequencer = VIRTUAL_SEQUENCER_T::type_id::create("virtual_sequencer", this); + virtual_sequencer.cfg = cfg; + virtual_sequencer.cov = cov; + end + + // scb also monitors the reset and call cfg.reset_asserted/reset_deasserted for reset + scoreboard = SCOREBOARD_T::type_id::create("scoreboard", this); + scoreboard.cfg = cfg; + scoreboard.cov = cov; + endfunction + + // If cfg doesn't already have the vif, look up a clk_rst_if for ral_name in uvm_config_db. Either + // way, copy the selected clock frequency to the interface. + // + // This should be called after the frequency has been selected for ral_name (which happens as part + // of randomisation after setup with initialize()) + local function void configure_clk_rst_vif(string ral_name, bit is_default_ral_name); + string if_name = is_default_ral_name ? "clk_rst_vif" : {"clk_rst_vif_", ral_name}; + + // If cfg doesn't already have the interface look one up in the config_db + if (!cfg.clk_rst_vifs.exists(ral_name) && + !uvm_config_db#(virtual clk_rst_if)::get(this, "", + if_name, cfg.clk_rst_vifs[ral_name])) begin + `uvm_fatal(get_full_name(), + $sformatf("No clk_rst_if for %0s (which would be called %0s) in uvm_config_db", + ral_name, if_name)) + end + + cfg.clk_rst_vifs[ral_name].set_freq_mhz(cfg.clk_freqs_mhz[ral_name]); + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv new file mode 100644 index 0000000..d28606c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv @@ -0,0 +1,347 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A base environment configuration that is used for all OpenTitan environments. + +class dv_base_env_cfg #(type RAL_T = dv_base_reg_block) extends uvm_object; + + // True if the environment is active (and thus drives sequences items to the dut). This is the + // default. + bit is_active = 1; + + // True if the scoreboard should be enabled. If it is false, the scoreboard still runs, but should + // ignore its checks. + bit en_scb = 1; + + // True if the scoreboard should check memory read transactions and predict memory updates from + // write transactions. + bit en_scb_mem_chk = 1; + + // Enable functional coverage collection. This causes monitors and scoreboards to collect coverage + // (through a dv_base_env_cov object). + bit en_cov = 0; + + // Enable CDC instrumentation + bit en_dv_cdc = 0; + + // A bit that is true if the environment is currently under reset. This should controlled by + // calling the reset_asserted and reset_deasserted functions. By default, + // dv_base_scoreboard::monitor_reset maintains this value. + bit under_reset = 0; + + // A flag to show that the initialize_ral method has been called. This is protected (rather than + // local) to allow specialised environments to set it to avoid the initialize_ral method being + // called. + protected bit is_initialized = 0; + + // The scope and runtime of a existing test can be reduced by setting this variable. This is + // useful to keep the runtime down especially in time-sensitive runs such as CI, which is meant + // to check the code health and not find design bugs. It is set via plusarg and retrieved in + // `dv_base_test`. + bit smoke_test = 0; + + // If this is true, all UVCs should run with zero delays, which creates a high bandwidth test. + rand bit zero_delays; + + // The type_name of the base RAL type (RAL_T). This is exposed explicitly, rather than being + // accessed through RAL_T::type_name, because this allows subclasses of dv_base_env_cfg to + // override the base RAL type without messing up the parameterized class type. + // + // This string will be added to ral_model_names at the start of the initialize function (which is + // after a derived class can have overridden it). + protected string ral_type_name = RAL_T::type_name; + + // The set of the names of RAL models that should exist by the end of `initialize_ral`. + // Related agents and adapters will be created in the environment as well as connecting them with + // the scoreboard. + // + // The set is implemented as an associative array whose keys are elements of the set (and whose + // values contain no information). + // + // The model names (keys of ral_model_names) are used as indices into associative arrays for + // ral_models, clk_rst_vifs and clk_freqs_mhz. + // + // To add another RAL model, a subclass of dv_base_env_cfg must make sure that the model's name is + // added to this set before running dv_base_env_cfg::initialize_ral. One way to do this is to + // implement the function itself and update the set before calling super.initialize_ral(). + protected bit ral_model_names[string]; + + typedef string string_queue_t[$]; + + function string_queue_t get_ral_model_names(); + string_queue_t ret; + foreach (ral_model_names[name]) ret.push_back(name); + return ret; + endfunction + + // A RAL model for each name in ral_model_names. + dv_base_reg_block ral_models[string]; + + // A clock and reset interface for each name in ral_model_names. An item is the clock and reset + // that should be used for the associated TL interface. + virtual clk_rst_if clk_rst_vifs[string]; + + // Clock frequencies for the TL interfaces indexed by the keys of ral_model_names. + rand uint clk_freqs_mhz[string]; + + // The "default" RAL's register model. This corresponds to RAL_T::type_name as a model name, and + // the variable is of type RAL_T (a more specialised class) to simplify access. + RAL_T ral; + + // The interface for the clock and reset assoicated with the default RAL. + virtual clk_rst_if clk_rst_vif; + + // The frequency of the clock and reset assoicated with the default RAL. + rand uint clk_freq_mhz; + + // Set zero_delays 40% of the time + extern constraint zero_delays_c; + + // Constrain frequencies of the various clocks. + extern constraint clk_freq_mhz_c; + + `uvm_object_param_utils_begin(dv_base_env_cfg #(RAL_T)) + `uvm_field_int (is_active, UVM_DEFAULT) + `uvm_field_int (en_scb, UVM_DEFAULT) + `uvm_field_int (en_scb_mem_chk, UVM_DEFAULT) + `uvm_field_int (en_cov, UVM_DEFAULT) + `uvm_field_int (en_dv_cdc, UVM_DEFAULT) + `uvm_field_int (smoke_test, UVM_DEFAULT) + `uvm_field_int (zero_delays, UVM_DEFAULT) + `uvm_field_aa_int_string (ral_model_names, UVM_DEFAULT) + `uvm_field_aa_object_string (ral_models, UVM_DEFAULT) + `uvm_field_aa_int_string (clk_freqs_mhz, UVM_DEFAULT) + `uvm_object_utils_end + + extern function new (string name=""); + + extern function void pre_randomize(); + extern function void post_randomize(); + + // Configure whether this env_cfg is active + // + // Use this, rather than directly setting is_active, in order that any agents' configurations are + // also updated. + extern virtual function void set_is_active(bit active); + + // Initialise the object with RAL models and set it up for randomisation + // + // The addr_width, data_width and be_width arguments are used to configure the analogous fields of + // the dv_base_reg_block instances that are created. + // + // If inherit_ral_models is true, the object is already expected to have the RAL models (possibly + // from a higher level of the testbench). If so, csr_base_addr should be ignored, but the other + // initialisation for the object is still done. + // + // This function is virtual, allowing subclasses to set up list_of_alerts and num_interrupts. + extern virtual function void initialize_ral(int unsigned addr_width, + int unsigned data_width, + int unsigned be_width, + bit inherit_ral_models); + + // Set pre-build RAL knobs. + // + // This method enables setting pre-build config knobs that can be used to control how the RAL + // sub-structures are created. + extern protected virtual function void pre_build_ral_settings(dv_base_reg_block ral); + + // Perform post-build, pre-lock modifications to the RAL. + // + // For some registers / fields, the correct access policies or reset values may not be set. Fixes + // like those can be made with this method. + extern protected virtual function void post_build_ral_settings(dv_base_reg_block ral); + + // Update the under_reset flag to match the fact that reset has been asserted. This is currently + // driven by dv_base_scoreboard::monitor_reset. + extern virtual function void reset_asserted(); + + // Update the under_reset flag to match the fact that reset is no longer asserted. This is + // currently driven by dv_base_scoreboard::monitor_reset. + extern virtual function void reset_deasserted(); + + // Create missing RAL models and set their base addresses based on the supplied arg. + // + // The addr_width, data_width and be_width arguments are used to configure the analogous fields of + // the dv_base_reg_block instances that are created. + extern local function void make_ral_models(int unsigned addr_width, + int unsigned data_width, + int unsigned be_width); + + // Create the named RAL model and give it a randomised base address. + // + // The addr_width, data_width and be_width arguments are used to configure the analogous fields of + // the dv_base_reg_block that is created. + extern local function void make_ral_model(string ral_model_name, + int unsigned addr_width, + int unsigned data_width, + int unsigned be_width); + + // Create the named register block. This protected function is virtual to allow subclasses to + // customise how the register block is created. + extern protected virtual function dv_base_reg_block create_ral_by_name(string name); +endclass + +constraint dv_base_env_cfg::zero_delays_c { + zero_delays dist {1'b0 := 6, 1'b1 := 4}; +} + +constraint dv_base_env_cfg::clk_freq_mhz_c { + `DV_COMMON_CLK_CONSTRAINT(clk_freq_mhz) + foreach (clk_freqs_mhz[i]) { + `DV_COMMON_CLK_CONSTRAINT(clk_freqs_mhz[i]) + } +} + +function dv_base_env_cfg::new (string name=""); + super.new(name); +endfunction + +function void dv_base_env_cfg::pre_randomize(); + if (!is_initialized) `uvm_fatal(`gfn, "Run initialize_ral() before randomizing this object.") +endfunction + +function void dv_base_env_cfg::post_randomize(); + if (clk_freqs_mhz.size > 0) begin + `DV_CHECK_FATAL(clk_freqs_mhz.exists(ral_type_name)) + clk_freqs_mhz[ral_type_name] = clk_freq_mhz; + end +endfunction + +function void dv_base_env_cfg::set_is_active(bit active); + is_active = active; +endfunction + +function void dv_base_env_cfg::initialize_ral(int unsigned addr_width, + int unsigned data_width, + int unsigned be_width, + bit inherit_ral_models); + if (is_initialized) `uvm_fatal(`gfn, "Cannot call initialize_ral when already initialized") + + // Add ral_type_name to ral_model_names (we just need the key in the array; the value has no + // meaning) + ral_model_names[ral_type_name] = 1'b0; + + is_initialized = 1'b1; + + if (inherit_ral_models) begin + // If inherit_ral_models is true then there should already be a RAL model associated with each + // name (including ral_type_name). Check that there is. + foreach (ral_model_names[ral_name]) begin + if (!ral_models.exists(ral_name)) begin + `uvm_fatal(get_name(), + $sformatf("inherit_ral_models is true but there is no RAL model at %0s.", + ral_name)) + end + end + end else begin + // As inherit_ral_models is false, we need to build them here. + make_ral_models(addr_width, data_width, be_width); + end + + // At this point, each RAL model will exist in the ral_models associative array. As a convenience, + // set the "ral" class variable to the ral model defined for this type. This should have been + // created with some subtype of RAL_T. + if (!$cast(ral, ral_models[ral_type_name])) begin + `uvm_fatal(get_name(), + $sformatf("The register model stored under %0s cannot be cast to type RAL_T.", + ral_type_name)) + end + + // add items to clk_freqs_mhz before randomizing it + foreach (ral_model_names[name]) begin + clk_freqs_mhz[name] = 0; + end +endfunction + +function void dv_base_env_cfg::pre_build_ral_settings(dv_base_reg_block ral); + // This is an empty function that a subclass can override +endfunction + +function void dv_base_env_cfg::post_build_ral_settings(dv_base_reg_block ral); + // This is an empty function that a subclass can override +endfunction + +function void dv_base_env_cfg::reset_asserted(); + this.under_reset = 1; + csr_utils_pkg::reset_asserted(); +endfunction + +function void dv_base_env_cfg::reset_deasserted(); + this.under_reset = 0; + csr_utils_pkg::reset_deasserted(); +endfunction + +function void dv_base_env_cfg::make_ral_models(int unsigned addr_width, + int unsigned data_width, + int unsigned be_width); + foreach (ral_model_names[name]) begin + make_ral_model(name, addr_width, data_width, be_width); + end + + if (!ral_models.exists(ral_type_name)) begin + `uvm_fatal(get_name(), + $sformatf("The generated RAL models don't include ral_type_name=%0s.", + ral_type_name)) + end +endfunction + +function void dv_base_env_cfg::make_ral_model(string ral_model_name, + int unsigned addr_width, + int unsigned data_width, + int unsigned be_width); + dv_base_reg_block reg_blk; + + if (ral_models.exists(ral_model_name)) begin + // If there is already a model for this name, there's nothing to do (probably because the + // env_cfg has already been initialised) + return; + end + + // If a model for this name doesn't already exist, we should make one. + reg_blk = create_ral_by_name(ral_model_name); + + // Build the register block with an arbitrary base address. We'll randomize it once we've locked + // the model (and thus know the alignment requirements). + pre_build_ral_settings(reg_blk); + reg_blk.build(.base_addr(0), + .csr_excl(null), + .addr_width(addr_width), + .data_width(data_width), + .be_width(be_width)); + post_build_ral_settings(reg_blk); + + // Lock the model. One side effect is that this will compute an initial address map (with offset + // zero). + reg_blk.lock_model(); + + // Now pick a randomized base address. This has alignment requirements. Round up the largest + // address in the initial address map to the next power of two: the base address must be divisible + // by that power of two, ensuring that addresses within the block have predictable low bits. + reg_blk.set_randomized_base_addr(); + + if (reg_blk.get_name() == ral_type_name) `downcast(ral, reg_blk) + + ral_models[ral_model_name] = reg_blk; +endfunction + +function dv_base_reg_block dv_base_env_cfg::create_ral_by_name(string name); + uvm_object obj; + uvm_factory factory; + dv_base_reg_block ral; + + factory = uvm_factory::get(); + obj = factory.create_object_by_name(.requested_type_name(name), .name(name)); + if (obj == null) begin + // print factory overrides to help debug + factory.print(); + `uvm_fatal(`gfn, + $sformatf({"Could not create %0s as a RAL model. ", + "See above for a list of type/instance overrides"}, + name)) + end + if (!$cast(ral, obj)) begin + `uvm_fatal(`gfn, $sformatf("Cast failed - %0s is not a dv_base_reg_block", name)) + end + return ral; +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cov.sv new file mode 100644 index 0000000..5e9bb28 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cov.sv @@ -0,0 +1,16 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A base class for coverage collection. This base class only really contains the CFG_T handle, that +// points to the config for the environment in use. + +class dv_base_env_cov #(type CFG_T = dv_base_env_cfg) extends uvm_component; + `uvm_component_param_utils(dv_base_env_cov #(CFG_T)) + + CFG_T cfg; + + function new(string name, uvm_component parent); + super.new(name, parent); + endfunction +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_scoreboard.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_scoreboard.sv new file mode 100644 index 0000000..a9a5b6c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_scoreboard.sv @@ -0,0 +1,81 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_scoreboard #(type RAL_T = dv_base_reg_block, + type CFG_T = dv_base_env_cfg, + type COV_T = dv_base_env_cov) extends uvm_component; + `uvm_component_param_utils(dv_base_scoreboard #(RAL_T, CFG_T, COV_T)) + + CFG_T cfg; + RAL_T ral; + COV_T cov; + + bit obj_raised = 1'b0; + bit under_pre_abort = 1'b0; + + `uvm_component_new + + virtual function void build_phase(uvm_phase phase); + super.build_phase(phase); + ral = cfg.ral; + endfunction + + virtual task run_phase(uvm_phase phase); + super.run_phase(phase); + fork + monitor_reset(); + sample_resets(); + join_none + endtask + + virtual task monitor_reset(); + forever begin + if (!cfg.clk_rst_vif.rst_n) begin + `uvm_info(`gfn, "reset occurred", UVM_HIGH) + cfg.reset_asserted(); + @(posedge cfg.clk_rst_vif.rst_n); + reset(); + cfg.reset_deasserted(); + csr_utils_pkg::clear_outstanding_access(); + `uvm_info(`gfn, "out of reset", UVM_HIGH) + end + else begin + // wait for a change to rst_n + @(cfg.clk_rst_vif.rst_n); + end + end + endtask + + virtual task sample_resets(); + // Do nothing, actual coverage collection is under extended classes. + endtask + + virtual function void reset(string kind = "HARD"); + // reset the ral model + foreach (cfg.ral_models[i]) cfg.ral_models[i].reset(kind); + endfunction + + virtual function void pre_abort(); + super.pre_abort(); + + // In UVM, a fatal error normally aborts the test completely and skips the check phase. However, + // it's sometimes helpful to run that phase on the scoreboard anyway (it might make it easier to + // debug whatever went wrong), so we do that here. + // + // We only run the check phase if we were in the run phase: if something went wrong in the build + // or connect phase, there's not much point in "checking the run" further. We also have to be + // careful to avoid an infinite loop, so we set a flag to avoid doing this a second time if we + // have errors in the check phase. + if (has_uvm_fatal_occurred() && + !under_pre_abort && + m_current_phase != null && + m_current_phase.is(uvm_run_phase::get())) begin + + under_pre_abort = 1; + check_phase(m_current_phase); + under_pre_abort = 0; + end + endfunction : pre_abort + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_test.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_test.sv new file mode 100644 index 0000000..953a1ea --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_test.sv @@ -0,0 +1,163 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_test #(type CFG_T = dv_base_env_cfg, + type ENV_T = dv_base_env) extends uvm_test; + `uvm_component_param_utils(dv_base_test #(CFG_T, ENV_T)) + + ENV_T env; + CFG_T cfg; + bit run_test_seq = 1'b1; + string test_seq_s; + + uint max_quit_count = 1; + uint64 test_timeout_ns = 200_000_000; // 200ms + uint drain_time_ns = 2_000; // 2us + bit poll_for_stop = 1'b0; + uint poll_for_stop_interval_ns = 1000; + bit print_topology = 1'b0; + + `uvm_component_new + + virtual function void build_phase(uvm_phase phase); + uvm_object_wrapper cfg_type; + uvm_object base_cfg; + + dv_report_server m_dv_report_server = new(); + dv_report_catcher m_report_catcher; + uvm_report_server::set_server(m_dv_report_server); + + // Message catcher/demoter + `uvm_create_obj(dv_report_catcher, m_report_catcher) + // Add demoted messages - we need to do this here to catch build warnings + add_message_demotes(m_report_catcher); + // Register catcher + uvm_report_cb::add(null, m_report_catcher); + + super.build_phase(phase); + + env = ENV_T::type_id::create("env", this); + + // Check whether there is a type for the environment config that has been registered in + // config_db. Doing so is a way that a (templated) test can pass a specific type, allowing the + // test class not to depend on that type. + // + // If the class hasn't chosen to do so, we can just use the type for CFG_T (part of the type of + // this test) + if (!uvm_config_db#(uvm_object_wrapper)::get(this, "env", "cfg_type", cfg_type)) begin + cfg_type = CFG_T::get_type(); + end + + // Now we know the config type, see whether one has been created by the testbench, configured + // and supplied through uvm_config_db. + // + // Note that we do the lookup through CFG_T rather than cfg_type, because the latter is only + // known at runtime. If there isn't a cfg object that has been provided, we create one ourselves + // and call its initialize() method. + if (!uvm_config_db#(CFG_T)::get(this, "env", "cfg", cfg)) begin + base_cfg = cfg_type.create_object("cfg"); + if (!base_cfg) begin + `uvm_fatal(`gfn, $sformatf("Failed to create object of type %p", cfg_type)) + end + + // At this point, we will normally have just created an object of type CFG_T, but have a + // handle to it with a weaker type. But we might have got an instance of some extension class + // if one is passed as cfg_type. Either way, we should be able to cast the result to a CFG_T. + if (!$cast(cfg, base_cfg)) begin + `uvm_fatal(`gfn, + $sformatf("Failed to cast object of type %p to expected CFG_T class.", cfg_type)) + end + + initialize_env_cfg(); + end + + `DV_CHECK_RANDOMIZE_FATAL(cfg) + uvm_config_db#(CFG_T)::set(this, "env", "cfg", cfg); + + // Enable scoreboard (and sub-scoreboard checks) via plusarg. + void'($value$plusargs("en_scb=%0b", cfg.en_scb)); + void'($value$plusargs("en_scb_mem_chk=%0b", cfg.en_scb_mem_chk)); + // Enable fastest design performance by configuring zero delays in all agents. + void'($value$plusargs("zero_delays=%0b", cfg.zero_delays)); + + // Enable coverage collection. + void'($value$plusargs("en_cov=%0b", cfg.en_cov)); + + // Enable reduced runtime test. + void'($value$plusargs("smoke_test=%0b", cfg.smoke_test)); + + // Enable print_topology + void'($value$plusargs("print_topology=%0b", print_topology)); + uvm_top.enable_print_topology = print_topology; + + void'($value$plusargs("cdc_instrumentation_enabled=%d", cfg.en_dv_cdc)); + + // Register cfg in the config db. This might already have been registered, but that shouldn't + // matter. + uvm_config_db#(CFG_T)::set(this, "*", "cfg", cfg); + + endfunction : build_phase + + // Initialize an env_cfg that has been created in build_phase + // + // This virtual function allows classes that extend dv_base_test to configure the env_cfg before + // or after calling dv_base_test::initialize_env_cfg (which calls initialize on the cfg object). + // + // The function is not called for cfg objects that are supplied through uvm_config_db (since they + // are assumed to have been initialized in the testbench already). + virtual function void initialize_env_cfg(); + cfg.initialize(); + endfunction + + virtual function void end_of_elaboration_phase(uvm_phase phase); + super.end_of_elaboration_phase(phase); + void'($value$plusargs("max_quit_count=%0d", max_quit_count)); + set_max_quit_count(max_quit_count); + void'($value$plusargs("test_timeout_ns=%0d", test_timeout_ns)); + uvm_top.set_timeout((test_timeout_ns * 1ns)); + endfunction : end_of_elaboration_phase + + virtual task run_phase(uvm_phase phase); + super.run_phase(phase); + void'($value$plusargs("drain_time_ns=%0d", drain_time_ns)); + phase.phase_done.set_drain_time(this, (drain_time_ns * 1ns)); + void'($value$plusargs("poll_for_stop=%0b", poll_for_stop)); + void'($value$plusargs("poll_for_stop_interval_ns=%0d", poll_for_stop_interval_ns)); + if (poll_for_stop) dv_utils_pkg::poll_for_stop(.interval_ns(poll_for_stop_interval_ns)); + void'($value$plusargs("UVM_TEST_SEQ=%0s", test_seq_s)); + if (run_test_seq) begin + run_seq(test_seq_s, phase); + end + endtask : run_phase + + // Add message demotes here - hook to use by extended tests + virtual function void add_message_demotes(dv_report_catcher catcher); + endfunction + + virtual task run_seq(string test_seq_s, uvm_phase phase); + uvm_sequence test_seq = create_seq_by_name(test_seq_s); + + configure_sequence(test_seq); + + `DV_CHECK_RANDOMIZE_FATAL(test_seq) + + `uvm_info(`gfn, {"Starting test sequence ", test_seq_s}, UVM_MEDIUM) + phase.raise_objection(this, $sformatf("%s objection raised", `gn)); + test_seq.start(env.virtual_sequencer); + phase.drop_objection(this, $sformatf("%s objection dropped", `gn)); + `uvm_info(`gfn, {"Finished test sequence ", test_seq_s}, UVM_MEDIUM) + endtask + + // A virtual function that allows the test to set up the sequence to know about the sequencer + // where it should run. This runs before the sequence is randomised, which allows the sequence to + // constrain its randomisation using the environment's cfg handle (getting it through p_sequencer). + // + // The base class version of this function registers env.virtual_sequencer. If a testbench wishes + // to register multiple sequencers with a virtual sequence, it can do so by overriding this + // function. + virtual function void configure_sequence(uvm_sequence seq); + seq.set_sequencer(env.virtual_sequencer); + endfunction + +endclass : dv_base_test diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_virtual_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_virtual_sequencer.sv new file mode 100644 index 0000000..1fc4c7d --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_virtual_sequencer.sv @@ -0,0 +1,32 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_virtual_sequencer #(type CFG_T = dv_base_env_cfg, + type COV_T = dv_base_env_cov) extends uvm_sequencer; + `uvm_component_param_utils(dv_base_virtual_sequencer #(CFG_T, COV_T)) + + CFG_T cfg; + COV_T cov; + + function new(string name, uvm_component parent); + super.new(name, parent); + endfunction + + // Dynamic associative array to store sub-sequencers + uvm_sequencer_base sub_sequencers[string]; + + // Method to dynamically register a sub-sequencer + function void register_sequencer(string name, uvm_sequencer_base sequencer); + // Check if the sub_sequencer name does not exists before register it. + `DV_CHECK_FATAL(!sub_sequencers.exists(name)) + sub_sequencers[name] = sequencer; + endfunction + + // Method to retrieve a sequencer by name + function uvm_sequencer_base get_sequencer(string name); + // Check if the sub_sequencer name is registered before return it. + `DV_CHECK_FATAL(sub_sequencers.exists(name)) + return sub_sequencers[name]; + endfunction +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv new file mode 100644 index 0000000..40e3435 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv @@ -0,0 +1,291 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class dv_base_vseq #(type RAL_T = dv_base_reg_block, + type CFG_T = dv_base_env_cfg, + type COV_T = dv_base_env_cov, + type VIRTUAL_SEQUENCER_T = dv_base_virtual_sequencer) extends uvm_sequence; + `uvm_object_param_utils(dv_base_vseq #(RAL_T, CFG_T, COV_T, VIRTUAL_SEQUENCER_T)) + `uvm_declare_p_sequencer(VIRTUAL_SEQUENCER_T) + + // number of iterations to run the test seq - please override constraint in extended vseq + // randomization for this is disabled in pre_start since we don't want to re-randomize it again + rand uint num_trans; + + constraint num_trans_c { + num_trans inside {[1:20]}; + } + + // handles for ease of op + CFG_T cfg; + RAL_T ral; + COV_T cov; + + // knobs to enable pre_start routines + bit do_dut_init = 1'b1; + bit do_apply_reset = 1'b1; + bit do_wait_for_reset = 1'b0; + + // knobs to enable post_start routines + bit do_dut_shutdown = 1'b1; + + // various knobs to enable certain routines + // this knob allows user to disable assertions in csr_hw_reset before random write sequence, + // the assertions will turn back on after the hw reset deasserted + bit enable_asserts_in_hw_reset_rand_wr = 1'b1; + + `uvm_object_new + + virtual function void set_handles(); + `DV_CHECK_NE_FATAL(p_sequencer, null, "Did you forget to call `set_sequencer()`?") + cfg = p_sequencer.cfg; + cov = p_sequencer.cov; + ral = cfg.ral; + endfunction + + // This function is invoked in pre_randomize(). Override it in the extended classes to configure + // / control the randomization of this sequence. + virtual function void configure_vseq(); + endfunction + + function void pre_randomize(); + // Set the handles in pre_randomize(), so that the knobs in cfg are available during sequence + // randomization. This forces `p_sequencer` handle to be set before the randomization - users + // are required to call `set_sequencer()` right after creating the sequence and before + // randomizing it. + if (cfg == null) set_handles(); + configure_vseq(); + endfunction + + task pre_start(); + super.pre_start(); + if (cfg == null) set_handles(); + if (do_dut_init) dut_init("HARD"); + num_trans.rand_mode(0); + endtask + + task post_start(); + super.post_start(); + if (do_dut_shutdown) dut_shutdown(); + endtask + + /* + * startup, reset and shutdown related tasks + */ + virtual task dut_init(string reset_kind = "HARD"); + if (do_apply_reset) begin + apply_reset(reset_kind); + post_apply_reset(reset_kind); + end else if (do_wait_for_reset) wait_for_reset(reset_kind); + // delay after reset for tl agent check seq_item_port empty + #1ps; + endtask + + virtual task apply_reset(string kind = "HARD"); + if (kind == "HARD") begin + if (cfg.clk_rst_vifs.size() > 0) begin + fork + begin : isolation_fork + foreach (cfg.clk_rst_vifs[i]) begin + automatic string ral_name = i; + fork + cfg.clk_rst_vifs[ral_name].apply_reset(); + join_none + end + wait fork; + end : isolation_fork + join + end else begin // no ral model and only has default clk_rst_vif + cfg.clk_rst_vif.apply_reset(); + end + end // if (kind == "HARD") + endtask + + // Apply all resets in the DUT concurrently to generate a random in-test reset scenario. + // + // - Assert resets concurrently to make sure all resets are issued. + // - Deassert resets concurrently is a specific requirement of the `stress_all_with_rand_reset` + // sequence, which will randomly issue resets and terminate the parallel sequence once all DUT + // resets are deasserted. If DUT resets are deasserted at different time, the parallel sequence + // might send a transaction request to driver between different resets are deasserting. Then when + // `stress_all_with_rand_reset` sequence tries to terminate the parallel sequence, an UVM_ERROR + // will be thrown by the sequencer saying `task responsible for requesting a wait_for_grant has + // been killed`. + // In order to ensure all resets at least being asserted for one clock cycle, this task takes an + // optional input `reset_duration_ps` if the DUT has additional resets. The task uses this input + // to compute the minimal time required to keep all resets asserted. + virtual task apply_resets_concurrently(int reset_duration_ps = 0); + int slowest_clk_period_ps = 0; + int reset_duration_from_clks_ps; + + // Calculate the slowest clock that we see with a RAL model or fall back to the default + // clk_rst_if if there is no RAL model. + if (cfg.clk_rst_vifs.size() > 0) begin + foreach (cfg.clk_rst_vifs[i]) begin + slowest_clk_period_ps = max2(slowest_clk_period_ps, cfg.clk_rst_vifs[i].clk_period_ps); + end + end else begin + slowest_clk_period_ps = cfg.clk_rst_vif.clk_period_ps; + end + + // Pick the reset duration by picking a random number of (slowest) clock cycles, taking at least + // two. Then use the maximum of that value and the reset_duration_ps argument. + reset_duration_from_clks_ps = $urandom_range(2, 10) * slowest_clk_period_ps; + reset_duration_ps = max2(reset_duration_ps, reset_duration_from_clks_ps); + + // Now apply the reset by driving any reset pins to zero, waiting a while, and then driving the + // back to one. + if (cfg.clk_rst_vifs.size() > 0) begin + foreach (cfg.clk_rst_vifs[i]) cfg.clk_rst_vifs[i].drive_rst_pin(0); + #(reset_duration_ps * 1ps); + foreach (cfg.clk_rst_vifs[i]) cfg.clk_rst_vifs[i].drive_rst_pin(1); + end else begin + cfg.clk_rst_vif.drive_rst_pin(0); + #(reset_duration_ps * 1ps); + cfg.clk_rst_vif.drive_rst_pin(1); + end + endtask + + // This is called after apply_reset in this class and after apply_resets_concurrently + // in cip_base_vseq::run_seq_with_rand_reset_vseq. + virtual task post_apply_reset(string reset_kind = "HARD"); + endtask + + virtual task wait_for_reset(string reset_kind = "HARD", + bit wait_for_assert = 1, + bit wait_for_deassert = 1); + if (wait_for_assert) begin + `uvm_info(`gfn, "waiting for rst_n assertion...", UVM_MEDIUM) + @(negedge cfg.clk_rst_vif.rst_n); + end + if (wait_for_deassert) begin + `uvm_info(`gfn, "waiting for rst_n de-assertion...", UVM_MEDIUM) + @(posedge cfg.clk_rst_vif.rst_n); + end + `uvm_info(`gfn, "wait_for_reset done", UVM_HIGH) + endtask + + // dut shutdown - this is called in post_start if do_dut_shutdown bit is set + virtual task dut_shutdown(); + csr_utils_pkg::wait_no_outstanding_access(); + endtask + + // wrapper task around run_csr_vseq - the purpose is to be able to call this directly for actual + // csr tests (as opposed to higher level stress test that could also run csr seq as a fork by + // calling run_csr_vseq(..) task) + virtual task run_csr_vseq_wrapper(int num_times = 1, dv_base_reg_block models[$] = {}); + string csr_test_type; + + // Env needs to have a ral instance. + if (models.size() == 0) begin + `DV_CHECK_GE_FATAL(cfg.ral_models.size(), 1) + end + + // Get csr_test_type from plusarg + void'($value$plusargs("csr_%0s", csr_test_type)); + + // run the csr seq + for (int i = 1; i <= num_times; i++) begin + `uvm_info(`gfn, $sformatf("Running csr %0s vseq iteration %0d/%0d.", + csr_test_type, i, num_times), UVM_LOW) + run_csr_vseq(.csr_test_type(csr_test_type), .models(models)); + end + endtask + + // capture the entire csr seq as a task that can be overridden if desired + // arg csr_test_type: what csr test to run {hw_reset, rw, bit_bash, aliasing} + // arg num_test_csrs:instead of testing the entire ral model or passing test chunk info via + // plusarg, provide ability to set a random number of csrs to test from higher level sequence + // `models` is the list of RAL models to run the common sequences on. + // `ral_name` is the string name of the RAL to run the common sequences on. + // Both of these inputs are 'null' by default. If externally set, `models` takes precedence over + // `ral_name`. + virtual task run_csr_vseq(string csr_test_type, + int num_test_csrs = 0, + bit do_rand_wr_and_reset = 1, + dv_base_reg_block models[$] = {}, + string ral_name = ""); + csr_base_seq m_csr_seq; + + // env needs to have at least one ral instance + `DV_CHECK_GE_FATAL(cfg.ral_models.size(), 1) + + // Filter out the RAL blocks under test with the supplied name, if available. + if (models.size() == 0) begin + if (ral_name != "") begin + `DV_CHECK_FATAL(cfg.ral_models.exists(ral_name)) + models.push_back(cfg.ral_models[ral_name]); + end else begin + foreach (cfg.ral_models[i]) models.push_back(cfg.ral_models[i]); + end + end + + // check which csr test type + case (csr_test_type) + "hw_reset": csr_base_seq::type_id::set_type_override(csr_hw_reset_seq::get_type()); + "rw" : csr_base_seq::type_id::set_type_override(csr_rw_seq::get_type()); + "bit_bash": csr_base_seq::type_id::set_type_override(csr_bit_bash_seq::get_type()); + "aliasing": csr_base_seq::type_id::set_type_override(csr_aliasing_seq::get_type()); + "mem_walk": csr_base_seq::type_id::set_type_override(csr_mem_walk_seq::get_type()); + default : `uvm_fatal(`gfn, $sformatf("specified opt is invalid: +csr_%0s", csr_test_type)) + endcase + + // Print the list of available exclusions that are in effect for debug. + foreach (models[i]) begin + csr_excl_item csr_excl = csr_utils_pkg::get_excl_item(models[i]); + if (csr_excl != null) csr_excl.print_exclusions(); + end + + // if hw_reset test, then write all CSRs first and reset the whole dut + if (csr_test_type == "hw_reset" && do_rand_wr_and_reset) begin + string reset_type = "HARD"; + csr_write_seq m_csr_write_seq; + + // Writing random values to CSRs might trigger assertion errors. So we disable in the entire + // DUT hierarchy and re-enable after resetting the DUT. See DV_ASSERT_CTRL macro defined in + // hw/dv/sv/dv_utils/dv_macros.svh for more details. + if (!enable_asserts_in_hw_reset_rand_wr) begin + `DV_ASSERT_CTRL_REQ("dut_assert_en", 1'b0) + end + + // run write-only sequence to randomize the csr values + m_csr_write_seq = csr_write_seq::type_id::create("m_csr_write_seq"); + m_csr_write_seq.models = models; + m_csr_write_seq.external_checker = cfg.en_scb; + m_csr_write_seq.en_rand_backdoor_write = 1'b1; + m_csr_write_seq.start(null); + + // run dut_shutdown before asserting reset + dut_shutdown(); + // issue reset + void'($value$plusargs("do_reset=%0s", reset_type)); + dut_init(reset_type); + if (!enable_asserts_in_hw_reset_rand_wr) begin + `DV_ASSERT_CTRL_REQ("dut_assert_en", 1'b1) + end + end + + // create base csr seq and pass our ral + m_csr_seq = csr_base_seq::type_id::create("m_csr_seq"); + m_csr_seq.models = models; + m_csr_seq.external_checker = cfg.en_scb; + m_csr_seq.max_num_test_csrs = num_test_csrs; + m_csr_seq.start(null); + endtask + + // enable/disable csr_assert + virtual function void set_csr_assert_en(bit enable, string path = "*"); + uvm_config_db#(bit)::set(null, path, "csr_assert_en", enable); + endfunction + + // Use the factory to create a sequence by name and return the resulting uvm_sequence. + // + // The created sequence should be an instance of the class where this function is defined. + // Creating the sequence through this method rather than the underlying function, + // dv_utils_pkg::create_seq_by_name, allows subclasses of dv_base_seq to copy information about + // themselves (such as sequencers or other configuration) to the new sequence. + virtual function uvm_sequence create_seq_by_name(string name); + return dv_utils_pkg::create_seq_by_name(name); + endfunction +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib.core b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib.core new file mode 100644 index 0000000..4190323 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib.core @@ -0,0 +1,32 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_lib" +description: "DV base class UVM library" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_utils + - lowrisc:dv:csr_utils + - lowrisc:dv:dv_base_reg + - lowrisc:dv:dv_base_agent + - lowrisc:dv:common_ifs + files: + - dv_lib_pkg.sv + + - dv_base_env_cfg.sv: {is_include_file: true} + - bit_toggle_cg_wrap.sv: {is_include_file: true} + - dv_base_env_cov.sv: {is_include_file: true} + - dv_base_virtual_sequencer.sv: {is_include_file: true} + - dv_base_scoreboard.sv: {is_include_file: true} + - dv_base_env.sv: {is_include_file: true} + - dv_base_vseq.sv: {is_include_file: true} + - dv_base_test.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib_pkg.sv new file mode 100644 index 0000000..9d9bc32 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_lib/dv_lib_pkg.sv @@ -0,0 +1,36 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package dv_lib_pkg; + // dep packages + import uvm_pkg::*; + import dv_utils_pkg::*; + import csr_utils_pkg::*; + import dv_base_reg_pkg::*; + import dv_base_agent_pkg::*; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + // package variables + string msg_id = "dv_lib_pkg"; + + // package sources + + // base env + `include "dv_base_env_cfg.sv" + `include "bit_toggle_cg_wrap.sv" + `include "dv_base_env_cov.sv" + `include "dv_base_virtual_sequencer.sv" + `include "dv_base_scoreboard.sv" + `include "dv_base_env.sv" + + // base test vseq + `include "dv_base_vseq.sv" + + // base test + `include "dv_base_test.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/README.md b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/README.md new file mode 100644 index 0000000..e69de29 diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.core b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.core new file mode 100644 index 0000000..4542886 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.core @@ -0,0 +1,17 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_fcov_macros" +description: "DV FCOV macros" + +filesets: + files_fcov: + files: + - dv_fcov_macros.svh: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_fcov diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.svh b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.svh new file mode 100644 index 0000000..eaae393 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_fcov_macros.svh @@ -0,0 +1,112 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Include FCOV RTL by default. Disable it for synthesis and where explicitly requested (by defining +// DV_FCOV_DISABLE). +`ifdef SYNTHESIS + `define DV_FCOV_DISABLE +`elsif YOSYS + `define DV_FCOV_DISABLE +`endif + +// Disable instantiations of FCOV coverpoints or covergroups. +`ifdef VERILATOR + `define DV_FCOV_DISABLE_CP +`elsif DV_FCOV_DISABLE + `define DV_FCOV_DISABLE_CP +`endif + +// Instantiates a covergroup in an interface or module. +// +// This macro assumes that a covergroup of the same name as the NAME_ arg is defined in the +// interface or module. It just adds some extra signals and logic to control the creation of the +// covergroup instance with ~bit en_~. This defaults to 0. It is ORed with the external +// COND_ signal. The testbench can modify it at t = 0 based on the test being run. +// NOTE: This is not meant to be invoked inside a class. +// +// NAME_ : Name of the covergroup. +// COND_ : External condition / expr that controls the creation of the covergroup. +// ARGS_ : Arguments to covergroup instance, if any. Args MUST BE wrapped in (..). +`ifndef DV_FCOV_INSTANTIATE_CG +`ifdef DV_FCOV_DISABLE_CP + `define DV_FCOV_INSTANTIATE_CG(NAME_, COND_ = 1'b1, ARGS_ = ()) +`else + `define DV_FCOV_INSTANTIATE_CG(NAME_, COND_ = 1'b1, ARGS_ = ()) \ + bit en_``NAME_ = 1'b0; \ + NAME_ NAME_``_inst; \ + initial begin \ + /* The #1 delay below allows any part of the tb to control the conditions first at t = 0. */ \ + #1; \ + if ((en_``NAME_) || (COND_)) begin \ + $display("%0t: (%0s:%0d) [%m] %0s", $time, `__FILE__, `__LINE__, \ + {"Creating covergroup ", `"NAME_`"}); \ + NAME_``_inst = new``ARGS_; \ + end \ + end +`endif +`endif + +// Creates a coverpoint for an expression where only the expression true case is of interest for +// coverage (e.g. where the expression indicates an event has occurred). +`ifndef DV_FCOV_EXPR_SEEN +`ifdef DV_FCOV_DISABLE_CP + `define DV_FCOV_EXPR_SEEN(NAME_, EXPR_) +`else + `define DV_FCOV_EXPR_SEEN(NAME_, EXPR_) cp_``NAME_: coverpoint EXPR_ { bins seen = {1}; } +`endif +`endif + +// Creates a SVA cover that can be used in a covergroup. +// +// This macro creates an unnamed SVA cover from the property (or an expression) `PROP_` and an event +// with the name `EV_NAME_`. When the SVA cover is hit, the event is triggered. A coverpoint can +// cover the `triggered` property of the event. +`ifndef DV_FCOV_SVA +`ifdef DV_FCOV_DISABLE + `define DV_FCOV_SVA(EV_NAME_, PROP_, CLK_ = clk_i, RST_ = rst_ni) +`else + `define DV_FCOV_SVA(EV_NAME_, PROP_, CLK_ = clk_i, RST_ = rst_ni) \ + event EV_NAME_; \ + cover property (@(posedge CLK_) disable iff (RST_ == 0) (PROP_)) begin \ + -> EV_NAME_; \ + end +`endif +`endif + +// Coverage support is not always available but it's useful to include extra fcov signals for +// linting purposes. They need to be marked as unused to avoid warnings. +`ifndef DV_FCOV_MARK_UNUSED + `define DV_FCOV_MARK_UNUSED(TYPE_, NAME_) \ + TYPE_ unused_fcov_``NAME_; \ + assign unused_fcov_``NAME_ = fcov_``NAME_; +`endif + +// Define a signal and expression in the design for capture in functional coverage +`ifndef DV_FCOV_SIGNAL +`ifdef DV_FCOV_DISABLE + `define DV_FCOV_SIGNAL(TYPE_, NAME_, EXPR_) +`else + `define DV_FCOV_SIGNAL(TYPE_, NAME_, EXPR_) \ + TYPE_ fcov_``NAME_; \ + assign fcov_``NAME_ = EXPR_; \ + `DV_FCOV_MARK_UNUSED(TYPE_, NAME_) +`endif +`endif + +// Define a signal and expression in the design for capture in functional coverage depending on +// design configuration. The input GEN_COND_ must be a constant or parameter. +`ifndef DV_FCOV_SIGNAL_GEN_IF +`ifdef DV_FCOV_DISABLE + `define DV_FCOV_SIGNAL_GEN_IF(TYPE_, NAME_, EXPR_, GEN_COND_, DEFAULT_ = '0) +`else + `define DV_FCOV_SIGNAL_GEN_IF(TYPE_, NAME_, EXPR_, GEN_COND_, DEFAULT_ = '0) \ + TYPE_ fcov_``NAME_; \ + if (GEN_COND_) begin : g_fcov_``NAME_ \ + assign fcov_``NAME_ = EXPR_; \ + end else begin : g_no_fcov_``NAME_ \ + assign fcov_``NAME_ = DEFAULT_; \ + end \ + `DV_FCOV_MARK_UNUSED(TYPE_, NAME_) +`endif +`endif diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.core b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.core new file mode 100644 index 0000000..61a236b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.core @@ -0,0 +1,17 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_macros" +description: "A collection of macros used in DV." + +filesets: + files_dv: + files: + - dv_macros.svh: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: &default_target + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.svh b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.svh new file mode 100644 index 0000000..a239b1e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_macros.svh @@ -0,0 +1,651 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +`ifdef UVM + `include "uvm_macros.svh" +`endif + +// UVM speficic macros +`ifndef gfn +`ifdef UVM + // verilog_lint: waive macro-name-style + `define gfn get_full_name() +`else + // verilog_lint: waive macro-name-style + `define gfn $sformatf("%m") +`endif +`endif + +`ifndef gtn + // verilog_lint: waive macro-name-style + `define gtn get_type_name() +`endif + +`ifndef gn + // verilog_lint: waive macro-name-style + `define gn get_name() +`endif + +`ifndef gmv + // verilog_lint: waive macro-name-style + `define gmv(csr) csr.get_mirrored_value() +`endif + +// cast base class obj holding extended class handle to extended class handle; +// throw error if cast fails +`ifndef downcast + // verilog_lint: waive macro-name-style + `define downcast(EXT_, BASE_, MSG_="", SEV_=fatal, ID_=`gfn) \ + begin \ + if (!$cast(EXT_, BASE_)) begin \ + `dv_``SEV_($sformatf({"Cast failed: base class variable %0s ", \ + "does not hold extended class %0s handle %s"}, \ + `"BASE_`", `"EXT_`", MSG_), ID_) \ + end \ + end +`endif + +// Note, UVM provides a macro `uvm_new_func -- which only applies to uvm_components +`ifndef uvm_object_new + `define uvm_object_new \ + function new (string name=""); \ + super.new(name); \ + endfunction : new +`endif + +`ifndef uvm_create_obj + `define uvm_create_obj(_type_name_, _inst_name_) \ + _inst_name_ = _type_name_::type_id::create(`"_inst_name_`"); +`endif + +`ifndef uvm_component_new + `define uvm_component_new \ + function new (string name, uvm_component parent); \ + super.new(name, parent); \ + endfunction : new +`endif + +`ifndef uvm_create_comp + `define uvm_create_comp(_type_name_, _inst_name_) \ + _inst_name_ = _type_name_::type_id::create(`"_inst_name_`", this); +`endif + +// Convert arbitrary text / expression to string. +`ifndef DV_STRINGIFY + `define DV_STRINGIFY(I_) `"I_`" +`endif + +`ifndef DUT_HIER_STR + `define DUT_HIER_STR `DV_STRINGIFY(`DUT_HIER) +`endif + +// Common check macros used by DV_CHECK error and fatal macros. +// Note: Should not be called by user code +`ifndef DV_CHECK + `define DV_CHECK(T_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if (T_) ; else begin \ + `dv_``SEV_($sformatf("Check failed (%s) %s ", `"T_`", MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_EQ + `define DV_CHECK_EQ(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) == (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s == %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_NE + `define DV_CHECK_NE(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) != (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s != %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_CASE_EQ + `define DV_CHECK_CASE_EQ(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) === (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s === %s (0x%0h [%0b] vs 0x%0h [%0b]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_CASE_NE + `define DV_CHECK_CASE_NE(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) !== (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s !== %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_LT + `define DV_CHECK_LT(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) < (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s < %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_GT + `define DV_CHECK_GT(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) > (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s > %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_LE + `define DV_CHECK_LE(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) <= (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s <= %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_GE + `define DV_CHECK_GE(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) >= (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed %s >= %s (%0d [0x%0h] vs %0d [0x%0h]) %s", \ + `"ACT_`", `"EXP_`", ACT_, ACT_, EXP_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_STREQ + `define DV_CHECK_STREQ(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) == (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed \"%s\" == \"%s\" %s", ACT_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_STRNE + `define DV_CHECK_STRNE(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + if ((ACT_) != (EXP_)) ; else begin \ + `dv_``SEV_($sformatf("Check failed \"%s\" != \"%s\" %s", ACT_, EXP_, MSG_), ID_) \ + end \ + end +`endif + +`ifndef DV_CHECK_Q_EQ + `define DV_CHECK_Q_EQ(ACT_, EXP_, MSG_="", SEV_=error, ID_=`gfn) \ + begin \ + `DV_CHECK_EQ(ACT_.size(), EXP_.size(), MSG_, SEV_, ID_) \ + foreach (ACT_[i]) begin \ + `DV_CHECK_EQ(ACT_[i], EXP_[i], $sformatf("for i = %0d %s", i, MSG_), SEV_, ID_) \ + end \ + end +`endif + +// Fatal version of the checks +`ifndef DV_CHECK_FATAL + `define DV_CHECK_FATAL(T_, MSG_="", ID_=`gfn) \ + `DV_CHECK(T_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_EQ_FATAL + `define DV_CHECK_EQ_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_EQ(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_NE_FATAL + `define DV_CHECK_NE_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_NE(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_LT_FATAL + `define DV_CHECK_LT_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_LT(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_GT_FATAL + `define DV_CHECK_GT_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_GT(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_LE_FATAL + `define DV_CHECK_LE_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_LE(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_GE_FATAL + `define DV_CHECK_GE_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_GE(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_STREQ_FATAL + `define DV_CHECK_STREQ_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_STREQ(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +`ifndef DV_CHECK_STRNE_FATAL + `define DV_CHECK_STRNE_FATAL(ACT_, EXP_, MSG_="", ID_=`gfn) \ + `DV_CHECK_STRNE(ACT_, EXP_, MSG_, fatal, ID_) +`endif + +// Shorthand for common foo.randomize() + fatal check +`ifndef DV_CHECK_RANDOMIZE_FATAL + `define DV_CHECK_RANDOMIZE_FATAL(VAR_, MSG_="Randomization failed!", ID_=`gfn) \ + `DV_CHECK_FATAL(VAR_.randomize(), MSG_, ID_) +`endif + +// Shorthand for common foo.randomize() with { } + fatal check +`ifndef DV_CHECK_RANDOMIZE_WITH_FATAL + `define DV_CHECK_RANDOMIZE_WITH_FATAL(VAR_, WITH_C_, MSG_="Randomization failed!", ID_=`gfn) \ + `DV_CHECK_FATAL(VAR_.randomize() with {WITH_C_}, MSG_, ID_) +`endif + +// Shorthand for common std::randomize(foo) + fatal check +`ifndef DV_CHECK_STD_RANDOMIZE_FATAL + `define DV_CHECK_STD_RANDOMIZE_FATAL(VAR_, MSG_="Randomization failed!", ID_=`gfn) \ + `DV_CHECK_FATAL(std::randomize(VAR_), MSG_, ID_) +`endif + +// Shorthand for common std::randomize(foo) with { } + fatal check +`ifndef DV_CHECK_STD_RANDOMIZE_WITH_FATAL + `define DV_CHECK_STD_RANDOMIZE_WITH_FATAL(VAR_, WITH_C_, MSG_="Randomization failed!",ID_=`gfn) \ + `DV_CHECK_FATAL(std::randomize(VAR_) with {WITH_C_}, MSG_, ID_) +`endif + +// Shorthand for common cls_inst.randomize(member) + fatal check +// Randomizes a specific member of a class instance. +`ifndef DV_CHECK_MEMBER_RANDOMIZE_FATAL + `define DV_CHECK_MEMBER_RANDOMIZE_FATAL(VAR_, CLS_INST_=this, MSG_="Randomization failed!", ID_=`gfn) \ + `DV_CHECK_FATAL(CLS_INST_.randomize(VAR_), MSG_, ID_) +`endif + +// Shorthand for common cls_inst.randomize(member) with { } + fatal check +// Randomizes a specific member of a class instance with inline constraints. +`ifndef DV_CHECK_MEMBER_RANDOMIZE_WITH_FATAL + `define DV_CHECK_MEMBER_RANDOMIZE_WITH_FATAL(VAR_, C_, CLS_INST_=this, MSG_="Randomization failed!", ID_=`gfn) \ + `DV_CHECK_FATAL(CLS_INST_.randomize(VAR_) with {C_}, MSG_, ID_) +`endif + +// print static/dynamic 1d array or queue +`ifndef DV_PRINT_ARR_CONTENTS +`define DV_PRINT_ARR_CONTENTS(ARR_, V_=uvm_pkg::UVM_MEDIUM, ID_=`gfn) \ + begin \ + foreach (ARR_[i]) begin \ + `dv_info($sformatf("%s[%0d] = %0d (0x%0h)", `"ARR_`", i, ARR_[i], ARR_[i]), V_, ID_) \ + end \ + end +`endif + +// print non-empty tlm FIFOs that were uncompared at end of test +`ifndef DV_EOT_PRINT_TLM_FIFO_CONTENTS +`define DV_EOT_PRINT_TLM_FIFO_CONTENTS(TYP_, FIFO_, SEV_=error, ID_=`gfn) \ + forever begin \ + TYP_ item; \ + int res = FIFO_.try_get(item); \ + if (res == 0) break; \ + if (res < 0) `dv_fatal($sformatf("Cannot read item from %s (type mismatch)", `"FIFO_`"), ID_) \ + `dv_``SEV_($sformatf("%s item uncompared:\n%s", `"FIFO_`", item.sprint()), ID_) \ + end +`endif + +// print non-empty tlm FIFOs that were uncompared at end of test +`ifndef DV_EOT_PRINT_TLM_FIFO_ARR_CONTENTS +`define DV_EOT_PRINT_TLM_FIFO_ARR_CONTENTS(TYP_, FIFO_, SEV_=error, ID_=`gfn) \ + begin \ + foreach (FIFO_[i]) begin \ + while (!FIFO_[i].is_empty()) begin \ + TYP_ item; \ + void'(FIFO_[i].try_get(item)); \ + `dv_``SEV_($sformatf("%s[%0d] item uncompared:\n%s", `"FIFO_`", i, item.sprint()), ID_) \ + end \ + end \ + end +`endif + +// print non-empty tlm FIFOs that were uncompared at end of test +`ifndef DV_EOT_PRINT_Q_CONTENTS +`define DV_EOT_PRINT_Q_CONTENTS(TYP_, Q_, SEV_=error, ID_=`gfn) \ + begin \ + while (Q_.size() != 0) begin \ + TYP_ item = Q_.pop_front(); \ + `dv_``SEV_($sformatf("%s item uncompared:\n%s", `"Q_`", item.sprint()), ID_) \ + end \ + end +`endif + +// print non-empty tlm FIFOs that were uncompared at end of test +`ifndef DV_EOT_PRINT_Q_ARR_CONTENTS +`define DV_EOT_PRINT_Q_ARR_CONTENTS(TYP_, Q_, SEV_=error, ID_=`gfn) \ + begin \ + foreach (Q_[i]) begin \ + while (Q_[i].size() != 0) begin \ + TYP_ item = Q_[i].pop_front(); \ + `dv_``SEV_($sformatf("%s[%0d] item uncompared:\n%s", `"Q_`", i, item.sprint()), ID_) \ + end \ + end \ + end +`endif + +// check for non-empty mailbox and print items that were uncompared at end of test +`ifndef DV_EOT_PRINT_MAILBOX_CONTENTS +`define DV_EOT_PRINT_MAILBOX_CONTENTS(TYP_, MAILBOX_, SEV_=error, ID_=`gfn) \ + begin \ + while (MAILBOX_.num() != 0) begin \ + TYP_ item; \ + void'(MAILBOX_.try_get(item)); \ + `dv_``SEV_($sformatf("%s item uncompared:\n%s", `"MAILBOX_`", item.sprint()), ID_) \ + end \ + end +`endif + +// get parity - implemented as a macro so that it can be invoked in constraints as well +`ifndef GET_PARITY + `define GET_PARITY(val, odd=0) (^val ^ odd) +`endif + +// Wait for a statement but stop early if the EXIT statement completes. +// +// Example usage: +// +// `DV_SPINWAIT_EXIT(do_something_time_consuming();, +// wait(stop_now_flag);, +// "The stop flag was set when we were working") +`ifndef DV_SPINWAIT_EXIT +`define DV_SPINWAIT_EXIT(WAIT_, EXIT_, MSG_ = "exit condition occurred!", ID_ =`gfn) \ + begin \ + fork begin \ + fork \ + begin \ + WAIT_ \ + end \ + begin \ + EXIT_ \ + if (MSG_ != "") begin \ + `dv_info(MSG_, uvm_pkg::UVM_HIGH, ID_) \ + end \ + end \ + join_any \ + disable fork; \ + end join \ + end +`endif + +// Wait for one of two statements but stop early if the EXIT statement completes. +// +// Example usage: +// +// `DV_SPINWAIT_EXIT_MULTI(do_something_time_consuming();, +// do_something_else_time_consuming();, +// wait(stop_now_flag);, +// "The stop flag was set when we were working") +`ifndef DV_SPINWAIT_EXIT_MULTI +`define DV_SPINWAIT_EXIT_MULTI(WAIT_1_, WAIT_2_, EXIT_, MSG_ = "exit condition occurred!", ID_ =`gfn) \ + `DV_SPINWAIT_EXIT(fork begin \ + fork \ + begin WAIT_1_ end \ + begin WAIT_2_ end \ + join_any \ + disable fork; \ + end join, \ + EXIT_, MSG_, ID_) +`endif + +// macro that waits for a given delay and then reports an error +`ifndef DV_WAIT_TIMEOUT +`define DV_WAIT_TIMEOUT(TIMEOUT_NS_, ID_ = `gfn, ERROR_MSG_ = "timeout occurred!", REPORT_FATAL_ = 1) \ + begin \ + #(TIMEOUT_NS_ * 1ns); \ + if (REPORT_FATAL_) begin \ + `dv_fatal(ERROR_MSG_, ID_) \ + end else begin \ + `dv_error(ERROR_MSG_, ID_) \ + end \ + end +`endif + +// Wait for a statement, but exit early after a timeout +`ifndef DV_SPINWAIT +`define DV_SPINWAIT(WAIT_, MSG_ = "timeout occurred!", TIMEOUT_NS_ = default_spinwait_timeout_ns, ID_ =`gfn, REPORT_FATAL_ = 1) \ + `DV_SPINWAIT_EXIT(WAIT_, `DV_WAIT_TIMEOUT(TIMEOUT_NS_, ID_, MSG_, REPORT_FATAL_);, "", ID_) +`endif + +// a shorthand of `DV_SPINWAIT(wait(...)) +`ifndef DV_WAIT +`define DV_WAIT(WAIT_COND_, MSG_ = "wait timeout occurred!", TIMEOUT_NS_ = default_spinwait_timeout_ns, ID_ =`gfn, REPORT_FATAL_ = 1) \ + `DV_SPINWAIT(wait (WAIT_COND_);, MSG_, TIMEOUT_NS_, ID_, REPORT_FATAL_) +`endif + +// Wait for one of two statements, but exit early after a timeout +`ifndef DV_WAIT_MULTI +`define DV_WAIT_MULTI(WAIT_COND_1_, WAIT_COND_2_, MSG_ = "wait timeout occurred!", TIMEOUT_NS_ = default_spinwait_timeout_ns, ID_ =`gfn, REPORT_FATAL_ = 1) \ + `DV_SPINWAIT_EXIT_MULTI(WAIT_COND_1_, WAIT_COND_2_, `DV_WAIT_TIMEOUT(TIMEOUT_NS_, ID_, MSG_, REPORT_FATAL_);, "", ID_) +`endif + +// Control assertions in the DUT. +// +// This macro is invoked in top level testbench that instantiates the DUT. It spawns off an initial +// block that forever waits for a resource of type bit named by the string arg ~LABEL_~ that +// can be set by any entity in the testbench. Based on the value set, it enables or disables the +// assertions at the hierarchy of the provided path. The entity setting the resource value invokes +// uvm_config_db#(bit)::set(...) and this macro calls the corresponding get. +// +// LABEL_ : Name of the assertion control resource bit (string). +// HIER_ : Path to the module within which the assertion is controlled. +// LEVELS_: Number of levels within the module to control the assertions. +// SCOPE_ : Hierarchical string path to the testbench where this macro is invoked, example: %m. +// ID_ : Identifier string used for UVM logs. +`ifndef DV_ASSERT_CTRL +`define DV_ASSERT_CTRL(LABEL_, HIER_, LEVELS_ = 0, SCOPE_ = "", ID_ = $sformatf("%m")) \ + initial begin \ + bit assert_en; \ + forever begin \ + uvm_config_db#(bit)::wait_modified(null, SCOPE_, LABEL_); \ + if (!uvm_config_db#(bit)::get(null, SCOPE_, LABEL_, assert_en)) begin \ + `uvm_fatal(ID_, $sformatf("Failed to get \"%0s\" from uvm_config_db", LABEL_)) \ + end \ + if (assert_en) begin \ + `uvm_info(ID_, $sformatf("Enabling assertions: %0s", `DV_STRINGIFY(HIER_)), UVM_LOW) \ + $asserton(LEVELS_, HIER_); \ + end else begin \ + `uvm_info(ID_, $sformatf("Disabling assertions: %0s", `DV_STRINGIFY(HIER_)), UVM_LOW) \ + $assertoff(LEVELS_, HIER_); \ + $assertkill(LEVELS_, HIER_); \ + end \ + end \ + end +`endif + +// Retrieves a plusarg value representing an enum literal. +// +// The plusarg is parsed as a string, which needs to be converted into the enum literal whose name +// matches the string. This functionality is provided by the UVM helper function below. +// +// ENUM_: The enum type. +// VAR_: The enum variable to which the plusarg value will be set (must be declared already). +// PLUSARG_: the name of the plusarg (as a string). This is typically the same as the enum variable. +`ifndef DV_GET_ENUM_PLUSARG +`define DV_GET_ENUM_PLUSARG(ENUM_, VAR_, PLUSARG_, ID_ = `gfn) \ + begin \ + string str; \ + if ($value$plusargs({PLUSARG_, "=%0s"}, str)) begin \ + if (!uvm_enum_wrapper#(ENUM_)::from_name(str, VAR_)) begin \ + `uvm_fatal(ID_, $sformatf(`"Cannot find %s from enum ``ENUM_```", VAR_.name())) \ + end \ + end \ + end +`endif + +// Enable / disable assertions at a module hierarchy identified by LABEL_. +// +// This goes in conjunction with `DV_ASSERT_CTRL() macro above, but is invoked in the entity that is +// sending the req to turn on / off the assertions. Note that piece of code invoking this macro +// does not have the information on the actual hierarchical path to the module or the levels - this +// is 'wrapped' into the LABEL_ instead. DV user needs to uniquify the label sufficiently enough to +// reflect it. +// +// LABEL_ : Name of the assertion control resource bit (string). +// VALUE_ : Value of the control bit - 1 - enable assertions, 0 - disable assertions. +// SCOPE_ : Hierarchical string path to the testbench where this macro is invoked, example: %m. +`ifndef DV_ASSERT_CTRL_REQ +`define DV_ASSERT_CTRL_REQ(LABEL_, VALUE_, SCOPE_="") \ + begin \ + uvm_config_db#(bit)::set(null, SCOPE_, LABEL_, VALUE_); \ + end +`endif + +// Macros for logging (info, warning, error and fatal severities). +// +// These are meant to be invoked in modules and interfaces that are shared between DV and Verilator +// testbenches. We waive the lint requirement for these to be in uppercase, since they are +// UVM-adjacent. +`ifdef UVM +`ifndef dv_info + // verilog_lint: waive macro-name-style + `define dv_info(MSG_, VERBOSITY_ = uvm_pkg::UVM_LOW, ID_ = $sformatf("%m")) \ + if (uvm_pkg::uvm_report_enabled(VERBOSITY_, uvm_pkg::UVM_INFO, ID_)) begin \ + uvm_pkg::uvm_report_info(ID_, MSG_, VERBOSITY_, `uvm_file, `uvm_line, "", 1); \ + end +`endif + +`ifndef dv_warning + // verilog_lint: waive macro-name-style + `define dv_warning(MSG_, ID_ = $sformatf("%m")) \ + if (uvm_pkg::uvm_report_enabled(uvm_pkg::UVM_NONE, uvm_pkg::UVM_WARNING, ID_)) begin \ + uvm_pkg::uvm_report_warning(ID_, MSG_, uvm_pkg::UVM_NONE, `uvm_file, `uvm_line, "", 1); \ + end +`endif + +`ifndef dv_error + // verilog_lint: waive macro-name-style + `define dv_error(MSG_, ID_ = $sformatf("%m")) \ + if (uvm_pkg::uvm_report_enabled(uvm_pkg::UVM_NONE, uvm_pkg::UVM_ERROR, ID_)) begin \ + uvm_pkg::uvm_report_error(ID_, MSG_, uvm_pkg::UVM_NONE, `uvm_file, `uvm_line, "", 1); \ + end +`endif + +`ifndef dv_fatal + // verilog_lint: waive macro-name-style + `define dv_fatal(MSG_, ID_ = $sformatf("%m")) \ + if (uvm_pkg::uvm_report_enabled(uvm_pkg::UVM_NONE, uvm_pkg::UVM_FATAL, ID_)) begin \ + uvm_pkg::uvm_report_fatal(ID_, MSG_, uvm_pkg::UVM_NONE, `uvm_file, `uvm_line, "", 1); \ + end +`endif + +`else // UVM + +`ifndef dv_info + // verilog_lint: waive macro-name-style + `define dv_info(MSG_, VERBOSITY = DUMMY_, ID_ = $sformatf("%m")) \ + $display("%0t: (%0s:%0d) [%0s] %0s", $time, `__FILE__, `__LINE__, ID_, MSG_); +`endif + +`ifndef dv_warning + // verilog_lint: waive macro-name-style + `define dv_warning(MSG_, ID_ = $sformatf("%m")) \ + $warning("%0t: (%0s:%0d) [%0s] %0s", $time, `__FILE__, `__LINE__, ID_, MSG_); +`endif + +`ifndef dv_error + // verilog_lint: waive macro-name-style + `define dv_error(MSG_, ID_ = $sformatf("%m")) \ + $error("%0t: (%0s:%0d) [%0s] %0s", $time, `__FILE__, `__LINE__, ID_, MSG_); +`endif + +`ifndef dv_fatal + // verilog_lint: waive macro-name-style + `define dv_fatal(MSG_, ID_ = $sformatf("%m")) \ + $fatal(1, "%0t: (%0s:%0d) [%0s] %0s", $time, `__FILE__, `__LINE__, ID_, MSG_); +`endif + +`endif // UVM + +// Macros for constrain clk with common frequencies +// +// Nominal clock frequency range is 24Mhz - 100Mhz and use higher weights on 24, 25, 48, 50, 100, +// To mimic manufacturing conditions (when clocks are uncalibrated), we need to be able to go as +// low as 5MHz. +`ifndef DV_COMMON_CLK_CONSTRAINT +`define DV_COMMON_CLK_CONSTRAINT(FREQ_) \ + FREQ_ dist { \ + [5:23] :/ 2, \ + [24:25] :/ 2, \ + [26:47] :/ 1, \ + [48:50] :/ 2, \ + [51:95] :/ 1, \ + 96 :/ 1, \ + [97:99] :/ 1, \ + 100 :/ 1 \ + }; +`endif + +// Enables build-time randomization of fixed design constants. +// +// This is meant to be overridden externally by passing `+define+BUILD_SEED=`. +`ifndef BUILD_SEED + `define BUILD_SEED 1 +`endif + +// Max value out of 2 given expressions. +// +// Duplicate of dv_utils_pkg::max2() function, but this is better because +// it can consume different data types directly without the need for casting. +`ifndef DV_MAX2 + `define DV_MAX2(a, b) ((a) > (b) ? (a) : (b)) +`endif + +// Creates a signal probe function to sample / force / release an internal signal. +// +// If there is a need to sample / force an internal signal, then it must be done in the testbench, +// or in an interface bound to the DUT. This macro creates a standardized signal probe function +// to be defined in an interface. The generated function can then be invoked in test sequences +// or other UVM classes. The macro takes 2 arguments - name of the function and the hierarchical +// path to the signal. If invoked in an interface which is bound to the DUT, the signal can be a +// partial hierarchical path within the DUT. The generated function accepts 2 arguments - the first +// indicates the probe action (sample, force or release) of type dv_utils_pkg::signal_probe_e. The +// second argument is the value to be forced. If sample action is chosen, then it returns the +// sampled value (for other actions as well). +// +// The suggested naming convention for the function is: +// signal_probe__ +// +// This macro must be invoked in an interface or module. +`ifndef DV_CREATE_SIGNAL_PROBE_FUNCTION +`define DV_CREATE_SIGNAL_PROBE_FUNCTION(FUNC_NAME_, SIGNAL_PATH_, SIGNAL_WIDTH_ = uvm_pkg::UVM_HDL_MAX_WIDTH) \ + function static logic [SIGNAL_WIDTH_-1:0] FUNC_NAME_(dv_utils_pkg::signal_probe_e kind, \ + logic [SIGNAL_WIDTH_-1:0] value = '0); \ + case (kind) \ + dv_utils_pkg::SignalProbeSample: ; \ + dv_utils_pkg::SignalProbeForce: force SIGNAL_PATH_ = value; \ + dv_utils_pkg::SignalProbeRelease: release SIGNAL_PATH_; \ + default: `uvm_fatal(`"FUNC_NAME_`", $sformatf("Bad value: %0d", kind)) \ + endcase \ + return SIGNAL_PATH_; \ + endfunction +`endif + +// Usage:`OTDBG(( string )) +// This macro has unique keyword 'OTDBG' and timestamp only. +// Use for the temporary print to distinguish from `uvm_info. +// Do not leave this macro in other source files in the remote repo. +`ifndef OTDBG + `define OTDBG(x) \ + $write($sformatf("%t:OTDBG:%s:%d:",$time,`__FILE__, `__LINE__));\ + $display($sformatf x); +`endif diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_catcher.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_catcher.sv new file mode 100644 index 0000000..4f96279 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_catcher.sv @@ -0,0 +1,46 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// Report catcher/demoter +class dv_report_catcher extends uvm_report_catcher; + + // Stores a new severity indexed by the ID and + // the regular expression to match the message + protected uvm_severity m_changed_sev[string][string]; + + `uvm_object_utils(dv_report_catcher) + `uvm_object_new + + // Called for all report messages - defined in uvm_report_catcher + virtual function action_e catch(); + string id = get_id(); + if (m_changed_sev.exists(id)) begin + string report_msg = get_message(); + foreach (m_changed_sev[id, msg]) begin + if (uvm_re_match(msg, report_msg)) begin + set_severity(m_changed_sev[id][msg]); + end + end + end + return THROW; + endfunction + + // Change severity of a message with ID == id and message text + // matching msg which is treated as a regular expression + virtual function void add_change_sev(string id, string msg, uvm_severity sev); + m_changed_sev[id][msg] = sev; + endfunction + + // Remove a change entry + // If msg == "" then remove all changes for a given id + virtual function void remove_change_sev(string id, string msg = ""); + if (m_changed_sev.exists(id)) + if (msg == "") begin + // Delete all with id if message is blank + m_changed_sev.delete(id); + end else if (m_changed_sev[id].exists(msg)) begin + m_changed_sev[id].delete(msg); + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_server.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_server.sv new file mode 100644 index 0000000..fcfe25c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_report_server.sv @@ -0,0 +1,66 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Standardize look & feel of report phase and uvm logging messages. +class dv_report_server extends uvm_default_report_server; + `uvm_object_utils(dv_report_server) + + bit show_file_line = 1'b1; + // if enabled, show the relative path of the file. By default only show file name + bit show_file_path = 1'b0; + bit use_default_uvm_report_message_format = 1'b0; + + function new (string name = ""); + super.new(name); + // provide ability to override these knobs over cli + void'($value$plusargs("show_file_line=%0b", show_file_line)); + void'($value$plusargs("show_file_path=%0b", show_file_path)); + void'($value$plusargs("use_default_uvm_report_message_format=%0b", + use_default_uvm_report_message_format)); + endfunction + + function void report_summarize(UVM_FILE file = 0); + int num_uvm_warning; + int num_uvm_error; + int num_uvm_fatal; + + num_uvm_warning = get_severity_count(UVM_WARNING); + num_uvm_error = get_severity_count(UVM_ERROR); + num_uvm_fatal = get_severity_count(UVM_FATAL); + + // Print default summary report + super.report_summarize(file); + + // Print final test pass-fail - external tool can use this signature for test status + // Treat UVM_WARNINGs as a sign of test failure since it could silently result in false pass + dv_test_status_pkg::dv_test_status((num_uvm_warning + num_uvm_error + num_uvm_fatal) == 0); + endfunction + + // Override default messaging format to standard "pretty" format for all testbenches + virtual function string compose_report_message(uvm_report_message report_message, + string report_object_name = ""); + + if (use_default_uvm_report_message_format) begin + return (super.compose_report_message(report_message, report_object_name)); + end else begin + uvm_severity severity = report_message.get_severity(); + string filename = report_message.get_filename(); + int line = report_message.get_line(); + string obj_name = report_message.get_report_object().get_full_name(); + string id = report_message.get_id(); + string message = report_message.get_message(); + string file_line; + + if (show_file_line && filename != "") begin + if (!show_file_path) filename = str_utils_pkg::str_path_basename(filename); + file_line = $sformatf("(%0s:%0d) ", filename, line); + end + obj_name = {obj_name, ((obj_name != "") ? " " : "")}; + compose_report_message = $sformatf({"%0s @ %t: ", file_line, obj_name, "[%0s] %0s"}, + severity.name(), $realtime, id, message); + return compose_report_message; + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status.core b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status.core new file mode 100644 index 0000000..fdeea3e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status.core @@ -0,0 +1,19 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_test_status" +description: "DV test status reporting utilities" + +filesets: + files_dv: + depend: + - lowrisc:prim:util + files: + - dv_test_status_pkg.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status_pkg.sv new file mode 100644 index 0000000..d1516a2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_test_status_pkg.sv @@ -0,0 +1,38 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package dv_test_status_pkg; + + // Prints the test status signature & banner. + // + // This function takes a boolean arg indicating whether the test passed or failed and prints the + // signature along with a banner. The signature can be used by external scripts to determine if + // the test passed or failed. + function automatic void dv_test_status(bit passed); +`ifdef INC_ASSERT + if (prim_util_pkg::end_of_simulation) begin + // The first arg '1' is the error code, arbitrarily set to 1. + $fatal(1, "prim_util_pkg::end_of_simulation was already signaled!"); + end + prim_util_pkg::end_of_simulation = 1'b1; +`endif + if (passed) begin + $display("\nTEST PASSED CHECKS"); + $display(" _____ _ _ _ "); + $display("|_ _|__ ___| |_ _ __ __ _ ___ ___ ___ __| | |"); + $display(" | |/ _ \\/ __| __| | '_ \\ / _` / __/ __|/ _ \\/ _` | |"); + $display(" | | __/\\__ \\ |_ | |_) | (_| \\__ \\__ \\ __/ (_| |_|"); + $display(" |_|\\___||___/\\__| | .__/ \\__,_|___/___/\\___|\\__,_(_)"); + $display(" |_| \n"); + end else begin + $display("\nTEST FAILED CHECKS"); + $display(" _____ _ __ _ _ _ _ "); + $display("|_ _|__ ___| |_ / _| __ _(_) | ___ __| | |"); + $display(" | |/ _ \\/ __| __| | |_ / _` | | |/ _ \\/ _` | |"); + $display(" | | __/\\__ \\ |_ | _| (_| | | | __/ (_| |_|"); + $display(" |_|\\___||___/\\__| |_| \\__,_|_|_|\\___|\\__,_(_)\n"); + end + endfunction + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils.core b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils.core new file mode 100644 index 0000000..84bd52c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils.core @@ -0,0 +1,27 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:dv_utils" +description: "DV utilities" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_macros + - lowrisc:dv:dv_fcov_macros + - lowrisc:dv:common_ifs + - lowrisc:prim:assert:0.1 + - lowrisc:opentitan:bus_params_pkg + - lowrisc:dv:str_utils + - lowrisc:dv:dv_test_status + files: + - dv_utils_pkg.sv + - dv_report_catcher.sv: {is_include_file: true} + - dv_report_server.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv new file mode 100644 index 0000000..692b471 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv @@ -0,0 +1,350 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package dv_utils_pkg; + // dep packages + import uvm_pkg::*; + import bus_params_pkg::*; + + // macro includes + `include "dv_macros.svh" +`ifdef UVM + `include "uvm_macros.svh" +`endif + + // common parameters used across all benches + parameter int NUM_MAX_INTERRUPTS = 32; + typedef logic [NUM_MAX_INTERRUPTS-1:0] interrupt_t; + + parameter int NUM_MAX_ALERTS = 32; + typedef logic [NUM_MAX_ALERTS-1:0] alert_t; + + // types & variables + typedef bit [31:0] uint; + typedef bit [7:0] uint8; + typedef bit [15:0] uint16; + typedef bit [31:0] uint32; + typedef bit [63:0] uint64; + + // TODO: The above typedefs violate the name rule, which is fixed below. Cleanup the codebase to + // use the typedefs below and remove the ones above. + typedef bit [7:0] uint8_t; + typedef bit [15:0] uint16_t; + typedef bit [31:0] uint32_t; + typedef bit [63:0] uint64_t; + + // typedef parameterized pins_if for ease of implementation for interrupts and alerts + typedef virtual pins_if #(NUM_MAX_INTERRUPTS) intr_vif; + + // Interface direction / mode + typedef enum bit [1:0] { + Host, // The interface is active and is driving signals as a host + Device, // The interface is active and is driving signals as a device + Monitor // The interface is passive and drives no signals + } if_mode_e; + + // compare operator types + typedef enum { + CompareOpEq, + CompareOpCaseEq, + CompareOpNe, + CompareOpCaseNe, + CompareOpGt, + CompareOpGe, + CompareOpLt, + CompareOpLe + } compare_op_e; + + // mem address struct + typedef struct { + uvm_reg_addr_t start_addr; + uvm_reg_addr_t end_addr; + } addr_range_t; + + // Enum representing a bus operation type - read or write. + typedef enum bit { + BusOpWrite = 1'b0, + BusOpRead = 1'b1 + } bus_op_e; + + // Enum representing a probe operation on an internal signal. + typedef enum { + SignalProbeSample, // Sample the signal. + SignalProbeForce, // Force the signal with some value. + SignalProbeRelease // Release the previous force. + } signal_probe_e; + + // Enum representing a type of host requests - read only, write only or random read & write + typedef enum int { + HostReqNone = 0, + HostReqReadOnly = 1, + HostReqWriteOnly = 2, + HostReqReadWrite = 3 + } host_req_type_e; + + // Enum representing clock frequency difference on 2 clocks + typedef enum bit [1:0] { + ClkFreqDiffNone, + ClkFreqDiffSmall, + ClkFreqDiffBig, + ClkFreqDiffAny + } clk_freq_diff_e; + + // return the smaller value of 2 inputs + function automatic int min2(int a, int b); + return (a < b) ? a : b; + endfunction + + // return the bigger value of 2 inputs + function automatic int max2(int a, int b); + return (a > b) ? a : b; + endfunction + + // return the biggest value within the given queue of integers. + function automatic int max(const ref int int_q[$]); + `DV_CHECK_GT_FATAL(int_q.size(), 0, "max function cannot accept an empty queue of integers!", + $sformatf("%m")) + // Assign the first value from the queue in case of negative integers. + max = int_q[0]; + foreach (int_q[i]) max = max2(max, int_q[i]); + return max; + endfunction + + // get absolute value of the input. Usage: absolute(val) or absolute(a - b) + function automatic uint absolute(int val); + return val >= 0 ? val : -val; + endfunction + + // endian swaps a 32-bit data word + function automatic logic [31:0] endian_swap(logic [31:0] data); + return {<<8{data}}; + endfunction + + // endian swaps bytes at a word granularity, while preserving overall word ordering. + // + // e.g. if `arr[] = '{'h0, 'h1, 'h2, 'h3, 'h4, 'h5, 'h6, 'h7}`, this function will produce: + // `'{'h3, 'h2, 'h1, 'h0, 'h7, 'h6, 'h5, 'h4}` + function automatic void endian_swap_byte_arr(ref bit [7:0] arr[]); + arr = {<< byte {arr}}; + arr = {<< 32 {arr}}; + endfunction + +`ifdef UVM + // Simple function to set max errors before quitting sim + function automatic void set_max_quit_count(int n); + uvm_report_server report_server = uvm_report_server::get_server(); + report_server.set_max_quit_count(n); + endfunction + + // return if uvm_fatal occurred + function automatic bit has_uvm_fatal_occurred(); + uvm_report_server report_server = uvm_report_server::get_server(); + return report_server.get_severity_count(UVM_FATAL) > 0; + endfunction + + // create a sequence by name and return the handle of uvm_sequence + function automatic uvm_sequence create_seq_by_name(string seq_name); + uvm_object obj; + uvm_factory factory; + uvm_sequence seq; + + factory = uvm_factory::get(); + obj = factory.create_object_by_name(seq_name, "", seq_name); + if (obj == null) begin + // print factory overrides to help debug + factory.print(1); + `uvm_fatal($sformatf("%m"), $sformatf("could not create %0s seq", seq_name)) + end + if (!$cast(seq, obj)) begin + `uvm_fatal($sformatf("%m"), $sformatf("cast failed - %0s is not a uvm_sequence", seq_name)) + end + return seq; + endfunction +`endif + + // Returns the hierarchical path to the interface / module N levels up. + // + // Meant to be invoked inside a module or interface. + // hier: String input of the interface / module, typically $sformatf("%m"). + // n_levels_up: Integer number of levels up the hierarchy to omit. + // Example: if (hier = tb.dut.foo.bar, n_levels_up = 2), then return tb.dut + function automatic string get_parent_hier(string hier, int n_levels_up = 1); + int idx; + int level; + if (n_levels_up <= 0) return hier; + for (idx = hier.len() - 1; idx >= 0; idx--) begin + if (hier[idx] == ".") level++; + if (level == n_levels_up) break; + end + return (hier.substr(0, idx - 1)); + endfunction + + // Periodically check for the existence of a magic file (dv.stop). Exit if it exists. This + // provides a mechanism to gracefully kill a simulation without direct access to the process. + task automatic poll_for_stop(uint interval_ns = 10_000, string filename = "dv.stop"); + fork + while (1) begin + #(interval_ns * 1ns); + if (!$system($sformatf("test -f %0s", filename))) begin + $system($sformatf("rm %0s", filename)); + `dv_fatal($sformatf("Found %0s file. Exiting!", filename), "poll_for_stop") + end + end + join_none + endtask : poll_for_stop + + // Extracts the address and size of a const symbol in a SW test (supplied as an ELF file). + // + // Used by a testbench to modify the given symbol in an executable (elf) generated for an embedded + // CPU within the DUT. This function only returns the extracted address and size of the symbol + // using the readelf utility. Readelf comes with binutils, a package typically available on linux + // machines. If not available, the assumption is, it can be relatively easily installed. + // The actual job of writing the new value into the symbol is handled externally (often via a + // backdoor mechanism to write the memory). + // Return 1 on success and 0 on failure. + function automatic bit sw_symbol_get_addr_size(input string elf_file, + input string symbol, + input bit does_not_exist_ok, + output longint unsigned addr, + output longint unsigned size); + + string escaped_symbol = ""; + string symbol_for_filename = ""; + + if (elf_file == "") `uvm_fatal($sformatf("%m"), "'elf_file' argument cannot be an empty string") + if (symbol == "") `uvm_fatal($sformatf("%m"), "'symbol' argument cannot be an empty string") + + // If the symbol has special characters, such as '$', escape it for the cmd below, but when + // creating the file, omit the special characters entirely. + foreach (symbol[i]) begin + if (symbol[i] == "$") begin + escaped_symbol = {escaped_symbol, "\\", symbol[i]}; + end else begin + escaped_symbol = {escaped_symbol, symbol[i]}; + symbol_for_filename = {symbol_for_filename, symbol[i]}; + end + end + + begin + int ret; + string line; + int out_file_d = 0; + string out_file = $sformatf("%0s.dat", symbol_for_filename); + string cmd = $sformatf( + // use `--wide` to avoid truncating the output, in case of long symbol name + // `\s%0s$` ensures we are looking for an exact match, with no pre- or postfixes. + "/usr/bin/readelf -s --wide %0s | grep \"\\s%0s$\" | awk \'{print $2\" \"$3}\' > %0s", + elf_file, escaped_symbol, out_file); + + // TODO #3838: shell pipes are bad 'mkay? + ret = $system(cmd); + `DV_CHECK_EQ_FATAL(ret, 0, $sformatf("Command \"%0s\" failed with exit code %0d", cmd, ret), + $sformatf("%m")) + + out_file_d = $fopen(out_file, "r"); + `DV_CHECK_FATAL(out_file_d, $sformatf("Failed to open \"%0s\"", out_file), $sformatf("%m")) + + ret = $fgets(line, out_file_d); + + // If the symbol did not exist in the elf (empty file), and we are ok with that, then return. + if (!ret && does_not_exist_ok) return 0; + + `DV_CHECK_FATAL(ret, $sformatf("Failed to read line from \"%0s\"", out_file), $sformatf("%m")) + + // The first line should have the addr in hex followed by its size as integer. + ret = $sscanf(line, "%h %d", addr, size); + `DV_CHECK_EQ_FATAL(ret, 2, $sformatf("Failed to extract {addr size} from line \"%0s\"", line), + $sformatf("%m")) + + // Attempt to read the next line should be met with EOF. + void'($fgets(line, out_file_d)); + ret = $feof(out_file_d); + `DV_CHECK_FATAL(ret, $sformatf("EOF expected to be reached for \"%0s\"", out_file), + $sformatf("%m")) + $fclose(out_file_d); + + ret = $system($sformatf("rm -rf %0s", out_file)); + `DV_CHECK_EQ_FATAL(ret, 0, $sformatf("Failed to delete \"%0s\"", out_file), $sformatf("%m")) + return 1; + end + endfunction + + // Reads VMEM file contents into a queue of data. + // + // TODO: Add support for non-contiguous memory. + // TODO: Add support for ECC bits. + // TODO: Add support for non-BUS_DW sized VMEM data. + // vmem_file: Path to VMEM image, compatible with $readmemh mathod. + // vmem_data: A queue of BUS_DW sized data returned to the caller. + function automatic void read_vmem(input string vmem_file, + output logic [bus_params_pkg::BUS_DW-1:0] vmem_data[$]); + int fd; + uvm_reg_addr_t last_addr; + string text, msg = "\n", lines[$]; + + fd = $fopen(vmem_file, "r"); + `DV_CHECK_FATAL(fd, $sformatf("Failed to open \"%0s\"", vmem_file), $sformatf("%m")) + while (!$feof(fd)) begin + string line; + void'($fgets(line, fd)); + line = str_utils_pkg::str_strip(line); + if (line == "") continue; + text = {text, line, "\n"}; + end + $fclose(fd); + `DV_CHECK_STRNE_FATAL(text, "", , $sformatf("%m")) + + // Remove all block and single comments. + text = str_utils_pkg::str_remove_sections(.s(text), .start_delim("/*"), .end_delim("*/")); + text = str_utils_pkg::str_remove_sections(.s(text), .start_delim("//"), .end_delim("\n"), + .remove_end_delim(0)); + + vmem_data.delete(); + str_utils_pkg::str_split(text, lines, "\n"); + foreach (lines[i]) begin + string tokens[$]; + uvm_reg_addr_t addr; + + // Split the line by space. The first item must be the address that starts with '@'. + str_utils_pkg::str_split(lines[i], tokens, " "); + `DV_CHECK_FATAL(tokens.size() >= 2, + $sformatf("Line \"%s\" in VMEM file %s appears to be malformed", + lines[i], vmem_file), $sformatf("%m")) + if (!str_utils_pkg::str_starts_with(tokens[0], "@")) begin + `uvm_fatal($sformatf("%m"), $sformatf({"The first word \"%s\" on line \"%s\" in the VMEM", + " file %s does not appear to be a valid address"}, + tokens[0], lines[i], vmem_file)) + end + tokens[0] = tokens[0].substr(1, tokens[0].len() - 1); + `DV_CHECK_FATAL(tokens[0].len() <= bus_params_pkg::BUS_AW / 8 * 2, + $sformatf("Address width > %0d bytes is not supported: 0x%0s", + bus_params_pkg::BUS_AW / 8, tokens[0]), $sformatf("%m")) + addr = tokens[0].atohex(); + tokens = tokens[1:$]; + if (i > 0) begin + `DV_CHECK_FATAL(addr == last_addr, + $sformatf("Non-contiguous data unsupported - last_addr: 0x%0h, addr: 0x%0h", + last_addr, addr), $sformatf("%m")) + end + foreach (tokens[i]) begin + logic [bus_params_pkg::BUS_DW-1:0] data; + `DV_CHECK_FATAL(tokens[i].len() <= bus_params_pkg::BUS_DW / 8 * 2, + $sformatf("Data width > %0d bytes is not supported: 0x%0s", + bus_params_pkg::BUS_DW / 8, tokens[i]), $sformatf("%m")) + data = tokens[i].atohex(); + msg = {msg, $sformatf("[0x%0h] = 0x%0h\n", addr + i, data)}; + vmem_data.push_back(data); + end + last_addr = addr + tokens.size(); + end + `uvm_info($sformatf("%m"), $sformatf("Contents of VMEM file %s:%s", vmem_file, msg), UVM_HIGH) + endfunction + + // sources +`ifdef UVM + `include "dv_report_catcher.sv" + `include "dv_report_server.sv" +`endif + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/mem_model/README.md b/hw/vendor/lowrisc_ip/dv/sv/mem_model/README.md new file mode 100644 index 0000000..68d0f6f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/mem_model/README.md @@ -0,0 +1,27 @@ +# Memory Model + +The memory model UVC models a memory device which any host interface can read +from or write to. It is implemented as a `uvm_object`, and instantiates an +associative array of bytes `system_memory`. This class is parameterized by both +the address width and the data width, and creates two `typedefs` to represent +both, `mem_addr_t` and `mem_data_t`. +The `mem_model` class has four main functions, which are detailed below. + +### `read_byte(mem_addr_t addr)` +This function looks up the byte of data corresponding to the memory address +passed in, and returns it. If the address does not exist in `system_memory`, it +will randomize the returned data and throw a `UVM_ERROR`. + +### `write_byte(mem_addr_t addr, bit [7:0] data)` +This function simply assigns the given data to the specified memory address +location in `system_memory`. + +### `write(input mem_addr_t addr, mem_data_t data)` +This function writes a full memory word of width `mem_data_t` to the specified +address, breaking it down into a series of back-to-back calls to `write_byte()` +to correctly byte-address the memory. + +### `read(mem_addr_t addr)` +This function reads a full memory word of width `mem_data_t` from the specified +address, breaking it down into a series of back-to-back calls to `read_byte()` +to correctly byte-address the memory. diff --git a/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.core b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.core new file mode 100644 index 0000000..a7abbf3 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.core @@ -0,0 +1,21 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:mem_model" +description: "DV Memory Model" + +filesets: + files_dv: + depend: + - lowrisc:opentitan:bus_params_pkg + - lowrisc:dv:dv_macros + files: + - mem_model_pkg.sv + - mem_model.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.sv b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.sv new file mode 100644 index 0000000..f4579b8 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model.sv @@ -0,0 +1,99 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class mem_model #(int AddrWidth = bus_params_pkg::BUS_AW, + int DataWidth = bus_params_pkg::BUS_DW) extends uvm_object; + + localparam int MaskWidth = DataWidth / 8; + + typedef logic [AddrWidth-1:0] mem_addr_t; + typedef logic [DataWidth-1:0] mem_data_t; + typedef logic [MaskWidth-1:0] mem_mask_t; + + logic [7:0] system_memory[mem_addr_t]; + + `uvm_object_param_utils(mem_model#(AddrWidth, DataWidth)) + + `uvm_object_new + + function void init(); + system_memory.delete(); + endfunction + + function int get_written_bytes(); + return system_memory.size(); + endfunction + + function bit [7:0] read_byte(mem_addr_t addr); + bit [7:0] data; + if (addr_exists(addr)) begin + data = system_memory[addr]; + `uvm_info(`gfn, $sformatf("Read Mem : Addr[0x%0h], Data[0x%0h]", addr, data), UVM_HIGH) + end else begin + `DV_CHECK_STD_RANDOMIZE_FATAL(data) + `uvm_error(`gfn, $sformatf("read from uninitialized addr 0x%0h", addr)) + end + return data; + endfunction + + function void write_byte(mem_addr_t addr, logic [7:0] data); + `uvm_info(`gfn, $sformatf("Write Mem : Addr[0x%0h], Data[0x%0h]", addr, data), UVM_HIGH) + system_memory[addr] = data; + endfunction + + function void compare_byte(mem_addr_t addr, logic [7:0] act_data); + `uvm_info(`gfn, $sformatf("Compare Mem : Addr[0x%0h], Act Data[0x%0h], Exp Data[0x%0h]", + addr, act_data, system_memory[addr]), UVM_HIGH) + `DV_CHECK_CASE_EQ(act_data, system_memory[addr], + $sformatf("addr 0x%0h read out mismatch", addr)) + endfunction + + function void write(input mem_addr_t addr, mem_data_t data, mem_mask_t mask = '1); + bit [7:0] byte_data; + for (int i = 0; i < DataWidth / 8; i++) begin + if (mask[0]) begin + byte_data = data[7:0]; + write_byte(addr + i, byte_data); + end + data = data >> 8; + mask = mask >> 1; + end + endfunction + + function mem_data_t read(mem_addr_t addr, mem_mask_t mask = '1); + mem_data_t data; + for (int i = DataWidth / 8 - 1; i >= 0; i--) begin + data = data << 8; + if (mask[MaskWidth - 1]) data[7:0] = read_byte(addr + i); + else data[7:0] = 0; + mask = mask << 1; + end + return data; + endfunction + + function void compare(mem_addr_t addr, mem_data_t act_data, mem_mask_t mask = '1, + bit compare_exist_addr_only = 1); + bit [7:0] byte_data; + for (int i = 0; i < DataWidth / 8; i++) begin + mem_addr_t byte_addr = addr + i; + byte_data = act_data[7:0]; + if (mask[0]) begin + if (addr_exists(byte_addr)) begin + compare_byte(byte_addr, byte_data); + end else if (!compare_exist_addr_only) begin + `uvm_error(`gfn, $sformatf("address 0x%0x not exists", byte_addr)) + end + end else begin + // Nothing to do here: since this byte wasn't selected by the mask, there are no + // requirements about what data came back. + end + act_data = act_data>> 8; + mask = mask >> 1; + end + endfunction + + function bit addr_exists(mem_addr_t addr); + return system_memory.exists(addr); + endfunction +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model_pkg.sv new file mode 100644 index 0000000..975e3bd --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/mem_model/mem_model_pkg.sv @@ -0,0 +1,13 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package mem_model_pkg; + + import uvm_pkg::*; + + `include "uvm_macros.svh" + `include "dv_macros.svh" + `include "mem_model.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/str_utils/README.md b/hw/vendor/lowrisc_ip/dv/sv/str_utils/README.md new file mode 100644 index 0000000..b13afd1 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/str_utils/README.md @@ -0,0 +1,6 @@ +# str_utils_pkg + +This package provides some basic string and path manipulation utility functions that +can be used across the project. It can be imported in non-UVM testbenches as +well. Please see the package for the list of available functions and their +descriptions. diff --git a/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils.core b/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils.core new file mode 100644 index 0000000..14eebda --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils.core @@ -0,0 +1,19 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:str_utils" +description: "String manipulation utilities" + +filesets: + files_dv: + depend: + - lowrisc:dv:dv_macros + files: + - str_utils_pkg.sv + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils_pkg.sv new file mode 100644 index 0000000..5bd5ac9 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/str_utils/str_utils_pkg.sv @@ -0,0 +1,236 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package str_utils_pkg; + `include "dv_macros.svh" + + string msg_id = "str_utils_pkg"; + + // Returns 1 if string 's' has substring 'sub' within the given index range. 0 Otherwise. + function automatic bit str_has_substr(string s, string sub, int range_lo = 0, int range_hi = -1); + if (range_hi < 0 || range_hi >= s.len()) range_hi = s.len() - 1; + for (int i = range_lo; i <= (range_hi - sub.len() + 1); i++) begin + if (s.substr(i, i + sub.len() - 1) == sub) begin + return 1; + end + end + return 0; + endfunction : str_has_substr + + // Returns 1 when string 's' starts with substring 'sub'. + function automatic bit str_starts_with(string s, string sub); + return s.substr(0, sub.len() - 1) == sub; + endfunction + + // Returns 1 when string 's' ends with substring 'sub'. + function automatic bit str_ends_with(string s, string sub); + return s.substr(s.len() - sub.len(), s.len() - 1) == sub; + endfunction + + // Returns the index of first occurrence of string 'sub' within string 's''s given index range. + // Returns -1 otherwise. + function automatic int str_find(string s, string sub, int range_lo = 0, int range_hi = -1); + if (range_hi < 0 || range_hi >= s.len()) range_hi = s.len() - 1; + for (int i = range_lo; i <= (range_hi - sub.len() + 1); i++) begin + if (s.substr(i, i + sub.len() - 1) == sub) begin + return i; + end + end + return -1; + endfunction : str_find + + // Returns the index of last occurrence of string 'sub' within string 's''s given index range. + // Returns -1 otherwise. + function automatic int str_rfind(string s, string sub, int range_lo = 0, int range_hi = -1); + if (range_hi < 0 || range_hi >= s.len()) range_hi = s.len() - 1; + for (int i = (range_hi - sub.len() + 1); i >= range_lo; i--) begin + if (s.substr(i, i + sub.len() - 1) == sub) begin + return i; + end + end + return -1; + endfunction : str_rfind + + // Find the first match string 'sub' in 's' and replace it with 'new_sub'. + // TODO: Add support for global replacement. + function automatic string str_replace(string s, string sub, string new_sub); + string str_before_sub, str_after_sub; + int lo_idx = str_find(s, sub); + + // check sub string exists + `DV_CHECK_NE_FATAL(lo_idx, -1, $sformatf("sub string %s doesn't exist in %s", sub, s), msg_id) + + // the new_str contains 3 portions {str_before_sub, new_sub, str_after_sub} + if (lo_idx > 0) str_before_sub = s.substr(0, lo_idx - 1); + if (lo_idx + sub.len() < s.len()) str_after_sub = s.substr(lo_idx + sub.len(), s.len() - 1); + + return {str_before_sub, new_sub, str_after_sub}; + endfunction : str_replace + + // Strips a given set of characters in string 's'. + // + // The set of characters to strip is provided as a string. If not set, all whitespace characters + // are stripped by default. Stripping is done at both ends, unless the user turns off the + // stripping from one of the ends. + function automatic string str_strip(string s, + string chars = " \t\n", + bit lstrip = 1'b1, + bit rstrip = 1'b1); + byte chars_q[$]; + if (chars == "") return s; + foreach (chars[i]) chars_q.push_back(chars.getc(i)); + + if (lstrip) begin + int i = 0; + while (s.getc(i) inside {chars_q}) i++; + s = s.substr(i, s.len() - 1); + end + + if (rstrip) begin + int i = s.len() - 1; + while (s.getc(i) inside {chars_q}) i--; + s = s.substr(0, i); + end + return s; + endfunction : str_strip + + // Splits the input `string` on the given single-character delimiter `delim`. + // + // The split tokens are pushed into the `result` queue. The whitespaces on each split token are + // stripped by default, which can be turned off. + // TODO: allow arbitrary length delimiter. + function automatic void str_split(input string s, + output string result[$], + input byte delim = " ", + input bit strip_whitespaces = 1'b1); + string sub; + bit in_quotes; + result = {}; + foreach (s[i]) begin + if (s[i] == "\"") begin + in_quotes = !in_quotes; + end + if ((s.getc(i) == delim) && !in_quotes) begin + if (strip_whitespaces) sub = str_strip(sub); + if (sub != "") result.push_back(sub); + sub = ""; + end else begin + sub = {sub, s[i]}; + end + if (i == s.len() - 1) begin + if (strip_whitespaces) sub = str_strip(sub); + if (sub != "") result.push_back(sub); + end + end + endfunction : str_split + + // Returns a string concatenated from the provided queue of strings 's'. + // + // The concatenation is performed using the 'delim' arg as the delimiter. + function automatic string str_join(string s[$], string delim = " "); + string str; + foreach (s[i]) begin + str = {str, s[i], delim}; + end + if (str != "") begin + str = str.substr(0, str.len() - delim.len() - 1); + end + return str; + endfunction : str_join + + // Cuts sections (such as comments) from string s starting and ending with provided substrings. + // + // start_delim: substring representing the start of section to be removed (e.g. "//", "/*"). + // end_delim: substring representing the end of the section to be removed (e.g. "\n", "*/"). + // remove_start_delim: include the start_delim substring in the removal. + // remove_end_delim: include the end_delim substring in the removal. + function automatic string str_remove_sections(string s, + string start_delim, + string end_delim, + bit remove_start_delim = 1, + bit remove_end_delim = 1); + int start_idx, end_idx; + start_idx = str_utils_pkg::str_find(s, start_delim); + while (start_idx != -1) begin + int rm_start_idx, rm_end_idx; + rm_start_idx = remove_start_delim ? start_idx : start_idx + start_delim.len() - 1; + end_idx = str_utils_pkg::str_find(s, end_delim, .range_lo(start_idx + start_delim.len())); + if (end_idx == -1) break; + rm_end_idx = remove_end_delim ? end_idx + end_delim.len() - 1 : end_idx - 1; + s = str_utils_pkg::str_replace(s, s.substr(rm_start_idx, rm_end_idx), ""); + start_idx = str_utils_pkg::str_find(s, start_delim, .range_lo(end_idx + end_delim.len())); + end + return s; + endfunction + + // Converts a string to an array of bytes. + function automatic void str_to_bytes(string s, output byte bytes[]); + bytes = new[s.len()]; + foreach (bytes[i]) begin + bytes[i] = s.getc(i); + end + endfunction : str_to_bytes + + // Converts an array of bytes to a string. + function automatic string bytes_to_str(byte bytes[]); + string s; + foreach (bytes[i]) begin + s = {s, string'(bytes[i])}; + end + return s; + endfunction + + /************************/ + /* File path functions. */ + /************************/ + + // Returns the dirname of the file. + // + // Examples: + // path/to/foo.bar => path/to + // path/to/foo/bar => path/to/foo + // path/to/foo/bar/ => path/to/foo + // path/to/foo/bar/. => path/to/foo/bar + // / => / + function automatic string str_path_dirname(string filename); + int idx; + string dirname; + + if (filename == "/") return filename; + filename = str_strip(.s(filename), .chars("/"), .lstrip(1'b0)); + idx = str_rfind(.s(filename), .sub("/")); + if (idx == -1) idx = filename.len(); + if (idx == 0) idx++; + dirname = filename.substr(0, idx - 1); + return dirname; + endfunction : str_path_dirname + + // Returns the basename of the file. + // + // Optionally, it takes a bit flag to drop the extension from the basename if desired. + // Examples: + // path/to/foo.bar => (foo.bar, foo) + // path/to/foo/bar => (bar, bar) + // path/to/foo/bar/ => (bar, bar) + // path/to/foo/bar/. => (., .) + // / => (/, /) + function automatic string str_path_basename(string filename, bit drop_extn = 1'b0); + int idx; + string basename; + + if (filename == "/") return filename; + filename = str_strip(.s(filename), .chars("/"), .lstrip(1'b0)); + idx = str_rfind(.s(filename), .sub("/")); + basename = filename.substr(idx + 1, filename.len() - 1); + + if (basename == ".") return basename; + if (drop_extn) begin + idx = str_find(.s(basename), .sub(".")); + if (idx == -1) idx = basename.len(); + basename = basename.substr(0, idx - 1); + end + return basename; + endfunction : str_path_basename + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/README.md b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/README.md new file mode 100644 index 0000000..844d014 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/README.md @@ -0,0 +1,3 @@ +# TileLink UVM Agent + +**TODO** diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_device_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_device_seq.sv new file mode 100644 index 0000000..1c8e7e2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_device_seq.sv @@ -0,0 +1,187 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A forever running sequence that responds to a TL request. +// +// This sequence supports in-order and out-of-order responses. It maintains a +// memory to record the write requests, so that when the same address is read, +// the originally written data is returned. This sequence runs forever, i.e. +// it needs to be forked off as a separate thread. It can be stopped gracefully +// by invoking the seq_stop() method. +class tl_device_seq #(type REQ = tl_seq_item, int unsigned AddrWidth = 32) extends dv_base_seq #( + .REQ (REQ), + .CFG_T (tl_agent_cfg), + .SEQUENCER_T(tl_sequencer)); + + // if enabled, rsp will be aborted if it's not accepted after given valid length + rand bit rsp_abort_after_d_valid_len; + // chance to abort rsp + int rsp_abort_pct = 0; + + int min_rsp_delay = 0; + int max_rsp_delay = 10; + mem_model_pkg::mem_model#(.AddrWidth(AddrWidth)) mem; + REQ req_q[$]; + bit out_of_order_rsp = 0; + + // Stops running this sequence. + protected bit stop; + + // chance to set d_error + int d_error_pct = 0; + + `uvm_object_param_utils(tl_device_seq #(REQ, AddrWidth)) + `uvm_object_new + + constraint en_req_abort_after_d_valid_len_c { + rsp_abort_after_d_valid_len dist { + 1 :/ rsp_abort_pct, + 0 :/ 100 - rsp_abort_pct + }; + } + + virtual task body(); + fork + begin: isolation_thread + fork + collect_request_thread(); + send_response_thread(); + join_any + // Wait for all requests to be serviced. + wait (req_q.size() == 0); + disable fork; + end + join + + // Clear the stop flag. It must be set (because collect_request_thread and send_response_thread + // don't stop otherwise). Clear it to allow a virtual sequence to start the same sequence object + // again if it wishes. + stop = 0; + endtask + + // A blocking task that retrieves a request from the TLM fifo, unless the seq is stopped. + // + // req: A req item retrieved from the TLM fifo and returned back to the caller. + protected virtual task get_a_chan_req(output REQ req); + fork + begin: isolation_thread + fork + begin + tl_seq_item item; + p_sequencer.a_chan_req_fifo.get(item); + `downcast(req, item) + end + wait (stop); + join_any + // Allow the rest of the statements in the same time-step to finish executing in the "other" + // thread, before disabling the fork. + #0; + disable fork; + end + join + endtask + + // A perpetually running task that collects and enqueues the incoming TL requests. + // + // The task finishes when the sequence is stopped, which is done be invoking the seq_stop() + // method. + protected virtual task collect_request_thread(); + int req_cnt; + forever begin + REQ req; + get_a_chan_req(req); + if (req != null) begin + req_q.push_back(req); + `uvm_info(`gfn, $sformatf("Received req[%0d] : %0s", + req_cnt, req.convert2string()), UVM_HIGH) + req_cnt++; + end + if (stop) break; + end + endtask + + // A perpetually running task that pops requests from the collected request queue and sends + // randomized responses. + protected virtual task send_response_thread(); + int rsp_cnt; + forever begin + REQ req, rsp; + wait(req_q.size > 0); + if (out_of_order_rsp) req_q.shuffle(); + + // peek at the front of the queue, but don't pop it: we want to see it again if the + // rsp_completed flag doesn't get set. + req = req_q[0]; + `downcast(rsp, req.clone()) + + randomize_rsp(rsp); + post_randomize_rsp(rsp); + update_mem(rsp); + start_item(rsp); + finish_item(rsp); + get_response(rsp); + + // Remove from req_q if response is completed. + if (rsp.rsp_completed) begin + void'(req_q.pop_front()); + `uvm_info(`gfn, $sformatf("Sent rsp[%0d] : %0s, req: %0s", + rsp_cnt, rsp.convert2string(), req.convert2string()), UVM_HIGH) + rsp_cnt++; + end + end + endtask + + // User-overridable function to randomize the response. The response is already cloned from the + // request, so the request (a_channel) information is already present. + virtual function void randomize_rsp(REQ rsp); + rsp.disable_a_chan_randomization(); + if (d_error_pct > 0) rsp.no_d_error_c.constraint_mode(0); + if (!(rsp.randomize() with + {rsp.d_valid_delay inside {[min_rsp_delay : max_rsp_delay]}; + if (rsp.a_opcode == tlul_pkg::Get) { + rsp.d_opcode == tlul_pkg::AccessAckData; + } else { + rsp.d_opcode == tlul_pkg::AccessAck; + } + rsp.d_size == rsp.a_size; + rsp.d_source == rsp.a_source; + d_error dist {0 :/ (100 - d_error_pct), 1 :/ d_error_pct}; + })) begin + `uvm_fatal(`gfn, "Cannot randomize rsp") + end + endfunction + + // callback after randomize seq, extended seq can override it to handle some non-rand variables + virtual function void post_randomize_rsp(REQ rsp); + `DV_CHECK_MEMBER_RANDOMIZE_FATAL(rsp_abort_after_d_valid_len) + rsp.rsp_abort_after_d_valid_len = rsp_abort_after_d_valid_len; + endfunction + + virtual function void update_mem(REQ rsp); + if (mem != null) begin + if (rsp.a_opcode inside {PutFullData, PutPartialData}) begin + bit [tl_agent_pkg::DataWidth-1:0] data; + data = rsp.a_data; + for (int i = 0; i < $bits(rsp.a_mask); i++) begin + if (rsp.a_mask[i]) begin + mem.write_byte(rsp.a_addr + i, data[7:0]); + end + data = data >> 8; + end + end else begin + for (int i = 2**rsp.a_size - 1; i >= 0; i--) begin + rsp.d_data = rsp.d_data << 8; + rsp.d_data[7:0] = mem.read_byte(rsp.a_addr+i); + end + end + end + endfunction + + // Stop running this seq and wait until it has finished gracefully. + virtual task seq_stop(); + stop = 1'b1; + wait_for_sequence_state(UVM_FINISHED); + endtask + +endclass : tl_device_seq diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_base_seq.sv new file mode 100644 index 0000000..20a9c60 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_base_seq.sv @@ -0,0 +1,86 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Default base class sequence that overrides base UVM functions. +// +// This sequence is not meant to be run standalone by itself (fatal error will be thrown if you +// do). It is instead meant to provide base utilities to construct different flavors of host +// sequences on top of it. These are as follows: +// +// 1. Provide late randomization for a_source +// a_source value needs to be randomized such that it does not equal to an in-flight request that +// has not yet returned. This means at the time of randomization, the DUT must already be ready to +// consume the req and apply it to the interface immediately. The tl_host_seq::randomize_req() +// performs exactly this function. However, it does not cater to the next bullet - driving TL +// transactions over the RAL model, which is done completely within the RAL layers. We need to +// ensure that the a_source value is randomized right before the DUT is ready to consume it, so we +// override the finish_item() to do so instead. +// +// 2. Serve as the parent_sequence for the RAL adapter +// The RAL map uses a dummy sequence to synchronize with the driver, after creating the bus req +// using the adapter. It does not provide any ability to perform "late randomization" of +// request. This causes our a_source constraints to be violated. Since we need this to ensure that +// the a_source is set taking into account the most up-to-date DUT state, we supply this sequence +// as the adapter's parent_sequence instead (see tl_reg_adapter for more details). The UVM map then +// uses this sequence instead of the dummy one to invoke start_item(), finish_item() and +// get_response() instead. So, instead of doing the late randomization in randomize_req(), we do it +// in finish_item() instead. +// +// 3. Provide ability to override and "fix" the a_source to a particular value. +// This is done to satisfy the use case where the TL host sends ALL requests with the same source +// ID. +class tl_host_base_seq #(type REQ_T = tl_seq_item) extends dv_base_seq #( + .REQ (REQ_T), + .CFG_T (tl_agent_cfg), + .SEQUENCER_T(tl_sequencer)); + + // The knob below allows the user to fix a_source in the reqs from a higher level sequence. It is + // the responsibility of the higher level sequence to ensure that the overridden_a_source_val is + // not illegal. To avoid painful debug, refrain from changing override_a_source_val while the + // sequence is still running. + bit override_a_source_val = 0; + bit [SourceWidth-1:0] overridden_a_source_val; + + `uvm_object_param_utils_begin(tl_host_base_seq #(REQ_T)) + `uvm_field_int(override_a_source_val, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPACK) + `uvm_field_int(overridden_a_source_val, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPACK) + `uvm_object_utils_end + + `uvm_object_new + + virtual function void get_cfg(uvm_sequence_item item); + if (p_sequencer != null) begin + cfg = p_sequencer.cfg; + end else begin + tl_sequencer seqr; + `downcast(seqr, item.get_sequencer()) + cfg = seqr.cfg; + end + endfunction + + // Overrides the base class implementation to late randomize / set a_source. + virtual task finish_item(uvm_sequence_item item, int set_priority = -1); + REQ req; + + `downcast(req, item) + if (cfg == null) get_cfg(req); + if (override_a_source_val) begin + req.a_source = overridden_a_source_val; + cfg.add_to_a_source_pend_q(req.a_source); + end else begin + cfg.randomize_a_source_in_req(req); + end + super.finish_item(item, set_priority); + endtask + + // Called after the rsp is received. + virtual task get_base_response(output uvm_sequence_item response, input int transaction_id = -1); + REQ rsp; + super.get_base_response(response, transaction_id); + `downcast(rsp, response) + if (cfg == null) get_cfg(rsp); + cfg.remove_from_a_source_pend_q(rsp.d_source); + endtask + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_custom_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_custom_seq.sv new file mode 100644 index 0000000..f5ffa3f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_custom_seq.sv @@ -0,0 +1,20 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Disable TL protocol related constraint on a_chan to create a fully customized tl_item for error +// cases +class tl_host_custom_seq #(type REQ_T = tl_seq_item) extends tl_host_single_seq #(REQ_T); + + `uvm_object_param_utils(tl_host_custom_seq #(REQ_T)) + `uvm_object_new + + virtual function void randomize_req(REQ req, int idx); + control_addr_alignment = 1; + control_rand_size = 1; + control_rand_opcode = 1; + req.disable_a_chan_protocol_constraint(); + super.randomize_req(req, idx); + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_protocol_err_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_protocol_err_seq.sv new file mode 100644 index 0000000..919844a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_protocol_err_seq.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// This seq will send an item that triggers d_error due to protocol violation +class tl_host_protocol_err_seq #(type REQ_T = tl_seq_item) extends tl_host_single_seq #(REQ_T); + + `uvm_object_param_utils(tl_host_protocol_err_seq #(REQ_T)) + `uvm_object_new + + // forever randomize the item until we find one that violates the TL protocol + virtual function void randomize_req(REQ req, int idx); + req.a_valid_delay = $urandom_range(min_req_delay, max_req_delay); + req.a_valid_delay.rand_mode(0); + req.randomize_a_chan_with_protocol_error(); + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_seq.sv new file mode 100644 index 0000000..1e9a7c7 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_seq.sv @@ -0,0 +1,104 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// TL host sequence supports multiple outstanding requests +// It generates 'req_cnt' number of completely random requests +class tl_host_seq #(type REQ_T = tl_seq_item) extends tl_host_base_seq #(REQ_T); + + rand int unsigned req_cnt; + // if enabled, req will be aborted if it's not accepted after given valid length + rand bit req_abort_after_a_valid_len; + // chance to abort req + int req_abort_pct = 0; + + REQ pending_req[$]; + int min_req_delay = 0; + int max_req_delay = 10; + + // The number of requests that have been started so far in body(). Even if there is contention for + // the sequencer, this will only be incremented when a sequence item gets granted. + int unsigned reqs_started = 0; + + `uvm_object_param_utils(tl_host_seq #(REQ_T)) + `uvm_object_new + + constraint req_abort_after_a_valid_len_c { + req_abort_after_a_valid_len dist { + 1 :/ req_abort_pct, + 0 :/ 100 - req_abort_pct + }; + } + + virtual task body(); + set_response_queue_depth(-1); + fork + begin : wait_response_thread + for (int i = 0; i < req_cnt; i++) begin + REQ req; + bit found_req; + get_response(rsp); + `uvm_info(`gfn, $sformatf("Received rsp[%0d] : %0s", + i, rsp.convert2string()), UVM_HIGH) + // in case of out of order rsp, find req that has same source as rsp + foreach (pending_req[i]) begin + if (rsp.d_source == pending_req[i].a_source) begin + req = pending_req[i]; + pending_req.delete(i); + process_response(req, rsp); + found_req = 1; + break; + end + end // foreach + if (!found_req && !csr_utils_pkg::under_reset) begin + `uvm_error(`gfn, $sformatf("fail to find matching req for rsp[%0d]: %0s", + i, rsp.convert2string())) + end + end // for + end : wait_response_thread + begin : request_thread + `uvm_info(`gfn, $sformatf("Start sending %0d host requests", req_cnt), UVM_HIGH) + for (int i = 0; i < req_cnt; i++) begin + req = REQ::type_id::create("req"); + pre_start_item(req); + start_item(req); + reqs_started++; + randomize_req(req, i); + post_randomize_req(req, i); + pending_req.push_back(req); // in case of device same cycle response + finish_item(req); + `uvm_info(`gfn, $sformatf("Sent req[%0d] : %0s", + i, req.convert2string()), UVM_HIGH) + end + end : request_thread + join + `uvm_info(`gfn, $sformatf("Finished sending %0d host requests", req_cnt), UVM_HIGH) + endtask + + // Invoked after creating the req and before invoking start_item(req). Suitable for inserting + // delays before start_item(). Example: avoid running out of source IDs. + virtual task pre_start_item(REQ req); + endtask + + // Request randomization, override this function to do custom request generation. Invoked after + // start_item(). Not suitable for setting a_source, since that is handled in + // `tl_host_base_seq::finish_item()` instead, to facilitate late randomization when accesses are + // initiated from UVM RAL. + virtual function void randomize_req(REQ req, int idx); + if (!(req.randomize() with { + a_valid_delay inside {[min_req_delay:max_req_delay]};})) begin + `uvm_fatal(`gfn, "Cannot randomize req") + end + endfunction + + // callback after randomize seq, extened seq can override it to handle some non-rand variables + virtual function void post_randomize_req(REQ req, int idx); + `DV_CHECK_MEMBER_RANDOMIZE_FATAL(req_abort_after_a_valid_len) + req.req_abort_after_a_valid_len = req_abort_after_a_valid_len; + endfunction + + // A reserved function that can be extended to process response packet + virtual function void process_response(REQ req, REQ rsp); + endfunction + +endclass : tl_host_seq diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_single_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_single_seq.sv new file mode 100644 index 0000000..1bfa784 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_host_single_seq.sv @@ -0,0 +1,50 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Extend host seq to send single specific item constructed by the caller +class tl_host_single_seq #(type REQ_T = tl_seq_item) extends tl_host_seq #(REQ_T); + rand bit write; + rand bit [AddrWidth-1:0] addr; + rand bit [OpcodeWidth-1:0] opcode; + rand bit [SizeWidth-1:0] size; + rand bit [SourceWidth-1:0] source; + rand bit [MaskWidth-1:0] mask; + rand bit [DataWidth-1:0] data; + + // for most cases, upper seq just needs to provide addr[$:2], data, mask value, write. + // addr[1:0]/size/source/opcode can be randomized in tl_seq_item based on mask value + bit control_addr_alignment = 0; + bit control_rand_size = 0; + bit control_rand_source = 0; + bit control_rand_opcode = 0; + + `uvm_object_param_utils(tl_host_single_seq #(REQ_T)) + `uvm_object_new + + constraint req_cnt_eq_1_c { req_cnt == 1; } + + virtual function void randomize_req(REQ req, int idx); + if (!(req.randomize() with { + a_valid_delay inside {[min_req_delay:max_req_delay]}; + a_data == data; + a_mask == mask; + a_addr[AddrWidth-1:2] == addr[AddrWidth-1:2]; + control_addr_alignment -> a_addr[1:0] == addr[1:0]; + control_rand_size -> a_size == size; + control_rand_source -> a_source == source; + if (control_rand_opcode) { + a_opcode == opcode; + } else { + if (write) { + a_opcode inside {tlul_pkg::PutPartialData, tlul_pkg::PutFullData}; + } else { + a_opcode == tlul_pkg::Get; + } + } + })) begin + `uvm_fatal(`gfn, "Cannot randomize req") + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_seq_list.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_seq_list.sv new file mode 100644 index 0000000..cc99fbf --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/seq_lib/tl_seq_list.sv @@ -0,0 +1,10 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +`include "tl_host_base_seq.sv" +`include "tl_host_seq.sv" +`include "tl_host_single_seq.sv" +`include "tl_host_custom_seq.sv" +`include "tl_host_protocol_err_seq.sv" +`include "tl_device_seq.sv" diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.core b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.core new file mode 100644 index 0000000..c6e6caf --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.core @@ -0,0 +1,40 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:tl_agent" +description: "TileLink Uncached Lite (TL-UL) DV UVM agent" + +filesets: + files_dv: + depend: + - lowrisc:tlul:headers:0.1 + - lowrisc:prim:secded + - lowrisc:dv:mem_model + - lowrisc:dv:dv_lib + - lowrisc:opentitan:bus_params_pkg + files: + - tl_if.sv + - tl_agent_pkg.sv + - tl_seq_item.sv: {is_include_file: true} + - tl_agent_cfg.sv: {is_include_file: true} + - tl_agent_cov.sv: {is_include_file: true} + - tl_device_driver.sv: {is_include_file: true} + - tl_host_driver.sv: {is_include_file: true} + - tl_sequencer.sv: {is_include_file: true} + - tl_monitor.sv: {is_include_file: true} + - tl_agent.sv: {is_include_file: true} + - tl_reg_adapter.sv: {is_include_file: true} + - seq_lib/tl_seq_list.sv: {is_include_file: true} + - seq_lib/tl_host_base_seq.sv: {is_include_file: true} + - seq_lib/tl_host_seq.sv: {is_include_file: true} + - seq_lib/tl_host_single_seq.sv: {is_include_file: true} + - seq_lib/tl_host_custom_seq.sv: {is_include_file: true} + - seq_lib/tl_host_protocol_err_seq.sv: {is_include_file: true} + - seq_lib/tl_device_seq.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.sv new file mode 100644 index 0000000..b2a5fdc --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent.sv @@ -0,0 +1,41 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// --------------------------------------------- +// TileLink agent +// --------------------------------------------- +class tl_agent extends dv_base_agent#( + .CFG_T (tl_agent_cfg), + .DRIVER_T (tl_base_driver), + .HOST_DRIVER_T (tl_host_driver), + .DEVICE_DRIVER_T (tl_device_driver), + .SEQUENCER_T (tl_sequencer), + .MONITOR_T (tl_monitor), + .COV_T (tl_agent_cov) + ); + + `uvm_component_utils(tl_agent) + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + // get tl_if handle if it is not already supplied + if (cfg.vif == null && !uvm_config_db#(virtual tl_if)::get(this, "", "vif", cfg.vif)) begin + `uvm_fatal(`gfn, "failed to get tl_if handle from uvm_config_db") + end + cfg.vif.if_mode = cfg.if_mode; + endfunction + + function void connect_phase(uvm_phase phase); + super.connect_phase(phase); + if (cfg.if_mode == dv_utils_pkg::Device) begin + if (cfg.device_can_rsp_on_same_cycle) begin + monitor.a_chan_same_cycle_rsp_port.connect(sequencer.a_chan_req_fifo.analysis_export); + end else begin + monitor.a_chan_port.connect(sequencer.a_chan_req_fifo.analysis_export); + end + end + endfunction +endclass : tl_agent diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cfg.sv new file mode 100644 index 0000000..ef4630f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cfg.sv @@ -0,0 +1,251 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +// --------------------------------------------- +// Configuration class for TileLink agent +// --------------------------------------------- +class tl_agent_cfg extends dv_base_agent_cfg; + + virtual tl_if vif; + // TileLink conformance level supported by this agent + // Right now only TL-UL is supported + tl_level_e tl_level = kTLUL; + + // Maximum number of outstanding transactions supported by the DUT. + // 0: Unlimited from the host perspective, might be back-pressured by the device + // 1: Only single transaction at a time + // n: Number of maximum outstanding requests + + // This is initialized to an arbitrary value. The DUT may actually support higher or lower than + // this number. Calculating exactly how many outstanding transactions the DUT supports is hard to + // determine. For most comportable IPs, it will likely be less than 16. The testbench attempts to + // pump the DUT with as many transactions as possible. The missing coverage in + // `tl_agent_cov::max_outstanding_cfg` will then indicate what the design actually supported. + // The designer must then confirm if that looks correct (in the coverage report), and then this + // value is updated accordingly in the DUT's test / env class. + // + // Note that this is a device constant. It should only be set within the scope of the test class' + // build_phase. Once set, it MUST NOT BE modified whatsoever. + int unsigned max_outstanding_req = 16; + + // If allow_a_valid_drop_wo_a_ready then the host can de-assert valid if there is no response from + // the device on the A channel. The other knobs control how this works. Each transaction has a + // "valid_len". If the host hasn't seen a ready after holding valid high for that many cycles, it + // will de-assert valid for a time before retrying. + // + // If use_seq_item_a_valid_len is true then valid_len will be read from the sequence item (field + // a_valid_len). If not, it will be picked uniformly between a_valid_len_min and a_valid_len_max. + bit allow_a_valid_drop_wo_a_ready = 1; + bit use_seq_item_a_valid_len; + int unsigned a_valid_len_min = 1; + int unsigned a_valid_len_max = 10; + + // Knobs controlling when we de-assert valid in device mode: see above for the host mode + // equivalent. + bit use_seq_item_d_valid_len; + bit allow_d_valid_drop_wo_d_ready; + int unsigned d_valid_len_min = 1; + int unsigned d_valid_len_max = 10; + + // TileLink channel valid delay (host mode) + bit use_seq_item_a_valid_delay; + int unsigned a_valid_delay_min = 0; + int unsigned a_valid_delay_max = 10; + + // TileLink channel ready delay (host mode) + int unsigned d_ready_delay_min = 0; + int unsigned d_ready_delay_max = 10; + + // TileLink channel ready delay (device mode) + int unsigned a_ready_delay_min = 0; + int unsigned a_ready_delay_max = 10; + + // TileLink channel ready delay (device mode) + bit use_seq_item_d_valid_delay; + int unsigned d_valid_delay_min = 0; + int unsigned d_valid_delay_max = 10; + + // TL spec requires host to set d_ready = 1 when a_valid = 1, but some design may not follow this + // rule. Details at #3208. Use below knob to control + bit host_can_stall_rsp_when_a_valid_high = 0; + + // knob for device to enable/disable same cycle response + bit device_can_rsp_on_same_cycle = 0; + + // A configuration flag for the monitor that configures whether it should synchronise concurrent A + // and D transactions or not. See note above the definition of channel_dir_port in tl_monitor.sv + // for details. + bit synchronise_ports = 1'b0; + + // for same cycle response, need to know when a_valid and other data/control are available, so + // that monitor can sample it, then send to sequence to get data for response in the same cycle + // 10 means 10% of TL clock period. This var is only use when device_can_rsp_on_same_cycle = 1 + time time_a_valid_avail_after_sample_edge = 1ns; + + // Sets the valid a_source width. The DUT may support fewer bits than the whole SourceWidth bits. + int unsigned valid_a_source_width = SourceWidth; + + // Maintains a queue of a_source values used in previous TL requests. + // + // The queue size maxes out at max_outstanding_req value, beyond which the a_source values can + // be recycled. The a_source value for a new request is randomized such that it does not match any + // in this queue. The new a_source is pushed into the back of the queue and the oldest one is + // popped from the front when the max size is reached. + // + // NOTE: If a tl_seq_item is being constructed for a new host request (whether in the TL + // sequences, adapter or elsewhere), it is mandatory to constrain the tl_seq_item::a_source to NOT + // match what already exists in the queue. Otherwise, it will violate the spec and the design will + // end up throwing assertion errors. It is recommended to use the `randomize_a_source_in_req()` + // function below to achieve this. + bit [SourceWidth-1:0] a_source_pend_q[$]; + + // Records the a_source value that was last released from the `a_source_pend_q` pool. + // We influence the randomization of a new req's a_source to reuse this 20% (also a knob) of the + // time. The initial value is randomized (see post_randomize()). + protected bit [SourceWidth-1:0] last_a_source_released; + + // Sets the randomization dist weight for a new a_source value to be constrained to the last + // a_source released. This only ATTEMPTS to set the a_source to the last_a_source_released value - + // it is not always guaranteed even at 100%, especially if the test does non-blocking accesses. + rand int unsigned use_last_a_source_released_pct = 20; + + constraint a_source_eq_last_a_source_released_pct_c { + use_last_a_source_released_pct <= 100; + use_last_a_source_released_pct dist { + [0:19] :/ 1, + [20:59] :/ 1, + [60:99] :/ 1, + 100 :/ 1 + }; + } + + // TLUL allows host to switch content if the item isn't accepted. RAL doesn't provide interface + // to control this. Use this knob to allow tl_reg_adapter to randomize req_abort_after_a_valid_len + // Note: below set the chance to abort after a_valid_len in tl_reg_adapter. if > 0, csr access may + // return UVM_NOT_OK when the item is aborted without accepted. + int unsigned csr_access_abort_pct_in_adapter = 0; + + // Indicate whether to check TLUL errors. + // Added to allow some TLUL checks to be ignored on certain scenarios. + bit check_tl_errs = 1'b1; + + // Invalidate drive option + // Setting these to '1', make driver send 'x' during invalidate cycle. + // Setting these to '0', make driver send 'random value' during invalidate cycle. + rand bit invalidate_a_x; + rand bit invalidate_d_x; + + constraint invalidate_a_channel_op_c { + invalidate_a_x dist { 1 := 7, 0 := 3}; + } + constraint invalidate_d_channel_op_c { + invalidate_d_x dist { 1 := 7, 0 := 3}; + } + + + `uvm_object_utils_begin(tl_agent_cfg) + `uvm_field_int(max_outstanding_req, UVM_DEFAULT) + `uvm_field_enum(tl_level_e, tl_level, UVM_DEFAULT) + `uvm_field_int(a_ready_delay_min, UVM_DEFAULT) + `uvm_field_int(a_ready_delay_max, UVM_DEFAULT) + `uvm_field_int(d_ready_delay_min, UVM_DEFAULT) + `uvm_field_int(d_ready_delay_max, UVM_DEFAULT) + `uvm_field_int(host_can_stall_rsp_when_a_valid_high, UVM_DEFAULT) + `uvm_field_int(device_can_rsp_on_same_cycle, UVM_DEFAULT) + `uvm_field_int(time_a_valid_avail_after_sample_edge, UVM_DEFAULT) + `uvm_field_int(csr_access_abort_pct_in_adapter, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_object_new + + function void post_randomize(); + // We want to randomize the initial value of last_a_source_released, while respecting any + // constraints on a_source in the tl_seq_item (and its extensions). So we do it here instead. + tl_seq_item dummy = tl_seq_item::type_id::create("dummy"); + `DV_CHECK_RANDOMIZE_FATAL(dummy) + randomize_a_source_in_item(.item(dummy), .use_last_a_source_released(1'b0)); + last_a_source_released = dummy.a_source; + endfunction + + // Randomizes a_source within an item (protected function). + // + // This function takes the tl_seq_item object to specifically randomize the a_source such that it + // does not match an existing one in the a_source_q. This randomization also takes into account + // any existing constraints on a_source that may exist in the class definition. The new a_source + // value is randomized to be equal to the last a_source released from the a_source_pend_q + // 20% of the time (weight is configurable). + // + // For actual reqs made out to the DUT, use randomize_a_source_in_req(). + protected function void randomize_a_source_in_item(tl_seq_item item, + bit use_last_a_source_released); + bit [SourceWidth - 1 : 0] a_source; + + // Use std::randomize instead of calling item.randomize(a_source). item.randomize will invoke + // post_randomize. If user does sth after post_randomize before calling finish_item, invoking + // post_randomize may override that. + // For example, if we use item.randomize(a_source) + // item.randomize(); // in post_randomize, instr_type is set to False + // item.instr_type = True; + // finish_item(item); // finish_item will call randomize_a_source_in_item. + // // item.randomize(a_source) will invoke post_randomize, instr_type is set + // // to False again. + `DV_CHECK_STD_RANDOMIZE_WITH_FATAL(a_source, + // use soft constraint as seq may still send req when all the valid a_source are used + (!in_reset) -> soft !(a_source inside {a_source_pend_q}); + // Set the upper a_source bits that are unused to 0. + (a_source >> valid_a_source_width) == 0; + // We cannot guarantee that last_a_source_released is not in a_source_pend_q, + // especially if the test does non-blocking accesses. If the a_source for the new req + // needs to be equal to last_a_source_released, we will need the bottom constraint to be a + // soft one to *potentially* avoid violating the previous constraint. Only way to guarantee + // that the new a_source == last_a_source_released is to ensure the test only does blocking + // accesses. + use_last_a_source_released && !(last_a_source_released inside {a_source_pend_q}) + -> soft (a_source == last_a_source_released);) + item.a_source = a_source; + `uvm_info(`gfn, $sformatf("a_source_pend_q: %p a_source: %0h", a_source_pend_q, item.a_source), UVM_DEBUG) + endfunction + + // Randomizes the a_source for a 'real' req (public version of the above function). + // + // Invokes randomize_a_source_in_item() and adds the a_source for the new req to the queue. + virtual function void randomize_a_source_in_req(tl_seq_item item); + bit use_last_a_source_released; + use_last_a_source_released = ($urandom_range(1, 100) <= use_last_a_source_released_pct); + randomize_a_source_in_item(item, use_last_a_source_released); + add_to_a_source_pend_q(item.a_source); + endfunction + + // Adds a_source to the a_source_pend_q. + // + // Ensures that the queue does not exceed the max outstanding req size. Pops the oldest a_source + // used to last_a_source_released. + virtual function void add_to_a_source_pend_q(bit [SourceWidth-1:0] a_source); + if (in_reset) return; + if (a_source_pend_q.size() == max_outstanding_req) begin + last_a_source_released = a_source_pend_q.pop_front(); + end + a_source_pend_q.push_back(a_source); + `uvm_info(`gfn, $sformatf("a_source_pend_q: %p", a_source_pend_q), UVM_DEBUG) + endfunction + + // Removes the last used a_source from a_source_pend_q. + // + // Invoked by the tl_host_base_seq::get_base_response() which overrides the default UVM + // implementation. It is recommended that all TL host sequence flavors that do not extended from + // tl_host_base_seq invoke this function similarly to avoid running out of a_source IDs when + // creating non-blocking requests. + virtual function void remove_from_a_source_pend_q(bit [SourceWidth-1:0] a_source); + int result[$]; + + // Responses can return out of order, so the a_source can be anywhere in the queue. + result = a_source_pend_q.find_first_index with (item == a_source); + if (result.size() == 1) begin + a_source_pend_q.delete(result.pop_front()); + last_a_source_released = a_source; + `uvm_info(`gfn, $sformatf("a_source_pend_q: %p", a_source_pend_q), UVM_DEBUG) + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cov.sv new file mode 100644 index 0000000..17a0ff1 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_cov.sv @@ -0,0 +1,131 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Covergroup: pending_req_on_rst_cg +// define bins for having pending request while on reset +covergroup pending_req_on_rst_cg(string name, string path) with function + sample(bit req_pending); + option.per_instance = 1; + option.name = {path, "::", name}; + + cp_req_pending: coverpoint req_pending { + bins values[] = {0, 1}; + } +endgroup + +// coverage for sampling all the values of outstanding req, up to its max +covergroup max_outstanding_cg(string name, int max_outstanding, string path) with function + sample(int num_outstanding); + option.per_instance = 1; + option.name = {path, "::", name}; + + cp_num_of_outstanding: coverpoint num_outstanding { + bins values[] = {[1:max_outstanding]}; + } +endgroup : max_outstanding_cg + +covergroup tl_a_chan_cov_cg(string name, int valid_source_width, string path) with function + sample(tl_seq_item item); + option.per_instance = 1; + option.name = {path, "::", name}; + + cp_opcode: coverpoint item.a_opcode { + bins values[] = {Get, PutFullData, PutPartialData}; + } + cp_mask: coverpoint item.a_mask { + bins all_enables = {{MaskWidth{1'b1}}}; + bins others = default; + } + cp_size: coverpoint item.a_size { + bins biggest_size = {$clog2(DataWidth >> 3)}; + bins others = default; + } + cp_source: coverpoint item.a_source { + bins valid_sources[] = {[0 : 2 << (valid_source_width - 1) - 1]}; + } + cross cp_opcode, cp_mask, cp_size; +endgroup : tl_a_chan_cov_cg + +covergroup tl_d_chan_cov_cg(string name, string path) with function sample(tl_seq_item item); + option.per_instance = 1; + option.name = {path, "::", name}; + + cp_opcode: coverpoint item.d_opcode { + bins values[] = {AccessAckData, AccessAckData}; + } + cp_size: coverpoint item.a_size { + bins biggest_size = {$clog2(DataWidth >> 3)}; + bins others = default; + } + cp_error: coverpoint item.d_error; + cross cp_opcode, cp_size; +endgroup : tl_d_chan_cov_cg + +class tl_agent_cov extends dv_base_agent_cov #(tl_agent_cfg); + // sample these at proper location, for example, m_pending_req_on_rst_cg called after reset + pending_req_on_rst_cg m_pending_req_on_rst_cg; + max_outstanding_cg m_max_outstanding_cg; + bit_toggle_cg_wrap m_outstanding_item_w_same_addr_cov_obj; + + // knob to create m_outstanding_item_w_same_addr_cov_obj, even design supports more than + // 1 outstanding items, but may not support they use the same address + // TODO(#16840): may need to disable it for spi_device and hmac even they support 2 outstanding + // items + bit en_cov_outstanding_item_w_same_addr = 1; + + // item coverage, call sample(item) at the end of transaction to sample them + tl_a_chan_cov_cg m_tl_a_chan_cov_cg; // host mode + tl_d_chan_cov_cg m_tl_d_chan_cov_cg; // device mode + bit_toggle_cg_wrap m_tl_error_cov_objs[string]; // host mode + + `uvm_component_utils(tl_agent_cov) + `uvm_component_new + + function void build_phase(uvm_phase phase); + string tl_error_names[] = {"invalid_a_opcode", + "PutFullData_mask_not_match_size", + "addr_not_align_mask", + "addr_not_align_size", + "mask_not_in_active_lanes", + "size_over_max"}; + super.build_phase(phase); + m_pending_req_on_rst_cg = new("m_pending_req_on_rst_cg", `gfn); + m_max_outstanding_cg = new("m_max_outstanding_cg", cfg.max_outstanding_req, `gfn); + + if (cfg.max_outstanding_req > 1 && en_cov_outstanding_item_w_same_addr) begin + m_outstanding_item_w_same_addr_cov_obj = + new({`gfn, "::m_outstanding_item_w_same_addr_cov_obj"}); + end + + if (cfg.if_mode == dv_utils_pkg::Host) begin + m_tl_a_chan_cov_cg = new("m_tl_a_chan_cov_cg", cfg.valid_a_source_width, `gfn); + foreach (tl_error_names[i]) begin + m_tl_error_cov_objs[tl_error_names[i]] = new({`gfn, "::", tl_error_names[i]}); + end + end else begin // device mode + m_tl_d_chan_cov_cg = new("m_tl_d_chan_cov_cg", `gfn); + end + endfunction : build_phase + + // sample info that is within the seq_item, this will be called at the end of transaction + virtual function void sample(tl_seq_item item); + if (cfg.if_mode == dv_utils_pkg::Host) begin + if (!item.get_exp_d_error()) begin // no error + m_tl_a_chan_cov_cg.sample(item); + end else begin // error cases + m_tl_error_cov_objs["invalid_a_opcode"].sample(item.get_error_a_opcode_invalid()); + m_tl_error_cov_objs["PutFullData_mask_not_match_size"].sample( + item.get_error_PutFullData_mask_size_mismatched()); + m_tl_error_cov_objs["addr_not_align_mask"].sample(item.get_error_addr_size_misaligned()); + m_tl_error_cov_objs["addr_not_align_size"].sample(item.get_error_addr_size_misaligned()); + m_tl_error_cov_objs["mask_not_in_active_lanes"].sample( + item.get_error_mask_not_in_active_lanes()); + m_tl_error_cov_objs["size_over_max"].sample(item.get_error_size_over_max()); + end + end else begin // device mode + m_tl_d_chan_cov_cg.sample(item); + end + endfunction : sample + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_pkg.sv new file mode 100644 index 0000000..adfd0c0 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_agent_pkg.sv @@ -0,0 +1,89 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +package tl_agent_pkg; + // dep packages + import uvm_pkg::*; + import bus_params_pkg::*; + import tlul_pkg::*; + import mem_model_pkg::*; + import dv_base_agent_pkg::*; + import dv_lib_pkg::*; + import dv_base_reg_pkg::*; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + parameter int AddrWidth = bus_params_pkg::BUS_AW; + parameter int DataWidth = bus_params_pkg::BUS_DW; + parameter int SizeWidth = bus_params_pkg::BUS_SZW; + parameter int MaskWidth = bus_params_pkg::BUS_DBW; + parameter int SourceWidth = bus_params_pkg::BUS_AIW; + parameter int AUserWidth = bus_params_pkg::BUS_AUW; + parameter int DUserWidth = bus_params_pkg::BUS_DUW; + parameter int OpcodeWidth = 3; + parameter int InstrTypeLsbPos = get_instr_type_lsb_pos(); + parameter int InstrTypeMsbPos = get_instr_type_msb_pos(); + + typedef class tl_seq_item; + typedef class tl_agent_cfg; + // reuse dv_base_driver as is with the right parameter set + typedef dv_base_driver #(tl_seq_item, tl_agent_cfg) tl_base_driver; + + // TileLink conformance level + typedef enum bit [1:0] { + kTLUL, + kTLUH, + kTLC + } tl_level_e; + + typedef enum { + AddrChannel, + DataChannel + } tl_channels_e; + + function automatic void enable_logging(string file_name="tl_agent.log"); + int log_fd = $fopen(file_name,"w"); + `uvm_info($sformatf("%m"), $sformatf("The TL agent transaction log will be saved to %0s", + file_name), UVM_LOW) + uvm_top.set_report_id_verbosity_hier("tl_logging", UVM_HIGH); + uvm_top.set_report_id_file_hier("tl_logging", log_fd); + uvm_top.set_report_id_verbosity_hier("tl_logging", UVM_HIGH); + // Always save in a separate log file and disable printing on the screen + uvm_top.set_report_severity_id_action_hier(UVM_INFO, "tl_logging", UVM_LOG); + uvm_top.set_report_severity_id_action_hier(UVM_WARNING, + "tl_logging", UVM_DISPLAY | UVM_LOG); + uvm_top.set_report_severity_id_action_hier(UVM_ERROR, + "tl_logging", UVM_DISPLAY | UVM_LOG | UVM_COUNT); + uvm_top.set_report_severity_id_action_hier(UVM_FATAL, + "tl_logging", UVM_DISPLAY | UVM_LOG | UVM_EXIT); + endfunction + + // Extract the LSB position of the instr_type field from struct tl_a_user_t + function automatic int get_instr_type_lsb_pos(); + tl_a_user_t tl_a_user = '0; + tl_a_user.instr_type = prim_mubi_pkg::mubi4_t'(1); + return $clog2(tl_a_user); + endfunction : get_instr_type_lsb_pos + + // Extract the MSB position of the instr_type field from struct tl_a_user_t + function automatic int get_instr_type_msb_pos(); + tl_a_user_t tl_a_user = '0; + return get_instr_type_lsb_pos()+$size(tl_a_user.instr_type)-1; + endfunction : get_instr_type_msb_pos + + `include "tl_seq_item.sv" + `include "tl_agent_cfg.sv" + `include "tl_agent_cov.sv" + `include "tl_host_driver.sv" + `include "tl_device_driver.sv" + `include "tl_sequencer.sv" + `include "tl_monitor.sv" + `include "tl_agent.sv" + `include "tl_reg_adapter.sv" + `include "tl_seq_list.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_device_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_device_driver.sv new file mode 100644 index 0000000..ca17738 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_device_driver.sv @@ -0,0 +1,128 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +// --------------------------------------------- +// TileLink device driver +// --------------------------------------------- +class tl_device_driver extends tl_base_driver; + + `uvm_component_utils(tl_device_driver) + `uvm_component_new + + virtual task get_and_drive(); + // Wait for initial reset to pass. + wait(cfg.vif.rst_n === 1'b0); + wait(cfg.vif.rst_n === 1'b1); + fork + a_channel_thread(); + d_channel_thread(); + join_none + endtask + + task on_enter_reset(); + invalidate_d_channel(); + cfg.vif.d2h_int.a_ready <= 1'b0; + + // Make sure that seq_item_port FIFO will be empty when coming out of reset + `DV_CHECK_EQ(seq_item_port.has_do_available(), 0); + endtask + + virtual task a_channel_thread(); + int unsigned ready_delay; + + forever begin + ready_delay = $urandom_range(cfg.a_ready_delay_min, cfg.a_ready_delay_max); + repeat(ready_delay) @(cfg.vif.device_cb); + cfg.vif.device_cb.d2h.a_ready <= 1'b1; + @(cfg.vif.device_cb); + cfg.vif.device_cb.d2h.a_ready <= 1'b0; + end + endtask + + virtual task d_channel_thread(); + bit req_found; + tl_seq_item rsp; + + forever begin + int unsigned d_valid_delay, d_valid_len, d_valid_cnt; + bit rsp_done, rsp_abort; + seq_item_port.get_next_item(rsp); + + while (!rsp_done && !rsp_abort && cfg.vif.rst_n) begin + if (cfg.use_seq_item_d_valid_delay) begin + d_valid_delay = rsp.d_valid_delay; + end else begin + d_valid_delay = $urandom_range(cfg.d_valid_delay_min, cfg.d_valid_delay_max); + end + + if (cfg.allow_d_valid_drop_wo_d_ready || rsp.rsp_abort_after_d_valid_len) begin + if (cfg.use_seq_item_d_valid_len) begin + d_valid_len = rsp.d_valid_len; + end else begin + d_valid_len = $urandom_range(cfg.d_valid_len_min, cfg.d_valid_len_max); + end + end + + // break delay loop if reset asserted to release blocking + repeat (d_valid_delay) begin + if (!cfg.vif.rst_n) break; + else @(cfg.vif.device_cb); + end + if (cfg.vif.rst_n) begin + cfg.vif.d2h_int.d_valid <= 1'b1; + cfg.vif.d2h_int.d_opcode <= tl_d_op_e'(rsp.d_opcode); + cfg.vif.d2h_int.d_data <= rsp.d_data; + cfg.vif.d2h_int.d_source <= rsp.d_source; + cfg.vif.d2h_int.d_param <= rsp.d_param; + cfg.vif.d2h_int.d_error <= rsp.d_error; + cfg.vif.d2h_int.d_sink <= rsp.d_sink; + cfg.vif.d2h_int.d_user <= rsp.d_user; + cfg.vif.d2h_int.d_size <= rsp.d_size; + end + + // wait for ready or reaching d_valid_len + d_valid_cnt = 0; + while (cfg.vif.rst_n) begin + @(cfg.vif.device_cb); + d_valid_cnt++; + if (cfg.vif.device_cb.h2d.d_ready) begin + rsp_done = 1; + break; + end else if ((cfg.allow_d_valid_drop_wo_d_ready || rsp.rsp_abort_after_d_valid_len) + && d_valid_cnt >= d_valid_len) begin + if (rsp.rsp_abort_after_d_valid_len) rsp_abort = 1; + invalidate_d_channel(); + if (!cfg.vif.rst_n) @(cfg.vif.device_cb); + break; + end + end // while (!cfg.vif.rst_n) + end // while (!rsp_done && cfg.vif.rst_n) + invalidate_d_channel(); + rsp.rsp_completed = !rsp_abort; + seq_item_port.item_done(); + seq_item_port.put_response(rsp); + end + endtask : d_channel_thread + + function void invalidate_d_channel(); + if (cfg.invalidate_d_x) begin + cfg.vif.d2h_int.d_opcode <= tlul_pkg::tl_d_op_e'('x); + cfg.vif.d2h_int.d_param <= '{default:'x}; + cfg.vif.d2h_int.d_size <= '{default:'x}; + cfg.vif.d2h_int.d_source <= '{default:'x}; + cfg.vif.d2h_int.d_sink <= '{default:'x}; + cfg.vif.d2h_int.d_data <= '{default:'x}; + cfg.vif.d2h_int.d_user <= '{default:'x}; + cfg.vif.d2h_int.d_error <= 1'bx; + cfg.vif.d2h_int.d_valid <= 1'b0; + end else begin // if (cfg.invalidate_d_x) + tlul_pkg::tl_d2h_t d2h; + `DV_CHECK_STD_RANDOMIZE_FATAL(d2h) + d2h.d_valid = 1'b0; + cfg.vif.d2h_int <= d2h; + end + endfunction : invalidate_d_channel + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_host_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_host_driver.sv new file mode 100644 index 0000000..9be3489 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_host_driver.sv @@ -0,0 +1,381 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// A TileLink driver that behaves as a host, initiating TileLink transactions +class tl_host_driver extends tl_base_driver; + `uvm_component_utils(tl_host_driver) + + // A queue of sequence items corresponding to the requests have been sent on the A channel but + // haven't yet had a response on the D channel. + protected tl_seq_item pending_a_req[$]; + + extern function new (string name, uvm_component parent); + + // Drive items received from the sequencer. This implements a task declared in dv_base_driver. + extern task get_and_drive(); + + // Called at the start of a reset. Clear output signals and internal state. This implements a task + // declared in dv_base_driver. + extern task on_enter_reset(); + + // Called at the end of a reset. Make sure that all sequence items have been properly flushed + // while we were in reset. + extern function void on_leave_reset(); + + // Wait for the next edge of host_cb. Stops early if reset is asserted. + extern protected task wait_clk_or_rst(); + + // Get items from the sequencer and drive them on the A channel. This runs forever and runs + // synchronised with the TL clock. + // + // If we go into reset, this will flush all pending items from the sequencer, and continue + // flushing items until reset is deasserted. + extern protected task a_channel_thread(); + + // Send a request, req, on the A channel + // + // The steps to drive the request: + // + // - Wait until there is no pending response for req.a_source. + // - Call send_a_request_body to assert a_valid and similar signals, looping if + // send_a_request_body reports a timeout. + // + // Once the request has been driven call seq_item_port.item_done(), causing the sequencer to allow + // the item to finish. + // + // If a reset is asserted at any point, the task will stop driving the request and send a response + // as well as calling seq_item_port.item_done() (representing the D channel message that would + // normally come back). + extern protected task send_a_channel_request(tl_seq_item req); + + // Send the body of a request on the A channel. + // + // To do so, this writes a_valid and the other A signals and then waits for a clock edge where we + // see a_ready true, at which point the A channel transaction has been made. + // + // If a_ready doesn't go high, it's possible that there will be a timeout after a_valid_len + // cycles. If this is enabled and the timeout happens then remove the item from pendng_a_req, + // and invalidate the channel. + // + // req: The request whose body should be sent. + // + // a_valid_delay: The number of host clock cycles to wait before asserting a_valid. + // + // a_valid_len: The number of host clock cycles a_valid is held high waiting for a_ready to go + // high and accept the request. If req has req_abort_after_a_valid_len set, or if + // the cfg has allow_a_valid_drop_wo_a_ready, then the driver will drop a_valid + // again after that time, write 'x values to the A channel and exit. + // + // req_done [out] This is set to 1'b1 if a_ready has gone high on the host clock. + // + // req_abort [out] This is set to 1'b1 if the host decides to drop a_valid because the receiver + // hasn't responded with a_ready. + extern local task send_a_request_body(tl_seq_item req, + int unsigned a_valid_delay, + int unsigned a_valid_len, + output bit req_done, + output bit req_abort); + + // Drive the d_ready pin (as the host) forever to allow a device to send responses back + // + // This waits a random number of host clock cycles (between cfg.d_ready_delay_min and + // cfg.d_ready_delay_max) and then pulses d_ready high for a cycle before dropping again. + // + // If cfg.host_can_stall_rsp_when_a_valid_high is false then the driver setting a_valid high will + // cause this task to skip any wait period with d_ready low and hold it high. + extern protected task d_ready_rsp(); + + // Collect responses on the D channel + // + // A response is signalled by the device setting d_valid when we (the host) have set d_ready. The + // request to which this is a response is found by searching for d_source in the queue of pending + // requests. + // + // When a match is found, this task puts a response to seq_item_port (sending it back to the + // sequencer), then deletes the pending request. + // + // If the cfg.in_reset is high, this task responds to all pending requests (with potentially silly + // data values) + extern protected task d_channel_thread(); + + // Return true if the given source is the a_source value of some pending request. + extern protected function bit is_source_in_pending_req(bit [SourceWidth-1:0] source); + + // Set a_valid to zero and write rubbish to the A channel to invalidate it. + // + // If direct is true, this directly drives the vif.h2d_int signal as well as setting signals in + // host_cb (meaning that this will have immediate effect, even if the clock is not running). + // + // If cfg.invalidate_a_x is true then all fields other than a_valid will be set to 'x. If it is + // false then all the fields will be randomised. + extern local task invalidate_a_channel(bit direct); +endclass : tl_host_driver + +function tl_host_driver::new (string name, uvm_component parent); + super.new(name, parent); +endfunction + +task tl_host_driver::get_and_drive(); + // Wait for initial reset to pass. + wait(cfg.vif.rst_n === 1'b1); + @(cfg.vif.host_cb); + fork + a_channel_thread(); + d_channel_thread(); + d_ready_rsp(); + join_none +endtask + +task tl_host_driver::on_enter_reset(); + // Since we've just started a period of reset, invalidate all signals and mark ourselves as not + // ready on the D channel (both directly and through the clocking block) + invalidate_a_channel(1'b1); + cfg.vif.h2d_int.d_ready <= 1'b0; + cfg.vif.host_cb.h2d.d_ready <= 1'b0; +endtask + +function void tl_host_driver::on_leave_reset(); + // We should have flushed all sequence items immediately when we were in reset. To check this has + // worked correctly, the following things should be true when we leave reset: + // + // - The pending_a_req queue should be empty (d_channel_thread should have sent responses and + // flushed the requests). + // + // - The sequencer shouldn't have any items available through seq_item_port. If an item had been + // available, we should have taken it immediately in get_and_drive. + `DV_CHECK_EQ(pending_a_req.size(), 0) + `DV_CHECK_EQ(seq_item_port.has_do_available(), 0) +endfunction + +task tl_host_driver::wait_clk_or_rst(); + `DV_SPINWAIT_EXIT(@(cfg.vif.host_cb);, wait(cfg.in_reset);) +endtask + +task tl_host_driver::a_channel_thread(); + wait_clk_or_rst(); + + forever begin + // At the start of the loop, either the interface is in reset or we are either aligned with a + // clock edge. Look to see whether there is a request ready to be sent. + seq_item_port.try_next_item(req); + + // If there was not a request ready, use get_next_item(). Since that task blocks, we then have + // to resynchronise with the clock edge (or see a reset) before starting to drive the item. + if (req == null) begin + seq_item_port.get_next_item(req); + wait_clk_or_rst(); + end + + // At this point, we have a request to send and either the interface is in reset or we are + // aligned with a clock edge. Send that request. + send_a_channel_request(req); + end +endtask + +task tl_host_driver::send_a_channel_request(tl_seq_item req); + int unsigned a_valid_delay, a_valid_len; + bit req_done = 1'b0, req_abort = 1'b0; + + // Seq may override the a_source or all valid sources are used but still send req, in which case + // it is possible that it might not have factored + // This wait is only needed in xbar test as xbar can use all valid sources and xbar_stress runs + // all seq in parallel, which needs driver to stall when the source is currently being used + // in the a_source values from pending requests that have not yet completed. If that is true, we + // need to insert additional delays to ensure we do not end up sending the new request whose + // a_source matches one of the pending requests. + `DV_SPINWAIT_EXIT(while (is_source_in_pending_req(req.a_source)) @(cfg.vif.host_cb);, + wait(cfg.in_reset);) + + while (!req_done && !req_abort && !cfg.in_reset) begin + if (cfg.use_seq_item_a_valid_delay) begin + a_valid_delay = req.a_valid_delay; + end else begin + a_valid_delay = $urandom_range(cfg.a_valid_delay_min, cfg.a_valid_delay_max); + end + + if (req.req_abort_after_a_valid_len || cfg.allow_a_valid_drop_wo_a_ready) begin + if (cfg.use_seq_item_a_valid_len) begin + a_valid_len = req.a_valid_len; + end else begin + a_valid_len = $urandom_range(cfg.a_valid_len_min, cfg.a_valid_len_max); + end + end + + fork : isolation_fork begin + fork + begin + wait(cfg.in_reset); + req_abort = 1; + end + send_a_request_body(req, a_valid_delay, a_valid_len, req_done, req_abort); + join_any + disable fork; + end join + end + seq_item_port.item_done(); + if (req_abort || cfg.in_reset) begin + req.req_completed = 0; + // Just wire the d_source back to a_source to avoid errors in upstream logic. + req.d_source = req.a_source; + seq_item_port.put_response(req); + end else begin + req.req_completed = 1; + end + `uvm_info(get_full_name(), $sformatf("Req %0s: %0s", req_abort ? "aborted" : "sent", + req.convert2string()), UVM_HIGH) +endtask + +task tl_host_driver::send_a_request_body(tl_seq_item req, + int unsigned a_valid_delay, + int unsigned a_valid_len, + output bit req_done, + output bit req_abort); + int unsigned a_valid_cnt = 0; + req_done = 1'b0; + req_abort = 1'b0; + + // If there is a delay before sending the item, wait that number of cycles + repeat (a_valid_delay) @(cfg.vif.host_cb); + + // Set signals on the A channel and add the request to pending_a_req, then wait for one clock + // edge, which causes the signals to actually be presented as signals on the interface. + pending_a_req.push_back(req); + cfg.vif.host_cb.h2d.a_address <= req.a_addr; + cfg.vif.host_cb.h2d.a_opcode <= tl_a_op_e'(req.a_opcode); + cfg.vif.host_cb.h2d.a_size <= req.a_size; + cfg.vif.host_cb.h2d.a_param <= req.a_param; + cfg.vif.host_cb.h2d.a_data <= req.a_data; + cfg.vif.host_cb.h2d.a_mask <= req.a_mask; + cfg.vif.host_cb.h2d.a_user <= req.a_user; + cfg.vif.host_cb.h2d.a_source <= req.a_source; + cfg.vif.host_cb.h2d.a_valid <= 1'b1; + + forever begin + @(cfg.vif.host_cb); + a_valid_cnt++; + if (cfg.vif.host_cb.d2h.a_ready) begin + req_done = 1; + break; + end else if ((req.req_abort_after_a_valid_len || cfg.allow_a_valid_drop_wo_a_ready) && + a_valid_cnt >= a_valid_len) begin + if (req.req_abort_after_a_valid_len) req_abort = 1; + // remove unaccepted item + void'(pending_a_req.pop_back()); + break; + end + end + + // Finally, clear up the A channel signals (because the transaction has either happened or been + // aborted). The cleared signals will be visible on the interface on the next clock edge. + invalidate_a_channel(1'b0); +endtask + +task tl_host_driver::d_ready_rsp(); + int unsigned d_ready_delay; + tl_seq_item rsp; + + forever begin + bit req_found; + d_ready_delay = $urandom_range(cfg.d_ready_delay_min, cfg.d_ready_delay_max); + // if a_valid high then d_ready must be high, exit the delay when a_valid is set + repeat (d_ready_delay) begin + if (!cfg.host_can_stall_rsp_when_a_valid_high && cfg.vif.h2d.a_valid) break; + @(cfg.vif.host_cb); + end + + cfg.vif.host_cb.h2d.d_ready <= 1'b1; + @(cfg.vif.host_cb); + cfg.vif.host_cb.h2d.d_ready <= 1'b0; + end +endtask + +task tl_host_driver::d_channel_thread(); + int unsigned d_ready_delay; + tl_seq_item rsp; + + forever begin + if ((cfg.vif.host_cb.d2h.d_valid && cfg.vif.h2d.d_ready && !cfg.in_reset) || + ((pending_a_req.size() != 0) & cfg.in_reset)) begin + // Use the source ID to find the matching request + foreach (pending_a_req[i]) begin + if ((pending_a_req[i].a_source == cfg.vif.host_cb.d2h.d_source) | cfg.in_reset) begin + rsp = pending_a_req[i]; + rsp.d_opcode = cfg.vif.host_cb.d2h.d_opcode; + rsp.d_data = cfg.vif.host_cb.d2h.d_data; + rsp.d_param = cfg.vif.host_cb.d2h.d_param; + rsp.d_sink = cfg.vif.host_cb.d2h.d_sink; + rsp.d_size = cfg.vif.host_cb.d2h.d_size; + rsp.d_user = cfg.vif.host_cb.d2h.d_user; + // set d_error = 0 and rsp_completed = 0 when reset occurs + rsp.d_error = cfg.in_reset ? 0 : cfg.vif.host_cb.d2h.d_error; + // make sure every req has a rsp with same source even during reset + if (cfg.in_reset) rsp.d_source = rsp.a_source; + else rsp.d_source = cfg.vif.host_cb.d2h.d_source; + seq_item_port.put_response(rsp); + pending_a_req.delete(i); + `uvm_info(get_full_name(), $sformatf("Got response %0s, pending req:%0d", + rsp.convert2string(), pending_a_req.size()), UVM_HIGH) + rsp.rsp_completed = !cfg.in_reset; + break; + end + end + + // If there was a matching request, we responded to it above. If not, the device seems to + // have sent a response without a request (and we won't have done anything yet). + // + // If we're in reset, we might have forgotten the request (and can ignore the response). If + // not, we wouldn't normally expect this to happen. This is a property that is checked in + // the tlul_assert module, which should be bound in. But it *might* happen if we're doing + // fault injection and disabling assertions in that module. + // + // Ignore the response either way: we're a driver and there is definitely no sequence that + // is waiting for the response here. If there's a bug in the design and we're generating + // spurious responses, we expect something to fail in tlul_assert. + end else if (cfg.in_reset) begin + wait(!cfg.in_reset); + end + wait_clk_or_rst(); + end +endtask + +function bit tl_host_driver::is_source_in_pending_req(bit [SourceWidth-1:0] source); + foreach (pending_a_req[i]) begin + if (pending_a_req[i].a_source == source) return 1; + end + return 0; +endfunction + +task tl_host_driver::invalidate_a_channel(bit direct); + // To invalidate the A channel, we will drive a_valid to zero and drive all the other A channel + // signals to either 'x or to a random value. Since there's just one signal on the D channel, the + // easiest way to do this is to drive all the signals, but make sure to set the d_ready signal to + // the value it had before. + // + // If either current d_ready value is not known, consider it to be 0. + bit cb_d_ready = cfg.vif.mon_cb.h2d.d_ready; + bit raw_d_ready = cfg.vif.mon_cb.h2d.d_ready; + + if (cfg.invalidate_a_x) begin + cfg.vif.host_cb.h2d <= tl_h2d_t'('x); + cfg.vif.host_cb.h2d.a_valid <= 1'b0; + cfg.vif.host_cb.h2d.d_ready <= cb_d_ready; + + if (direct) begin + cfg.vif.h2d_int <= tl_h2d_t'('x); + cfg.vif.h2d_int.a_valid <= 1'b0; + cfg.vif.h2d_int.d_ready <= raw_d_ready; + end + end else begin + tlul_pkg::tl_h2d_t h2d; + if (!std::randomize(h2d) with { h2d.a_valid == 1'b0; h2d.d_ready == cb_d_ready; }) begin + `uvm_fatal(get_full_name(), "Failed to randomize h2d.") + end + + cfg.vif.host_cb.h2d <= h2d; + if (direct) begin + h2d.d_ready = raw_d_ready; + cfg.vif.h2d_int <= h2d; + end + end +endtask diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_if.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_if.sv new file mode 100644 index 0000000..c202036 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_if.sv @@ -0,0 +1,45 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +// --------------------------------------------- +// TileLink interface +// --------------------------------------------- +interface tl_if(input clk, input rst_n); + + wire tlul_pkg::tl_h2d_t h2d; // req + wire tlul_pkg::tl_d2h_t d2h; // rsp + + tlul_pkg::tl_h2d_t h2d_int; // req (internal) + tlul_pkg::tl_d2h_t d2h_int; // rsp (internal) + + dv_utils_pkg::if_mode_e if_mode; // interface mode - Host or Device + + modport dut_host_mp(output h2d_int, input d2h_int); + modport dut_device_mp(input h2d_int, output d2h_int); + + clocking host_cb @(posedge clk); + input rst_n; + output h2d = h2d_int; + input d2h; + endclocking + modport host_mp(clocking host_cb); + + clocking device_cb @(posedge clk); + input rst_n; + input h2d; + output d2h = d2h_int; + endclocking + modport device_mp(clocking device_cb); + + clocking mon_cb @(posedge clk); + input rst_n; + input h2d; + input d2h; + endclocking + modport mon_mp(clocking mon_cb); + + assign h2d = (if_mode == dv_utils_pkg::Host) ? h2d_int : 'z; + assign d2h = (if_mode == dv_utils_pkg::Device) ? d2h_int : 'z; + +endinterface : tl_if diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_monitor.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_monitor.sv new file mode 100644 index 0000000..a776f82 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_monitor.sv @@ -0,0 +1,293 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// + +// --------------------------------------------- +// TileLink interface monitor +// --------------------------------------------- +class tl_monitor extends dv_base_monitor#( + .ITEM_T (tl_seq_item), + .CFG_T (tl_agent_cfg), + .COV_T (tl_agent_cov) + ); + + tl_seq_item pending_a_req[bit [SourceWidth - 1 : 0]]; + string agent_name; + + // Sequence items for transactions on the A and D channels. Sampled on the positive clock edge. + // + // If cfg.synchronise_ports (disabled by default), use these by waiting on channel_dir_port. This + // gets updated just after we push to a_chan_port or d_chan_port, telling the reader which channel + // to read. That way, the reader can guarantee a sample order if an A and D transaction both + // appear at the same time. + // + // Otherwise, wait on a_chan_port and d_chan_port with two concurrent processes. A and D + // transactions that happen at the same time will be popped from the FIFOs in an indeterminate + // order. + uvm_analysis_port #(tl_channels_e) channel_dir_port; + uvm_analysis_port #(tl_seq_item) a_chan_port; + uvm_analysis_port #(tl_seq_item) d_chan_port; + + // Sequence items for transactions on the A channel, sampled shortly after the positive clock + // edge. This is only used if cfg.device_can_rsp_on_same_cycle, in which case a sequence item for + // a transaction will appear on this port when sampled and on a_chan_port on the following clock + // edge. + uvm_analysis_port #(tl_seq_item) a_chan_same_cycle_rsp_port; + + `uvm_component_utils(tl_monitor) + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + if (cfg.synchronise_ports) begin + channel_dir_port = new("channel_dir_port", this); + end + + a_chan_port = new("a_chan_port", this); + d_chan_port = new("d_chan_port", this); + + if (cfg.device_can_rsp_on_same_cycle) begin + a_chan_same_cycle_rsp_port = new("a_chan_same_cycle_rsp_port", this); + end + endfunction : build_phase + + // Watch the reset signal and maintain cfg.in_reset + local task monitor_reset(); + // At the start of the task, we don't know whether we are in reset. Set cfg.in_reset to be true + // unless rst_n is known and asserted. + cfg.in_reset = (cfg.vif.rst_n !== 1'b1); + + // Now wait until rst_n has a known value + wait(!$isunknown(cfg.vif.rst_n)); + + forever begin + // We maintain the invariant that cfg.vif.rst_n has a known value at the start of each loop + // iteration, which ensures that we can safely convert it to a bit in cfg.in_reset. Note that + // the wait statement below will only complete when cfg.vif.rst_n has a known value. + cfg.in_reset = !cfg.vif.rst_n; + wait(cfg.vif.rst_n != !cfg.in_reset); + end + endtask + + virtual task run_phase(uvm_phase phase); + super.run_phase(phase); + fork + monitor_reset(); + ad_channels_thread(); + join + endtask + + local task ad_channels_thread(); + forever begin + wait(!cfg.in_reset); + + // As we come out of reset, clear the pending_a_req and cfg.a_source_pend_q associative + // arrays. + pending_a_req.delete(); + cfg.a_source_pend_q.delete(); + + // Watch the interface for A and D channel requests, but stop immediately if we see a reset. + // Note that ad_channels_thread is safe to kill at any time. + fork begin : isolation_fork + fork + ad_channels_thread_(); + wait(cfg.in_reset); + join_any + disable fork; + end join + + // We have just entered reset. If coverage is enabled, take a note of whether there was a + // pending request as we did so. + if (cfg.en_cov) cov.m_pending_req_on_rst_cg.sample(pending_a_req.size() != 0); + end + endtask + + // Check the A and D channels for transactions. When a transaction is seen, push it to a_chan_port + // or d_chan_port, respectively. If cfg.synchronise_ports, also push the channel to + // channel_dir_port. If transactions are seen for both channels on a clock edge, push D then A. + // + // If the device isn't expected to respond combinatorially (cfg.device_can_rsp_on_same_cycle = 0), + // then both channels are sampled on the posedge of the clock. If the device *can* respond + // combinatorially, we delay sampling on the A side by a short time. The idea is that the A + // transaction will be asserted just after a clock edge and then D will be asserted some time + // afterwards. Sampling A in the middle of the cycle and then D at the following clock ensures + // that we see A before D (the order in which the events happened). + local task ad_channels_thread_(); + + // The most recently seen request on the A channel. Set to something non-null by successful + // calls to check_a_channel. Cleared back to null when the item is written to a_chan_port. + tl_seq_item a_chan_req_item; + + forever begin + @(cfg.vif.mon_cb); + // This is just after the clock edge, so time to sample D and A channels. + + // Handle the D side. + check_d_channel(); + + // Handle the A side. If cfg.device_can_rsp_on_same_cycle then we've actually done the + // sampling already. Otherwise, we should check now. + if (!cfg.device_can_rsp_on_same_cycle) begin + a_chan_req_item = check_a_channel(.immediate(1'b0)); + end + if (a_chan_req_item != null) begin + a_chan_port.write(a_chan_req_item); + if (cfg.synchronise_ports) channel_dir_port.write(AddrChannel); + a_chan_req_item = null; + end + + // We're done with this clock edge. If cfg.device_can_rsp_on_same_cycle, we now wait a short + // time afterwards and sample a little after the clockedge. + if (cfg.device_can_rsp_on_same_cycle) begin + `DV_SPINWAIT_EXIT( + #(cfg.time_a_valid_avail_after_sample_edge);, + @(cfg.vif.mon_cb) `uvm_fatal(`gfn, $sformatf( + "time_a_valid_avail_after_sample_edge (%0t) is over one cycle", + cfg.time_a_valid_avail_after_sample_edge))) + + // It's a short time afterwards. Do the sampling! + a_chan_req_item = check_a_channel(.immediate(1'b1)); + if (a_chan_req_item != null) begin + a_chan_same_cycle_rsp_port.write(a_chan_req_item); + end + end + end + endtask + + // Check the A channel for a transaction + // + // If immediate is true, this is running just after a posedge of the clock, to allow us to capture + // same-cycle responses. In this case, it samples the immediate values of the signals. + // + // Otherwise, this is running on the posedge. It samples signals through the mon_cb clocking + // block. + // + // In either case, if a transaction is found then it returns a sequence item. Otherwise, it + // returns null. + function tl_seq_item check_a_channel(bit immediate); + logic a_valid = immediate ? cfg.vif.h2d.a_valid : cfg.vif.mon_cb.h2d.a_valid; + logic a_ready = immediate ? cfg.vif.d2h.a_ready : cfg.vif.mon_cb.d2h.a_ready; + + if (a_valid && a_ready) begin + tl_seq_item req = tl_seq_item::type_id::create("req"); + tl_seq_item cloned_req; + tlul_pkg::tl_h2d_t h2d = immediate ? cfg.vif.h2d : cfg.vif.mon_cb.h2d; + + // Create a sequence item. Note: this is a field in the class, which ad_channels_thread() uses + // to pass the transaction to the relevant analysis port/ports. + req.a_addr = h2d.a_address; + req.a_opcode = h2d.a_opcode; + req.a_size = h2d.a_size; + req.a_param = h2d.a_param; + req.a_data = h2d.a_data; + req.a_mask = h2d.a_mask; + req.a_source = h2d.a_source; + req.a_user = h2d.a_user; + `uvm_info(`gfn, $sformatf("[%0s][a_chan] : %0s", agent_name, req.convert2string()), UVM_HIGH) + + if (cfg.en_cov) sample_outstanding_cov(req); + + `downcast(cloned_req, req.clone()); + `DV_CHECK_EQ_FATAL(cloned_req.a_source >> cfg.valid_a_source_width, 0) + `DV_CHECK_EQ_FATAL(pending_a_req.exists(cloned_req.a_source), 0) + pending_a_req[cloned_req.a_source] = cloned_req; + + if (cfg.max_outstanding_req > 0 && cfg.vif.rst_n === 1) begin + if (pending_a_req.size() > cfg.max_outstanding_req) begin + `uvm_error(`gfn, + $sformatf("Number of pending a_req exceeds limit %0d", pending_a_req.size())) + end + if (cfg.en_cov) cov.m_max_outstanding_cg.sample(pending_a_req.size()); + end + return req; + end + + return null; + endfunction + + // Checks the D channel for a transaction + // + // If a transaction is found, writes it to d_chan_port and clears the corresponding pending + // request. + function void check_d_channel(); + if (cfg.vif.mon_cb.d2h.d_valid && cfg.vif.mon_cb.h2d.d_ready) begin + tl_seq_item rsp; + + // We expect a matching request to exist. If it doesn't, this is a "spurious response" that + // the dut has generated itself. We don't expect that to happen (a property that is checked in + // the tlul_assert module, which should be bound in), but it *might* happen if we're doing + // fault injection and disabling assertions in that module. In that case, print a debug + // message and ignore the response in the monitor: we would normally expect the error to be + // caught in tlul_assert. + if (!pending_a_req.exists(cfg.vif.mon_cb.d2h.d_source)) begin + `uvm_info(`gfn, + $sformatf("Ignoring TL response with no matching request (d_source 0x%0x)", + cfg.vif.mon_cb.d2h.d_source), + UVM_HIGH) + return; + end + + rsp = pending_a_req[cfg.vif.mon_cb.d2h.d_source]; + pending_a_req.delete(cfg.vif.mon_cb.d2h.d_source); + + rsp.d_opcode = cfg.vif.mon_cb.d2h.d_opcode; + rsp.d_data = cfg.vif.mon_cb.d2h.d_data; + rsp.d_source = cfg.vif.mon_cb.d2h.d_source; + rsp.d_param = cfg.vif.mon_cb.d2h.d_param; + rsp.d_error = cfg.vif.mon_cb.d2h.d_error; + rsp.d_sink = cfg.vif.mon_cb.d2h.d_sink; + rsp.d_size = cfg.vif.mon_cb.d2h.d_size; + rsp.d_user = cfg.vif.mon_cb.d2h.d_user; + + `uvm_info(`gfn, $sformatf("[%0s][d_chan] : %0s", agent_name, rsp.convert2string()), UVM_HIGH) + + d_chan_port.write(rsp); + if (cfg.synchronise_ports) channel_dir_port.write(DataChannel); + + if (cfg.en_cov) cov.sample(rsp); + end + endfunction + + // update ok_to_end to prevent sim finish when there is any pending item + virtual task monitor_ready_to_end(); + forever begin + ok_to_end = (pending_a_req.size() == 0); + if (ok_to_end) wait(pending_a_req.size() > 0); + else wait(pending_a_req.size() == 0); + end + endtask + + virtual function void report_phase(uvm_phase phase); + super.report_phase(phase); + if (pending_a_req.size() > 0) begin + `uvm_error(get_full_name(), $sformatf( + "%0d items left at the end of sim", pending_a_req.size())) + foreach (pending_a_req[i]) begin + `uvm_info(get_full_name(), $sformatf("pending_a_req[%0d] = %0s", + i, pending_a_req[i].convert2string()), UVM_LOW) + end + end + endfunction : report_phase + + // sample outstanding related coverage + virtual function void sample_outstanding_cov(tl_seq_item item); + bit is_outstanding_item_w_same_addr; + + // check if same address has been used in more than 1 outstanding_item + foreach (pending_a_req[i]) begin + if (pending_a_req[i].a_addr == item.a_addr) begin + is_outstanding_item_w_same_addr = 1; + break; + end + end + + // sample a same address used in more than 1 outstanding items, if it's null, design doesn't + // support outstanding items use the same address + if (cov.m_outstanding_item_w_same_addr_cov_obj != null) begin + cov.m_outstanding_item_w_same_addr_cov_obj.sample(is_outstanding_item_w_same_addr); + end + endfunction : sample_outstanding_cov + +endclass : tl_monitor diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_reg_adapter.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_reg_adapter.sv new file mode 100644 index 0000000..ec85e72 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_reg_adapter.sv @@ -0,0 +1,185 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +typedef class tl_host_base_seq; + +// A register adapter parameterized with the default tl_seq_item type. The idea is to extend +// tl_seq_item for further constraints or customizations if required and create the tl_reg_adapter +// instance with the overridden type. + +class tl_reg_adapter #(type ITEM_T = tl_seq_item) extends uvm_reg_adapter; + `uvm_object_param_utils(tl_reg_adapter#(ITEM_T)) + + // Ensure that when an instance of this adapter is created, the cfg handle below is initialized to + // the `tl_agent_cfg` instance associated with this adapter instance. + tl_agent_cfg cfg; + + // Information about how to represent RACL role and uid values in the TL item. This has to be + // configured from the test environment (which can see the dut) because it depends on the + // top-level that is being modelled. + // + // The default is not to support either (so role and uid are both signalled as zero) + local int unsigned role_lsb, role_nbits; + local int unsigned uid_lsb, uid_nbits; + + extern function new(string name = ""); + + // Standard uvm_reg_adapter functions + extern function uvm_sequence_item reg2bus(const ref uvm_reg_bus_op rw); + extern function void bus2reg(uvm_sequence_item bus_item, ref uvm_reg_bus_op rw); + + // Configure and randomise a bus request for a register read or write + extern local function void fill_bus_rd(const ref uvm_reg_bus_op rw, ref ITEM_T bus_req); + extern local function void fill_bus_wr(const ref uvm_reg_bus_op rw, ref ITEM_T bus_req); + + // Return the highest bit index in the target of a uvm_reg_item. This will be the highest bit in a + // field of a register, or will be the bus width if item is a memory. + extern local function int unsigned get_tgt_msb(uvm_reg_item item); + + // Check that the requested bit indices for something will fit in the A channel's user field. + extern local function bit check_user_bit_idx(string field_name, + int unsigned lsb, + int unsigned nbits); + + // Configure how to represent RACL roles and uids + extern function void configure_racl_bits(int unsigned role_lsb, + int unsigned role_nbits, + int unsigned uid_lsb, + int unsigned uid_nbits); +endclass + +function tl_reg_adapter::new(string name = ""); + super.new(name); + // Force the uvm_reg_map to use this sequence to sync with the driver instead. + parent_sequence = tl_host_base_seq#(ITEM_T)::type_id::create("parent_sequence"); + supports_byte_enable = 1; + provides_responses = 1; +endfunction + +function uvm_sequence_item tl_reg_adapter::reg2bus(const ref uvm_reg_bus_op rw); + ITEM_T bus_req = ITEM_T::type_id::create("bus_req"); + + if (rw.kind == UVM_READ) begin + fill_bus_rd (rw, bus_req); + end else begin + fill_bus_wr (rw, bus_req); + end + + if (cfg.csr_access_abort_pct_in_adapter > $urandom_range(0, 100)) begin + bus_req.req_abort_after_a_valid_len = 1; + `uvm_info(`gfn, $sformatf("tl reg req item is allowed to be aborted"), UVM_MEDIUM) + end + `uvm_info(`gfn, {"tl_reg_adapter::reg2bus: ", bus_req.convert2string()}, UVM_HIGH) + return bus_req; +endfunction + +function void tl_reg_adapter::bus2reg(uvm_sequence_item bus_item, ref uvm_reg_bus_op rw); + ITEM_T bus_rsp; + `downcast(bus_rsp, bus_item) + rw.kind = bus_rsp.is_write() ? UVM_WRITE : UVM_READ; + rw.addr = bus_rsp.a_addr; + rw.data = (rw.kind == UVM_WRITE) ? bus_rsp.a_data : bus_rsp.d_data; + rw.byte_en = bus_rsp.a_mask; + `DV_CHECK_EQ(bus_rsp.d_source, bus_rsp.a_source) + // indicate if the item is completed successfully for upper level to update predict value + rw.status = !bus_rsp.req_completed ? UVM_NOT_OK : UVM_IS_OK; + `uvm_info(`gfn, {"tl_reg_adapter::bus2reg: ", bus_rsp.convert2string()}, UVM_HIGH) +endfunction + +function void tl_reg_adapter::fill_bus_rd(const ref uvm_reg_bus_op rw, ref ITEM_T bus_req); + // The tl_seq_item::mask_in_active_lanes_c constraint ensures that a_mask is only asserted in + // active byte lanes. For 50% of CSR full reads (with element_kind == UVM_REG and all bits set in + // byte_en), we ask mask to be asserted for a strict subset of the lanes. + bit is_csr_full_read = (rw.byte_en == '1 && get_item().element_kind == UVM_REG); + + if (!bus_req.randomize() with { + bus_req.a_opcode == tlul_pkg::Get; + bus_req.a_addr[AddrWidth-1:2] == local::rw.addr[AddrWidth-1:2]; + if (local::is_csr_full_read) { + $countones(bus_req.a_mask) dist {MaskWidth :/ 1, [0:MaskWidth-1] :/ 1}; + } else { + bus_req.a_mask == rw.byte_en[MaskWidth-1:0]; + } + }) begin + `uvm_fatal(get_name(), "Failed to randomize bus request for read") + end +endfunction + +function void tl_reg_adapter::fill_bus_wr(const ref uvm_reg_bus_op rw, ref ITEM_T bus_req); + // The TL bus may support byte-enable values, which might be given by allowing some bits of a_mask + // to be zero. Since CSRs in OpenTitan don't support partial accesses, the reg adapter wants to + // choose an a_mask which is true for every byte that exists in the target. + // + // The tl_seq_item::mask_contiguous_c constraint means that we can require that the bytes + // containing bits 0..msb are enabled by just requiring the ends to be enabled. These are the + // bytes with indices 0 and msb / 8. + int unsigned msb = supports_byte_enable ? get_tgt_msb(get_item()) : (DataWidth - 1); + + if (!bus_req.randomize() with { + bus_req.a_opcode inside {PutFullData, PutPartialData}; + bus_req.a_addr == AddrWidth'(rw.addr); + bus_req.a_data == DataWidth'(rw.data); + bus_req.a_mask[0] == 1; + bus_req.a_mask[msb/8] == 1; + }) begin + `uvm_fatal(get_name(), "Failed to randomize bus request for write") + end +endfunction + +function int unsigned tl_reg_adapter::get_tgt_msb(uvm_reg_item item); + case (item.element_kind) + UVM_REG: begin + // We only support registers that are instances of dv_base_reg. These registers have an msb + // position pre-calculated, which gives the highest bit that is contained in any field. + dv_base_reg csr; + if (!$cast(csr, item.element)) begin + `uvm_fatal(get_name(), "Cannot cast UVM_REG item to a dv_base_reg.") + end + return csr.get_msb_pos(); + end + + UVM_FIELD: begin + uvm_reg_field field; + if (!$cast(field, item.element)) begin + `uvm_fatal(get_name(), "Cannot cast UVM_FIELD item to a uvm_reg_field.") + end + return field.get_lsb_pos() + field.get_n_bits() - 1; + end + + UVM_MEM: begin + // Set msb to be the top bit of a_data, forcing all of the a_mask bits to be set. + return DataWidth - 1; + end + + default: + `uvm_fatal(get_name(), $sformatf("Unknown element_kind: %0p", item.element_kind)) + endcase +endfunction + +function bit tl_reg_adapter::check_user_bit_idx(string field_name, + int unsigned lsb, + int unsigned nbits); + if (nbits > 0 && lsb + nbits >= AUserWidth) begin + `uvm_error(this.get_name(), + $sformatf("Cannot represent RACL %s with lsb %0d and %0d bits: AUserWidth is %0d", + field_name, lsb, nbits, AUserWidth)) + return 0; + end + return 1; +endfunction + +function void tl_reg_adapter::configure_racl_bits(int unsigned role_lsb, + int unsigned role_nbits, + int unsigned uid_lsb, + int unsigned uid_nbits); + // Check that both sides can fit in the USER field for the A channel, zeroing out their width if + // not. If either doesn't fit, its call to check_user_bit_idx will have reported a uvm_error. + if (!check_user_bit_idx("role", role_lsb, role_nbits)) role_nbits = 0; + if (!check_user_bit_idx("uid", uid_lsb, uid_nbits)) uid_nbits = 0; + + this.role_lsb = role_lsb; + this.role_nbits = role_nbits; + this.uid_lsb = uid_lsb; + this.uid_nbits = uid_nbits; +endfunction diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_seq_item.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_seq_item.sv new file mode 100644 index 0000000..6c8eb50 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_seq_item.sv @@ -0,0 +1,472 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// --------------------------------------------- +// TileLink sequence item +// --------------------------------------------- + +// An expression that is true if a_opcode is a valid opcode. Using a macro instead of a function +// means that this can be used by the constraint solver. +`define A_OPCODE_IS_VALID(a_opcode) (a_opcode inside {Get, PutFullData, PutPartialData}) + +// An expression that is true if a_mask is true for every active byte lane. (This is required by the +// PutFullData operation). +// +// Note that the expression actually works by checking there are the right *number* of bits set in +// the mask. The alignment requirement is handled separately. +`define MASK_IS_FULL(a_mask, a_size) ($countones(a_mask) == (1 << a_size)) + +// The mask must always be LOW for all inactive byte lanes (see TL specification 1.8.1, p26) +// +// To evaluate this, notice that (1 << a_size) gives the number of active byte lanes. Exponentiating +// again gives ((1 << (1 << a_size)) - 1), which is a pattern of bits that are true for the active +// byte lanes, starting at index zero. +// +// Shifting this left by a_addr[SizeWidth-1:0] gives the pattern of bits for the active byte lanes, +// starting at the correct index. +// +// Invert this and then AND with a_mask. Any bits high in the result are inactive byte lanes that +// are HIGH in the mask. +`define MASK_LOW_IN_INACTIVE_LANES(a_mask, a_addr, a_size) \ + ((a_mask & ~(((1 << (1 << a_size)) - 1) << a_addr[SizeWidth-1:0])) == 0) + +// Addresses should be naturally aligned. The operation addresses (1 << a_size) bytes, so the +// address should be divisible by that. Equivalently, the bottom a_size bits of a_addr should be +// zero. +`define ADDR_ALIGNED_TO_SIZE(a_addr, a_size) ((a_addr & ((1 << a_size) - 1)) == 0) + +// The maximum allowed a_size is 2 (corresponding to a 4-byte / 32-bit operation) +`define BELOW_MAX_A_SIZE(a_size) (a_size <= 2) + +class tl_seq_item extends uvm_sequence_item; + + // This block of variables is the fields that are sent on the A side of the transaction + rand bit [AddrWidth - 1 : 0] a_addr; + rand bit [DataWidth - 1 : 0] a_data; + rand bit [MaskWidth - 1 : 0] a_mask; + rand bit [SizeWidth - 1 : 0] a_size; + rand bit [2:0] a_param; + rand bit [SourceWidth - 1 : 0] a_source; + rand bit [OpcodeWidth - 1 : 0] a_opcode; + rand bit [AUserWidth - 1 : 0] a_user; + + // This block of variables is the fields that are sent on the D side of the transaction + rand bit [2:0] d_param; + rand bit [DataWidth - 1 : 0] d_data; + rand bit [SourceWidth - 1 : 0] d_source; + rand bit [SizeWidth - 1 : 0] d_size; + rand bit [OpcodeWidth - 1 : 0] d_opcode; + rand bit d_error; + rand bit [DUserWidth - 1 : 0] d_user; + rand bit d_sink; + + // When this item is sent by a host-mode driver, this gives the number of cycles that the driver + // will wait before asserting a_valid (the VALID signal for a message on the A channel). + rand int unsigned a_valid_delay; + + // A TileLink message is sent by asserting the VALID signal and waiting for the receiver to assert + // READY. On the A channel, the signals are a_valid and a_ready. When the driver is configured to + // abort early (either by req_abort_after_a_valid_len or cfg.allow_a_valid_drop_wo_a_ready), this + // variable gives the number of cycles that it will assert a_valid before (if a_ready has been low + // throughout) aborting the message by dropping a_valid again. + rand int unsigned a_valid_len; + + // When this item is sent by a device-mode driver, this gives the number of cycles that the driver + // will wait before asserting d_valid (the VALID signal for a message on the D channel). + rand int unsigned d_valid_delay; + + // A TileLink message is sent by asserting the VALID signal and waiting for the receiver to assert + // READY. On the D channel, the signals are d_valid and d_ready. When the driver is configured to + // abort early (either by rsp_abort_after_d_valid_len or cfg.allow_d_valid_drop_wo_d_ready), this + // variable gives the number of cycles that it will assert d_valid before (if d_ready has been low + // throughout) aborting the message by dropping d_valid again. + rand int unsigned d_valid_len; + + // If this flag is true, a host-mode driver will abort sending a message on the A channel after + // waiting a_valid_len cycles for a_ready to be asserted by the other end. + bit req_abort_after_a_valid_len; + + // If this flag is true, a host-mode driver will abort sending a message on the D channel after + // waiting d_valid_len cycles for a_ready to be asserted by the other end. + bit rsp_abort_after_d_valid_len; + + // This signal is filled in by a host-mode driver after it stops sending the item on the A + // channel. It is set to true if the message was accepted and to false if the request was aborted + // (either because of timeout or because a reset was asserted). + bit req_completed; + + // This signal is filled in by a device-mode driver after it stops sending the item on the D + // channel. It is set to true if the message was accepted and to false if the request was aborted + // (either because of timeout or because a reset was asserted). + bit rsp_completed; + + // The a_param and d_param message fields are reserved in the spec for future use. Force them to + // be zero in items that we generate. + extern constraint param_c; + + // Constrain d_error to be false (so the message on the D channel does not report an error). This + // is a soft constraint, and is overridden in e.g. tl_device_seq, which can inject a nonzero + // number of error responses. + extern constraint no_d_error_c; + + // A bound on the time to wait before dropping a_valid if there is no a_ready response. + extern constraint a_valid_len_c; + + // A bound on the time to wait before dropping d_valid if there is no d_ready response. + extern constraint d_valid_len_c; + + // A bound on the time to wait before dropping asserting a_valid / d_valid on the A / D channels, + // respectively. + extern constraint valid_delay_c; + + // Constrain d_opcode to be a valid one for the D channel. + extern constraint d_opcode_c; + + // Constrain a_opcode to be a valid one for the A channel. + extern constraint a_opcode_c; + + // Constrain the mask to be contiguous. Technically, this avoids generating some PutPartialData + // messages that we should probably allow (e.g. a mask of 4'b1001). As a result, that behaviour + // won't be tested by randomised testing. + extern constraint mask_contiguous_c; + + // Require that the mask is high for all active byte lanes for a PutFullData message. + extern constraint mask_w_PutFullData_c; + + // Require that the mask is only high in active lanes. + extern constraint mask_in_active_lanes_c; + + // Require that a_addr is naturally aligned for an operation touching (1 << a_size) bytes. + extern constraint addr_size_align_c; + + // Require that a_size is at most 2 (this constrains messages to be at most 32 bits, so disallows + // multi-beat messages). + extern constraint max_size_c; + + `uvm_object_utils_begin(tl_seq_item) + `uvm_field_int (a_addr, UVM_DEFAULT) + `uvm_field_int (a_data, UVM_DEFAULT) + `uvm_field_int (a_mask, UVM_DEFAULT) + `uvm_field_int (a_size, UVM_DEFAULT) + `uvm_field_int (a_param, UVM_DEFAULT) + `uvm_field_int (a_source, UVM_DEFAULT) + `uvm_field_int (a_opcode, UVM_DEFAULT) + `uvm_field_int (a_user, UVM_DEFAULT) + `uvm_field_int (d_param, UVM_DEFAULT) + `uvm_field_int (d_source, UVM_DEFAULT) + `uvm_field_int (d_data, UVM_DEFAULT) + `uvm_field_int (d_size, UVM_DEFAULT) + `uvm_field_int (d_opcode, UVM_DEFAULT) + `uvm_field_int (d_error, UVM_DEFAULT) + `uvm_field_int (d_sink, UVM_DEFAULT) + `uvm_field_int (d_user, UVM_DEFAULT) + `uvm_field_int (a_valid_delay, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (d_valid_delay, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (a_valid_len, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (d_valid_len, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (req_abort_after_a_valid_len, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (rsp_abort_after_d_valid_len, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (req_completed, UVM_DEFAULT | UVM_NOPACK) + `uvm_field_int (rsp_completed, UVM_DEFAULT | UVM_NOPACK) + `uvm_object_utils_end + + extern function new (string name = ""); + extern function string convert2string(); + extern function bit do_compare(uvm_object rhs, uvm_comparer comparer); + + // Set rand_mode(0) for all fields relating to the A channel. This is used when re-randomising an + // item that has already been populated with data from that channel. + extern function void disable_a_chan_randomization(); + + // The expected value of d_error based on the fields from the A channel item + extern function bit get_exp_d_error(); + + // Return true if a_opcode is not a valid opcode for the A channel. + extern function bit get_error_a_opcode_invalid(); + + // Return the data that is being written by this transaction on the A channel. This is the + // contents of a_data, but masked by zeroing the bytes where a_mask is false. + extern function automatic logic [DataWidth-1:0] get_written_data(); + + // Return true if the A channel for this item is a PutFullData message and the a_mask field is not + // high for all the active byte lanes. + extern function bit get_error_PutFullData_mask_size_mismatched(); + + // Return true if the A channel message for this item has an a_addr that is not naturally aligned + // for the operation size implied by a_size. + extern function bit get_error_addr_size_misaligned(); + + // Return true if the A channel message for this item has bits in a_mask that are high in lanes + // that are inactive (based on a_addr and a_size). + extern function bit get_error_mask_not_in_active_lanes(); + + // Return true if the A channel message for this item gives an a_size larger than the biggest + // allowed by OpenTitan tilelink (32 bits, so 4 bytes, so a_size of 2) + extern function bit get_error_size_over_max(); + + // Disable the constraints that apply to the A channel fields. This can be used to generate + // sequence items that will (almost certainly) cause protocol errors. + extern function void disable_a_chan_protocol_constraint(); + + // Randomise the A channel fields, ensuring that at least one constraint is disabled and the + // protocol is violated. + extern function void randomize_a_chan_with_protocol_error(); + + // Return true if this sequence item is a write (as opposed to a read). + extern function bit is_write(); + + // Return true if the values in the fields of the D channel message are appropriate as a response + // to the A channel message. + extern function bit is_ok(); + + // Compute and check the integrity of the a_channel payload. + // + // The TL agent is generic and adheres to the TLUL spec, which does not define + // how the integrity of the payload on each channel is computed / checked. That + // is up to the chip implementation. Typically, parity / ECC scheme is used, with + // the redundant bits transmitted through *_user. + // + // Returns 1 if the integrity of a_channel is maintained, 0 otherwise. This base + // class implementation vacuously returns 1. + extern virtual function bit is_a_chan_intg_ok(bit throw_error = 1'b1); + + // d_channel version of the function above + extern virtual function bit is_d_chan_intg_ok(bit en_rsp_intg_chk = 1, + bit en_data_intg_chk = 1, + bit throw_error = 1'b1); +endclass + +constraint tl_seq_item::param_c { + a_param == 0; + d_param == 0; +} + +constraint tl_seq_item::no_d_error_c { + soft d_error == 0; +} + +constraint tl_seq_item::a_valid_len_c { + a_valid_len inside {[1:10]}; +} + +constraint tl_seq_item::d_valid_len_c { + d_valid_len inside {[1:10]}; +} + +constraint tl_seq_item::valid_delay_c { + a_valid_delay inside {[0:50]}; + d_valid_delay inside {[0:50]}; +} + +constraint tl_seq_item::d_opcode_c { + d_opcode inside {AccessAckData, AccessAck}; +} + +constraint tl_seq_item::a_opcode_c { + `A_OPCODE_IS_VALID(a_opcode); +} + +constraint tl_seq_item::mask_contiguous_c { + $countones(a_mask ^ {a_mask[MaskWidth-2:0], 1'b0}) <= 2; +} + +constraint tl_seq_item::mask_w_PutFullData_c { + a_opcode == PutFullData -> `MASK_IS_FULL(a_mask, a_size); +} + +constraint tl_seq_item::mask_in_active_lanes_c { + `MASK_LOW_IN_INACTIVE_LANES(a_mask, a_addr, a_size); +} + +constraint tl_seq_item::addr_size_align_c { + `ADDR_ALIGNED_TO_SIZE(a_addr, a_size); +} + +constraint tl_seq_item::max_size_c { + `BELOW_MAX_A_SIZE(a_size); +} + +function tl_seq_item::new (string name = ""); + super.new(name); +endfunction + +function string tl_seq_item::convert2string(); + string str; + string a_opcode_name, d_opcode_name; + tl_a_op_e a_op_e; + tl_d_op_e d_op_e; + if ($cast(a_op_e, a_opcode)) a_opcode_name = a_op_e.name(); + else a_opcode_name = $sformatf("Invalid, value: %0d", a_opcode); + if ($cast(d_op_e, d_opcode)) d_opcode_name = d_op_e.name(); + else d_opcode_name = $sformatf("Invalid, value: %0d", d_opcode); + + str = {$sformatf("a_addr = 0x%0h ", a_addr), + $sformatf("a_data = 0x%0h ", a_data), + $sformatf("a_mask = 0x%0h ", a_mask), + $sformatf("a_size = 0x%0h ", a_size), + $sformatf("a_param = 0x%0h ", a_param), + $sformatf("a_source = 0x%0h ", a_source), + $sformatf("a_opcode = %0s ", a_opcode_name), + $sformatf("a_user = 0x%0h ", a_user), + $sformatf("d_data = 0x%0h ", d_data), + $sformatf("d_size = 0x%0h ", d_size), + $sformatf("d_param = 0x%0h ", d_param), + $sformatf("d_source = 0x%0h ", d_source), + $sformatf("d_opcode = %0s ", d_opcode_name), + $sformatf("d_error = %0b ", d_error), + $sformatf("d_user = %0b ", d_user), + $sformatf("d_sink = %0b ", d_sink), + $sformatf("req_abort_after_a_valid_len = %0b ", req_abort_after_a_valid_len), + $sformatf("rsp_abort_after_d_valid_len = %0b ", rsp_abort_after_d_valid_len), + $sformatf("req_completed = %0b ", req_completed), + $sformatf("rsp_completed = %0b ", rsp_completed)}; + return str; +endfunction + +function void tl_seq_item::disable_a_chan_randomization(); + a_addr.rand_mode(0); + a_data.rand_mode(0); + a_mask.rand_mode(0); + a_size.rand_mode(0); + a_param.rand_mode(0); + a_source.rand_mode(0); + a_opcode.rand_mode(0); +endfunction + +function bit tl_seq_item::get_exp_d_error(); + return get_error_a_opcode_invalid() || get_error_PutFullData_mask_size_mismatched() || + get_error_addr_size_misaligned() || + get_error_mask_not_in_active_lanes() || get_error_size_over_max(); +endfunction + +function bit tl_seq_item::get_error_a_opcode_invalid(); + return !`A_OPCODE_IS_VALID(a_opcode); +endfunction + +function automatic logic [DataWidth-1:0] tl_seq_item::get_written_data(); + logic [DataWidth-1:0] masked_data = 'x; + `DV_CHECK(is_write(), "get_written_data() may only be called on a write") + for (int i = 0; i < MaskWidth; i++) begin + if (a_mask[i] == 1'b1) begin + masked_data[8*i +: 8] = a_data[8*i +: 8]; + end + end + return masked_data; +endfunction + +function bit tl_seq_item::get_error_PutFullData_mask_size_mismatched(); + return (a_opcode == PutFullData) && !(`MASK_IS_FULL(a_mask, a_size)); +endfunction + +function bit tl_seq_item::get_error_addr_size_misaligned(); + return !(`ADDR_ALIGNED_TO_SIZE(a_addr, a_size)); +endfunction + +function bit tl_seq_item::get_error_mask_not_in_active_lanes(); + return !`MASK_LOW_IN_INACTIVE_LANES(a_mask, a_addr, a_size); +endfunction + +function bit tl_seq_item::get_error_size_over_max(); + return !`BELOW_MAX_A_SIZE(a_size); +endfunction // get_error_size_over_max + +// Note: the do_compare() method should only be coded for those properties which can be compared +// that's the reason why the following fields are not part it: +// req_abort_after_a_valid_len, rsp_abort_after_d_valid_len, req_completed, rsp_completed +function bit tl_seq_item::do_compare(uvm_object rhs, uvm_comparer comparer); + tl_seq_item rhs_; + // If the cast fails, comparison has also failed + // A check for null is not needed because that is done in the compare() function which + // calls do_compare() + if (!$cast(rhs_, rhs)) begin + return 0; + end + + return (super.do_compare(rhs, comparer) && + (a_addr == rhs_.a_addr ) && + (a_data == rhs_.a_data ) && + (a_mask == rhs_.a_mask ) && + (a_size == rhs_.a_size ) && + (a_param == rhs_.a_param ) && + (a_source == rhs_.a_source ) && + (a_opcode == rhs_.a_opcode ) && + (a_user == rhs_.a_user ) && + (d_data == rhs_.d_data ) && + (d_size == rhs_.d_size ) && + (d_param == rhs_.d_param ) && + (d_source == rhs_.d_source ) && + (d_opcode == rhs_.d_opcode ) && + (d_error == rhs_.d_error ) && + (d_user == rhs_.d_user ) && + (d_sink == rhs_.d_sink )); +endfunction + +function void tl_seq_item::disable_a_chan_protocol_constraint(); + a_opcode_c.constraint_mode(0); + mask_contiguous_c.constraint_mode(0); + mask_w_PutFullData_c.constraint_mode(0); + mask_in_active_lanes_c.constraint_mode(0); + addr_size_align_c.constraint_mode(0); + max_size_c.constraint_mode(0); +endfunction + +function void tl_seq_item::randomize_a_chan_with_protocol_error(); + bit cm_a_opcode, cm_mask_w_PutFullData; + bit cm_mask_in_active_lanes, cm_addr_size_align, cm_max_size; + + // Randomly pick some constraint mode (enabled or disabled) for the various constraints, disabling + // at least one of them. + `DV_CHECK_FATAL(std::randomize(cm_a_opcode, cm_mask_w_PutFullData, + cm_mask_in_active_lanes, cm_addr_size_align, cm_max_size) with { + !(&{cm_a_opcode, cm_mask_w_PutFullData, + cm_mask_in_active_lanes, cm_addr_size_align && cm_max_size}); + }) + + // Apply the selected modes to the constraints that might be disabled + a_opcode_c.constraint_mode(cm_a_opcode); + mask_w_PutFullData_c.constraint_mode(cm_mask_w_PutFullData); + mask_in_active_lanes_c.constraint_mode(cm_mask_in_active_lanes); + addr_size_align_c.constraint_mode(cm_addr_size_align); + max_size_c.constraint_mode(cm_max_size); + + // Now randomise this object, ensuring that at least constraint we just disabled is actually being + // violated. + `DV_CHECK_FATAL(randomize() with { + (!cm_a_opcode && !`A_OPCODE_IS_VALID(a_opcode)) || + (!cm_mask_w_PutFullData && + (a_opcode == PutFullData) && !(`MASK_IS_FULL(a_mask, a_size))) || + (!cm_mask_in_active_lanes && + !(`MASK_LOW_IN_INACTIVE_LANES(a_mask, a_addr, a_size))) || + (!cm_addr_size_align && !`ADDR_ALIGNED_TO_SIZE(a_addr, a_size)) || + (!cm_max_size && !`BELOW_MAX_A_SIZE(a_size)); + }) +endfunction + +function bit tl_seq_item::is_write(); + return (a_opcode inside {PutFullData, PutPartialData}); +endfunction + +function bit tl_seq_item::is_ok(); + // For this to be an appropriate response, the D channel has to hold something that could be a + // response to the request on the A channel. For a Get, TileLink expects an AccessAckData; for a + // write or error opcode, it expects AccessAck + tl_d_op_e exp_d_opcode = (a_opcode == Get) ? tlul_pkg::AccessAckData : tlul_pkg::AccessAck; + return (d_opcode == exp_d_opcode) && (a_source == d_source); +endfunction + +function bit tl_seq_item::is_a_chan_intg_ok(bit throw_error = 1'b1); + return 1; +endfunction + +function bit tl_seq_item::is_d_chan_intg_ok(bit en_rsp_intg_chk = 1, + bit en_data_intg_chk = 1, + bit throw_error = 1'b1); + return 1; +endfunction + +`undef BELOW_MAX_A_SIZE +`undef ADDR_ALIGNED_TO_SIZE +`undef MASK_LOW_IN_INACTIVE_LANES +`undef MASK_IS_FULL +`undef A_OPCODE_IS_VALID diff --git a/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_sequencer.sv new file mode 100644 index 0000000..7d7557e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/tl_agent/tl_sequencer.sv @@ -0,0 +1,17 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class tl_sequencer extends dv_base_sequencer#(tl_seq_item, tl_agent_cfg); + `uvm_component_utils(tl_sequencer) + + uvm_tlm_analysis_fifo#(tl_seq_item) a_chan_req_fifo; + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + a_chan_req_fifo = new("a_chan_req_fifo", this); + endfunction : build_phase + +endclass : tl_sequencer diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/README.md b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/README.md new file mode 100644 index 0000000..e39fe4a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/README.md @@ -0,0 +1,3 @@ +# UART Agent + +**TODO** diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_base_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_base_seq.sv new file mode 100644 index 0000000..7168cd8 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_base_seq.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_base_seq extends dv_base_seq #( + .REQ (uart_item), + .CFG_T (uart_agent_cfg), + .SEQUENCER_T (uart_sequencer) + ); + `uvm_object_utils(uart_base_seq) + + `uvm_object_new + + task body(); + `uvm_error(`gfn, "Need to override this when you extend from this class!") + endtask : body + +endclass : uart_base_seq diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_default_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_default_seq.sv new file mode 100644 index 0000000..d2c07d9 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_default_seq.sv @@ -0,0 +1,18 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// drive everything 0 for testing break error +class uart_default_seq extends uart_seq; + `uvm_object_utils(uart_default_seq) + + constraint parity_err_c { + parity_err == 0; + } + constraint frame_err_c { + frame_err == 0; + } + + `uvm_object_new + +endclass : uart_default_seq diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq.sv new file mode 100644 index 0000000..45502c7 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq.sv @@ -0,0 +1,37 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_seq extends uart_base_seq; + `uvm_object_utils(uart_seq) + + rand bit [7:0] data; + rand bit parity_err; + rand bit parity; + rand bit frame_err; + + constraint parity_c { + if (parity_err) { + parity != `GET_PARITY(data, p_sequencer.cfg.odd_parity); + } else { + parity == `GET_PARITY(data, p_sequencer.cfg.odd_parity); + } + } + `uvm_object_new + + task body(); + `uvm_info(`gfn, $sformatf("starting uart rx byte xfer seq: 0x%0h", data), UVM_HIGH) + req = uart_item::type_id::create("req"); + start_item(req); + req.stop_bit_c.constraint_mode(0); + `DV_CHECK_RANDOMIZE_WITH_FATAL(req, + data == local::data; + parity == local::parity; + stop_bit == !frame_err; + ) + finish_item(req); + get_response(rsp); + `uvm_info(`gfn, "uart rx byte xfer done", UVM_HIGH) + endtask + +endclass : uart_seq diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq_list.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq_list.sv new file mode 100644 index 0000000..994668a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/seq_lib/uart_seq_list.sv @@ -0,0 +1,7 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +`include "uart_base_seq.sv" +`include "uart_seq.sv" +`include "uart_default_seq.sv" diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.core b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.core new file mode 100644 index 0000000..f95aa93 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.core @@ -0,0 +1,32 @@ +CAPI=2: +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +name: "lowrisc:dv:uart_agent:0.1" +description: "UART DV UVM agent" +filesets: + files_dv: + depend: + - lowrisc:dv:dv_utils + - lowrisc:dv:dv_lib + files: + - uart_if.sv + - uart_agent_pkg.sv + - uart_item.sv: {is_include_file: true} + - uart_agent_cfg.sv: {is_include_file: true} + - uart_agent_cov.sv: {is_include_file: true} + - uart_driver.sv: {is_include_file: true} + - uart_monitor.sv: {is_include_file: true} + - uart_sequencer.sv: {is_include_file: true} + - uart_logger.sv: {is_include_file: true} + - uart_agent.sv: {is_include_file: true} + - seq_lib/uart_seq_list.sv: {is_include_file: true} + - seq_lib/uart_base_seq.sv: {is_include_file: true} + - seq_lib/uart_default_seq.sv: {is_include_file: true} + - seq_lib/uart_seq.sv: {is_include_file: true} + file_type: systemVerilogSource + +targets: + default: + filesets: + - files_dv diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.sv new file mode 100644 index 0000000..755d8d3 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent.sv @@ -0,0 +1,44 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_agent extends dv_base_agent#( + .CFG_T (uart_agent_cfg), + .DRIVER_T (uart_driver), + .SEQUENCER_T (uart_sequencer), + .MONITOR_T (uart_monitor), + .COV_T (uart_agent_cov) + ); + `uvm_component_utils(uart_agent) + + uart_logger m_logger; + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + // get uart_if handle + if (!uvm_config_db#(virtual uart_if)::get(this, "", "vif", cfg.vif)) begin + `uvm_fatal(`gfn, "failed to get uart_if handle from uvm_config_db") + end + + // Create the logger instance. + if (cfg.en_logger) begin + m_logger = uart_logger::type_id::create("m_logger", this); + m_logger.cfg = cfg; + end + endfunction + + function void connect_phase(uvm_phase phase); + super.connect_phase(phase); + // Connect the logger TLM port to the monitor. + if (cfg.en_logger) begin + if (cfg.use_rx_for_logger) begin + monitor.rx_analysis_port.connect(m_logger.log_item_fifo.analysis_export); + end else begin + monitor.tx_analysis_port.connect(m_logger.log_item_fifo.analysis_export); + end + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cfg.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cfg.sv new file mode 100644 index 0000000..4614e06 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cfg.sv @@ -0,0 +1,103 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_agent_cfg extends dv_base_agent_cfg; + + bit en_rx_checks = 1'b1; // enable RX checks (implemented in monitor) + bit en_tx_checks = 1'b1; // enable TX checks (implemented in monitor) + bit en_rx_monitor = 1'b1; // enable RX monitor + bit en_tx_monitor = 1'b1; // enable TX monitor + + // device specific cfg + baud_rate_e baud_rate; + bit en_parity; + bit odd_parity; + + // Controls upto what percentage of the clock period the RX is randomly glitched every 1ns. + // RX is glitched at the start of the clock to ensure that the design is robust enough to sample + // the correct value (typically at the center of the clock). The recommended range for this value + // is 0-10%. + local uint uart_period_glitch_pct = 10; + + // Logger settings. + bit en_logger = 1'b0; // enable logger on tx + bit use_rx_for_logger = 1'b0; // use rx instead of tx + bit write_logs_to_file = 1'b1; + + // interface handle used by driver, monitor & the sequencer + virtual uart_if vif; + + // The actual UART clock is not perfectly aligned to the baud rate. The clock btw transmitter and + // receiver can have certain difference + // driver is using perfect baud rate. Here is the max allowed clock drift for design comparing the + // ideal baud rate, This number must be less than 50 + // if set 20 here, received data must be ready to sample and stable at 30%-70% of the cycle + local uint max_drift_cycle_pct = 25; + + `uvm_object_utils_begin(uart_agent_cfg) + `uvm_field_int(en_rx_checks, UVM_DEFAULT) + `uvm_field_int(en_tx_checks, UVM_DEFAULT) + `uvm_field_int(en_tx_monitor, UVM_DEFAULT) + `uvm_field_int(en_rx_monitor, UVM_DEFAULT) + `uvm_field_int(en_parity, UVM_DEFAULT) + `uvm_field_int(odd_parity, UVM_DEFAULT) + `uvm_field_enum(baud_rate_e, baud_rate, UVM_DEFAULT) + `uvm_field_int(uart_period_glitch_pct, UVM_DEFAULT) + `uvm_object_utils_end + + `uvm_object_new + + function void set_uart_period_glitch_pct(uint pct); + `DV_CHECK_LT_FATAL(pct, 20) + uart_period_glitch_pct = pct; + endfunction + + function uint get_uart_period_glitch_pct(); + return uart_period_glitch_pct; + endfunction + + function void set_baud_rate(baud_rate_e b); + baud_rate = b; + vif.uart_clk_period = (get_baud_rate_period_ns(b) * 1ns); + endfunction + + function void set_parity(bit en_parity, bit odd_parity); + this.en_parity = en_parity; + this.odd_parity = odd_parity; + endfunction + + function void set_max_drift_cycle_pct(uint pct); + `DV_CHECK_LT_FATAL(pct, 50) + max_drift_cycle_pct = pct; + endfunction + + function int get_max_drift_cycle_pct(); + return max_drift_cycle_pct; + endfunction + + // Update dv_base_agent_cfg::in_reset to match the fact the interface has just gone into reset. + // This is needed because the uart interface doesn't have a reset pin, so its "notional reset" + // needs to be controlled from a higher level. + virtual function void reset_asserted(); + in_reset = 1; + endfunction + + // Update dv_base_agent_cfg::in_reset to match the fact the interface has just left reset. This is + // needed because the uart interface doesn't have a reset pin, so its "notional reset" needs to be + // controlled from a higher level. + // + // As well as updating in_reset, this function clears an interface and may re-enable some + // monitoring. + virtual function void reset_deasserted(bit re_enable_chk_mon = 1); + in_reset = 0; + vif.reset_uart_rx(); + if (re_enable_chk_mon) begin + en_rx_checks = 1; + en_tx_checks = 1; + en_rx_monitor = 1; + en_tx_monitor = 1; + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cov.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cov.sv new file mode 100644 index 0000000..a61e811 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_cov.sv @@ -0,0 +1,33 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_agent_cov extends dv_base_agent_cov #(uart_agent_cfg); + `uvm_component_utils(uart_agent_cov) + + covergroup uart_cg with function sample(uart_dir_e dir, uart_item item); + cp_dir: coverpoint dir; + cp_data: coverpoint item.data; + cp_en_parity: coverpoint cfg.en_parity; + cp_odd_parity: coverpoint cfg.odd_parity; + cp_baud_rate: coverpoint cfg.baud_rate; + cross cp_dir, cp_data, cp_en_parity, cp_odd_parity, cp_baud_rate; + endgroup + + // sample reset at every bit location in both direction + covergroup uart_reset_cg with function sample(uart_dir_e dir, int bit_position); + cp_dir: coverpoint dir; + cp_rst_pos: coverpoint bit_position { + // including parity, totally NUM_BIT_START_DATA_STOP+1 bits + bins values[] = {[0:NUM_UART_XFER_BITS_WO_PARITY]}; + } + cross cp_dir, cp_rst_pos; + endgroup + + function new(string name, uvm_component parent); + super.new(name, parent); + uart_cg = new(); + uart_reset_cg = new(); + endfunction : new + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_pkg.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_pkg.sv new file mode 100644 index 0000000..b99572b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_agent_pkg.sv @@ -0,0 +1,63 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +package uart_agent_pkg; + // dep packages + import uvm_pkg::*; + import dv_utils_pkg::*; + import dv_base_agent_pkg::*; + import dv_lib_pkg::*; + + // macro includes + `include "uvm_macros.svh" + `include "dv_macros.svh" + + // 1 start + 8 data + 1 stop + parameter uint NUM_UART_XFER_BITS_WO_PARITY = 10; + + // local types + typedef enum bit { + UartTx, + UartRx + } uart_dir_e; + + // Max standard baudrate is 256000 bps in the link below, so 1M should be 1024000 + // Refer to www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/matlab_external/baudrate.html + typedef enum int { + BaudRate9600 = 9600, + BaudRate115200 = 115200, + BaudRate230400 = 230400, + BaudRate128Kbps = 128000, + BaudRate256Kbps = 256000, + BaudRate1Mbps = 1000000, + BaudRate1p5Mbps = 1500000 + } baud_rate_e; + + // functions + function automatic real get_baud_rate_period_ns(baud_rate_e baud_rate); + // return 10^9 / baud_rate ns upto 3 decimal places + case(baud_rate) + BaudRate9600 : return 104166.667; + BaudRate115200: return 8680.556; + BaudRate230400: return 4340.278; + BaudRate128Kbps: return 7812.5; + BaudRate256Kbps: return 3906.25; + BaudRate1Mbps : return 1000; + BaudRate1p5Mbps: return 666.667; + default: `uvm_fatal("uart_agent_pkg", $sformatf("Unsupported baud_rate: %0d", baud_rate)) + endcase + endfunction + + // package sources + `include "uart_item.sv" + `include "uart_agent_cfg.sv" + `include "uart_agent_cov.sv" + `include "uart_monitor.sv" + `include "uart_driver.sv" + `include "uart_sequencer.sv" + `include "uart_logger.sv" + `include "uart_agent.sv" + `include "uart_seq_list.sv" + +endpackage diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_driver.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_driver.sv new file mode 100644 index 0000000..7cd64da --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_driver.sv @@ -0,0 +1,74 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_driver extends dv_base_driver #(uart_item, uart_agent_cfg); + `uvm_component_utils(uart_driver) + + `uvm_component_new + + task on_enter_reset(); + cfg.vif.reset_uart_rx(); + endtask + + // Sets the value of rx after randomly glitching for 10% of uart clk + task set_rx(input bit val); + uint glitch_ns = uint'(cfg.vif.uart_clk_period * cfg.get_uart_period_glitch_pct() / 100 / 1ns); + repeat (glitch_ns) begin + if (!cfg.in_reset) begin + cfg.vif.uart_rx <= $urandom_range(0, 1); + #1ns; + end + end + cfg.vif.uart_rx <= val; + endtask + + // Drives transfers. + virtual task get_and_drive(); + bit send_data[]; + forever begin + seq_item_port.get(req); + $cast(rsp, req.clone()); + rsp.set_id_info(req); + if (!cfg.in_reset) begin + `uvm_info(`gfn, $sformatf("starting to send rx item: %0s", rsp.sprint()), UVM_HIGH) + // we send parity if enabled or if overridden in the req + if (cfg.en_parity ^ req.ovrd_en_parity) begin + send_data = new[NUM_UART_XFER_BITS_WO_PARITY + 1]; // + 1 for parity bit + {<<{send_data}} = {req.stop_bit, req.parity, req.data, req.start_bit}; + end + else begin + send_data = new[NUM_UART_XFER_BITS_WO_PARITY]; + {<<{send_data}} = {req.stop_bit, req.data, req.start_bit}; + end + // send data on uart_rx + for (int i = 0; i < send_data.size(); i++) begin + set_rx(send_data[i]); + wait_uart_rx_cycle(); + end + `uvm_info(`gfn, $sformatf("finished sending rx item: %0s", rsp.sprint()), UVM_HIGH) + end + if (cfg.in_reset) begin + `uvm_info(`gfn, $sformatf("Reset happens and drop rx item: %0s", rsp.sprint()), UVM_HIGH) + end + seq_item_port.put_response(rsp); + end + endtask + + virtual task wait_uart_rx_cycle(); + fork + begin : isolation_fork + fork + begin + wait(cfg.in_reset); + end + begin + @(cfg.vif.drv_rx_mp.drv_rx_cb); + end + join_any + disable fork; + end : isolation_fork + join + endtask + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_if.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_if.sv new file mode 100644 index 0000000..43d592a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_if.sv @@ -0,0 +1,65 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +// +interface uart_if #(realtime UartDefaultClkPeriod = 104166.667ns) (); + wire uart_tx; + logic uart_rx; + + // generate local clk + realtime uart_clk_period = UartDefaultClkPeriod; + bit uart_tx_clk = 1'b1; + int uart_tx_clk_pulses = 0; + bit uart_rx_clk = 1'b1; + int uart_rx_clk_pulses = 0; + + // UART TX from the DUT when signaled over muxed IOs can experience glitches in the same + // time-step (a simulation artifact). Delaying by 1ps eliminates them. + wire uart_tx_int; + assign #1ps uart_tx_int = uart_tx; + + clocking mon_tx_cb @(negedge uart_tx_clk); + input #10ns uart_tx_int; + endclocking + modport mon_tx_mp(clocking mon_tx_cb); + + clocking drv_rx_cb @(posedge uart_rx_clk); + output uart_rx; + endclocking + modport drv_rx_mp(clocking drv_rx_cb); + + clocking mon_rx_cb @(negedge uart_rx_clk); + input #10ns uart_rx; + endclocking + modport mon_rx_mp(clocking mon_rx_cb); + + function automatic void reset_uart_rx(); + uart_rx = 1; + endfunction + + task automatic wait_for_tx_idle(); + wait(uart_tx_clk_pulses == 0); + endtask + + task automatic wait_for_rx_idle(); + wait(uart_rx_clk_pulses == 0); + endtask + + task automatic wait_for_idle(); + fork + wait_for_tx_idle(); + wait_for_rx_idle(); + join + endtask + + task automatic drive_uart_rx_glitch(int max_glitch_ps, int stable_ps_after_glitch); + uart_rx = ~uart_rx; + randcase + 1: #(max_glitch_ps * 1ps); + 1: #($urandom_range(1, max_glitch_ps) * 1ps); + endcase + uart_rx = ~uart_rx; + #(stable_ps_after_glitch * 1ps); + endtask + +endinterface diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_item.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_item.sv new file mode 100644 index 0000000..ed1b37b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_item.sv @@ -0,0 +1,46 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_item extends uvm_sequence_item; + + // start and stop bits + rand bit start_bit = 1'b0; + rand bit stop_bit = 1'b1; + + // byte of data sent or received + rand bit [7:0] data; + + // calculated parity of data sent or received + rand bit parity; + + // allow driver to override sending parity + rand bit ovrd_en_parity = 1'b0; + + // dont override start_bit unless testing an error scenario + constraint start_bit_c { + start_bit == 1'b0; + } + + // dont override stop_bit unless testing an error scenario + constraint stop_bit_c { + stop_bit == 1'b1; + } + + // dont override parity setting unless testing an error scenario + constraint ovrd_en_parity_c { + ovrd_en_parity == 1'b0; + } + + `uvm_object_utils_begin(uart_item) + `uvm_field_int(start_bit, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPRINT) + `uvm_field_int(data, UVM_DEFAULT) + // parity & stop_bit are checked in monitor + `uvm_field_int(parity, UVM_DEFAULT | UVM_NOCOMPARE) + `uvm_field_int(stop_bit, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPRINT) + `uvm_field_int(ovrd_en_parity, UVM_DEFAULT | UVM_NOCOMPARE | UVM_NOPRINT) + `uvm_object_utils_end + + `uvm_object_new + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_logger.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_logger.sv new file mode 100644 index 0000000..3bf4485 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_logger.sv @@ -0,0 +1,98 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_logger extends uvm_component; + `uvm_component_utils(uart_logger) + + int logs_output_fd = 0; + + uart_agent_cfg cfg; + uvm_tlm_analysis_fifo #(uart_item) log_item_fifo; + uvm_analysis_port #(string) log_analysis_port; + + `uvm_component_new + + virtual function void build_phase(uvm_phase phase); + log_item_fifo = new("log_item_fifo", this); + log_analysis_port = new("log_analysis_port", this); + endfunction + + virtual task run_phase(uvm_phase phase); + string fname = {`gfn, ".log"}; + if (cfg.write_logs_to_file) begin + logs_output_fd = $fopen(fname, "w"); + `DV_CHECK_FATAL((logs_output_fd !=0), $sformatf("Failed to open %s for writing", fname)) + end + capture_logs(); + endtask + + virtual function void final_phase(uvm_phase phase); + if (logs_output_fd != 0) $fclose(logs_output_fd); + endfunction + + // Captures bytes received from UART TX port and constructs the logs for printing. + virtual task capture_logs(); + uart_item item; + string char; + string log; + byte lf = 8'ha; // \n + byte cr = 8'hd; // \r + + fork + forever begin + log_item_fifo.get(item); + char = string'(item.data); + `uvm_info(`gfn, $sformatf("received char: %0s", char), UVM_DEBUG) + // Continue concatenating chars into the log string until lf or cr is encountered. + if (item.data inside {lf, cr}) begin + print_log(log); + log_analysis_port.write(log); + log = ""; + end + else begin + log = {log, char}; + end + end + forever begin + // reset thread - if reset occurs, reset the log to an empty string. + @(cfg.in_reset); + if (cfg.in_reset) log = ""; + end + join + endtask + + // Print log with the right severity. Severity is extracted from the log string. + // See sw/device/lib/runtime/log.h for details on how the severity is indicated. + // TODO: Add support for verbosity when the severity is info. + virtual function void print_log(string log); + string info = "INFO: *"; + string warn = "WARNING: *"; + string error = "ERROR: *"; + string fatal = "FATAL: *"; + + if (log == "") return; + case (1) + (!uvm_re_match(info, log)): begin + `uvm_info(`gfn, log.substr(info.len() - 1, log.len() - 1), UVM_LOW) + end + (!uvm_re_match(warn, log)): begin + // verilog_lint: waive forbidden-macro + `uvm_warning(`gfn, log.substr(warn.len() - 1, log.len() - 1)) + end + (!uvm_re_match(error, log)): begin + `uvm_error(`gfn, log.substr(error.len() - 1, log.len() - 1)) + end + (!uvm_re_match(fatal, log)): begin + `uvm_fatal(`gfn, log.substr(fatal.len() - 1, log.len() - 1)) + end + default: begin + `uvm_info(`gfn, log, UVM_LOW) + end + endcase + if (logs_output_fd != 0) begin + $fwrite(logs_output_fd, "[%15t]: %0s\n", $time, log); + end + endfunction + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_monitor.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_monitor.sv new file mode 100644 index 0000000..c53e450 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_monitor.sv @@ -0,0 +1,211 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + + +class uart_monitor extends dv_base_monitor#( + .ITEM_T (uart_item), + .CFG_T (uart_agent_cfg), + .COV_T (uart_agent_cov) + ); + `uvm_component_utils(uart_monitor) + + // Analysis port for the collected transfer. + uvm_analysis_port #(uart_item) tx_analysis_port; + uvm_analysis_port #(uart_item) rx_analysis_port; + + `uvm_component_new + + function void build_phase(uvm_phase phase); + super.build_phase(phase); + tx_analysis_port = new("tx_analysis_port", this); + rx_analysis_port = new("rx_analysis_port", this); + endfunction + + task run_phase(uvm_phase phase); + forever begin + fork + collect_tx_data(); + collect_rx_data(); + drive_tx_clk(); + drive_rx_clk(); + mon_tx_stable(); + wait(cfg.in_reset); + join_any + disable fork; + + if (cfg.in_reset) process_reset(); + end + endtask + + virtual task collect_tx_data(); + uart_item item; + forever begin + if (cfg.vif.uart_tx === 1'b0 && cfg.en_tx_monitor == 1) begin + // 1 start + 8 data + 1 parity (if enabled) + 1 stop + cfg.vif.uart_tx_clk_pulses = NUM_UART_XFER_BITS_WO_PARITY + cfg.en_parity; + item = uart_item::type_id::create("item"); + // get the start bit + @(cfg.vif.mon_tx_mp.mon_tx_cb); + `uvm_info(`gfn, $sformatf("tx start bit %0b", cfg.vif.uart_tx_int), UVM_HIGH) + item.start_bit = cfg.vif.uart_tx_int; + // get the data bits + for (int i = 0; i < 8; i++) begin + @(cfg.vif.mon_tx_mp.mon_tx_cb); + `uvm_info(`gfn, $sformatf("tx data bit[%0d] %0b", i, cfg.vif.uart_tx_int), UVM_DEBUG) + item.data[i] = cfg.vif.uart_tx_int; + end + // get the parity bit + if (cfg.vif.uart_tx_clk_pulses > 2) begin + @(cfg.vif.mon_tx_mp.mon_tx_cb); + `uvm_info(`gfn, $sformatf("tx parity bit %0b", cfg.vif.uart_tx_int), UVM_DEBUG) + item.parity = cfg.vif.uart_tx_int; + if (cfg.en_tx_checks && item.parity != `GET_PARITY(item.data, cfg.odd_parity)) begin + `uvm_error(`gfn, "Parity failed") + end + end + else item.parity = 1'b0; + + // get the stop bit + @(cfg.vif.mon_tx_mp.mon_tx_cb); + `uvm_info(`gfn, $sformatf("tx stop bit %0b", cfg.vif.uart_tx_int), UVM_DEBUG) + item.stop_bit = cfg.vif.uart_tx_int; + // check stop bit + if (cfg.en_tx_checks && cfg.vif.uart_tx_int !== 1'b1) begin + `uvm_error(`gfn, "No stop bit when expected!") + end + `uvm_info(`gfn, $sformatf("collected uart tx txn:\n%0s", item.sprint()), UVM_HIGH) + tx_analysis_port.write(item); + + // wait for uart_tx_clk_pulses==0, otherwise, it may affect next transaction + cfg.vif.wait_for_tx_idle(); + + if (cfg.en_cov) cov.uart_cg.sample(UartTx, item); + end else begin + @(cfg.vif.uart_tx_int); + end + end + endtask + + virtual task collect_rx_data(); + uart_item item; + forever begin + if (cfg.vif.uart_rx === 1'b0 && cfg.en_rx_monitor == 1) begin + item = uart_item::type_id::create("item"); + cfg.vif.uart_rx_clk_pulses = NUM_UART_XFER_BITS_WO_PARITY + cfg.en_parity; + // get the start bit + @(cfg.vif.mon_rx_mp.mon_rx_cb); + `uvm_info(`gfn, $sformatf("rx start bit %0b", cfg.vif.uart_rx), UVM_DEBUG) + item.start_bit = cfg.vif.uart_rx; + // get the data bits + for (int i = 0; i < 8; i++) begin + @(cfg.vif.mon_rx_mp.mon_rx_cb); + `uvm_info(`gfn, $sformatf("rx data bit[%0d] %0b", i, cfg.vif.uart_rx), UVM_DEBUG) + item.data[i] = cfg.vif.uart_rx; + end + // get the parity bit + if (cfg.vif.uart_rx_clk_pulses > 2) begin + @(cfg.vif.mon_rx_mp.mon_rx_cb); + `uvm_info(`gfn, $sformatf("rx parity bit %0b", cfg.vif.uart_rx), UVM_DEBUG) + item.parity = cfg.vif.uart_rx; + if (cfg.en_rx_checks && item.parity != `GET_PARITY(item.data, cfg.odd_parity)) begin + `uvm_error(`gfn, "Parity failed") + end + end + else item.parity = 1'b0; + + // get the stop bit + @(cfg.vif.mon_rx_mp.mon_rx_cb); + `uvm_info(`gfn, $sformatf("rx stop bit %0b", cfg.vif.uart_rx), UVM_DEBUG) + item.stop_bit = cfg.vif.uart_rx; + // check stop bit + if (cfg.en_rx_checks && cfg.vif.uart_rx !== 1'b1) begin + `uvm_error(`gfn, "No stop bit when expected!") + end + `uvm_info(`gfn, $sformatf("collected uart rx txn:\n%0s", item.sprint()), UVM_HIGH) + rx_analysis_port.write(item); + + // wait for uart_rx_clk_pulses==0, otherwise, it may affect next transaction + cfg.vif.wait_for_rx_idle(); + + if (cfg.en_cov) cov.uart_cg.sample(UartRx, item); + end else begin + @(cfg.vif.uart_rx); + end + end + endtask + + task drive_tx_clk(); + forever begin + if (cfg.vif.uart_tx_clk_pulses > 0) begin + #(cfg.vif.uart_clk_period / 2); + cfg.vif.uart_tx_clk = ~cfg.vif.uart_tx_clk; + // last cycle only use half period as design and agent aren't using same clock. If agent + // freq is slower and design continues sending tx item, the freq diff will be accumulated. + // Ending current item after latch STOP bit to allow agent to re-establish clock to sample + // the START bit of next item + if (cfg.vif.uart_tx_clk_pulses == 1) #(cfg.vif.uart_clk_period / 4); + else #(cfg.vif.uart_clk_period / 2); + cfg.vif.uart_tx_clk = ~cfg.vif.uart_tx_clk; + cfg.vif.uart_tx_clk_pulses--; + end else begin + @(cfg.vif.uart_tx_int, cfg.vif.uart_tx_clk_pulses); + end + end + endtask + + task drive_rx_clk(); + forever begin + if (cfg.vif.uart_rx_clk_pulses > 0) begin + #(cfg.vif.uart_clk_period / 2); + cfg.vif.uart_rx_clk = ~cfg.vif.uart_rx_clk; + #(cfg.vif.uart_clk_period / 2); + cfg.vif.uart_rx_clk = ~cfg.vif.uart_rx_clk; + cfg.vif.uart_rx_clk_pulses--; + end else begin + @(cfg.vif.uart_rx, cfg.vif.uart_rx_clk_pulses); + end + end + endtask + + // actual uart clock isn't ideal, it's allowed to off less than max_drift_cycle_pct cycle as cfg + // this to check data stable from (50 - max_drift_cycle_pct) to (50 + max_drift_cycle_pct) + task mon_tx_stable(); + forever begin + @(cfg.vif.uart_tx_clk_pulses); + if (cfg.vif.uart_tx_clk_pulses == 0) continue; + + #(cfg.vif.uart_clk_period * (50 - cfg.get_max_drift_cycle_pct()) / 100); + `DV_SPINWAIT_EXIT( + begin + @(cfg.vif.uart_tx_int); + `uvm_error(`gfn, $sformatf( + "Expect uart_tx stable from %0d to %0d of the period, but it's changed", + 50 - cfg.get_max_drift_cycle_pct(), 50 + cfg.get_max_drift_cycle_pct())) + end, + // simplified from cfg.vif.uart_clk_period * max_drift_cycle_pct * 2 / 100 + #(cfg.vif.uart_clk_period * cfg.get_max_drift_cycle_pct() / 50)) + end + endtask + + // update ok_to_end to prevent sim finish when there is any activity on the bus + virtual task monitor_ready_to_end(); + forever begin + @(cfg.vif.uart_tx_clk_pulses or cfg.vif.uart_rx_clk_pulses); + ok_to_end = (cfg.vif.uart_tx_clk_pulses == 0) && (cfg.vif.uart_rx_clk_pulses == 0); + end + endtask + + virtual task process_reset(); + if (cfg.en_cov) begin + cov.uart_reset_cg.sample(UartTx, cfg.vif.uart_tx_clk_pulses); + cov.uart_reset_cg.sample(UartRx, cfg.vif.uart_rx_clk_pulses); + end + cfg.vif.uart_tx_clk_pulses = 0; + cfg.vif.uart_tx_clk = 1; + cfg.vif.uart_rx_clk_pulses = 0; + cfg.vif.uart_rx_clk = 1; + wait(!cfg.in_reset); + endtask + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_sequencer.sv b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_sequencer.sv new file mode 100644 index 0000000..89f25ca --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/sv/uart_agent/uart_sequencer.sv @@ -0,0 +1,10 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +class uart_sequencer extends dv_base_sequencer#(uart_item, uart_agent_cfg); + `uvm_component_utils(uart_sequencer) + + `uvm_component_new + +endclass diff --git a/hw/vendor/lowrisc_ip/dv/tools/common.tcl b/hw/vendor/lowrisc_ip/dv/tools/common.tcl new file mode 100644 index 0000000..7743450 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/common.tcl @@ -0,0 +1,73 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +# Commonly used globals & procs. This file must be sourced first. +set simulator "" +if {[info exists ::env(SIMULATOR)]} { + set simulator "$::env(SIMULATOR)" +} else { + puts "ERROR: tool script run without SIMULATOR environment variable." + quit +} + +set waves "none" +if {[info exists ::env(WAVES)]} { + set waves "$::env(WAVES)" +} + +set gui 0 +if {[info exists ::env(GUI)]} { + set gui "$::env(GUI)" +} + +set gui_debug 0 +# Detect when GUI debug mode has been invoked to build UVM objects by default +if {[info exists ::env(GUI_DEBUG)]} { + set gui_debug "$::env(GUI_DEBUG)" +} + +set tb_top "tb" +if {[info exists ::env(TB_TOP)]} { + set tb_top "$::env(TB_TOP)" +} else { + puts "WARNING: TB_TOP environment variable not set - using \"tb\" as the + top level testbench hierarchy." +} + +# Checks if variable is defined, else throw an error and exit. +proc checkVarExists {var} { + upvar $var var_ + if {![info exists var_]} { + puts "ERROR: Variable \"$var\" not found." + quit + } +} + +# If variable is defined, then use it, else set the default value. +proc setDefault {var value} { + upvar $var var_ + if {[info exists var_]} { + puts "INFO: \"$var\" is already set to \"$var_\"." + } else { + puts "INFO: Setting \"$var\" to \"$value\"." + set var_ $value + } + return $var_ +} + +proc checkEq {var value} { + upvar $var var_ + if {$var_ != $value} { + puts "ERROR: Check failed \"$var\" == \"$value\"!. Actual: \"$var_\"." + quit + } +} + +proc checkNe {var value} { + upvar $var var_ + if {$var_ == $value} { + puts "ERROR: Check failed \"$var\" != \"$value\"!. Actual: \"$var_\"." + quit + } +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/dvsim/common_modes.hjson b/hw/vendor/lowrisc_ip/dv/tools/dvsim/common_modes.hjson new file mode 100644 index 0000000..d158c61 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/dvsim/common_modes.hjson @@ -0,0 +1,82 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +{ + // Sim modes are collection of build_opts and run_opts + // These are only set on the command line + // These are different from the build modes in the sense that these collection of + // options are appended to actual build_modes + build_modes: [ + { + name: gui + is_sim_mode: 1 + en_build_modes: ["{tool}_gui"] + } + { + name: gui_debug + is_sim_mode: 1 + en_build_modes: ["{tool}_gui_debug"] + } + { + name: waves + is_sim_mode: 1 + en_build_modes: ["{tool}_waves"] + } + { + name: waves_off + is_sim_mode: 1 + en_build_modes: ["{tool}_waves_off"] + } + { + name: cov + is_sim_mode: 1 + en_build_modes: ["{tool}_cov"] + // This plusarg is retrieved in `hw/dv/sv/dv_lib/dv_base_test.sv`. If not set, the coverage + // collection components are not created. + run_opts: ["+en_cov=1"] + } + { + name: profile + is_sim_mode: 1 + en_build_modes: ["{tool}_profile"] + } + { + name: xprop + is_sim_mode: 1 + en_build_modes: ["{tool}_xprop"] + } + { + name: loopdetect + is_sim_mode: 1 + en_build_modes: ["{tool}_loopdetect"] + } + // Enables randomization of testbench / RTL build. + // + // Build randomization is achieved by passing `--build-seed ` on the dvsim + // command-line. If not passed, the build is not randomized. Build randomization is achieved + // in two ways. One of them is setting the pre-processor macro `BUILD_SEED` to the seed value, + // which is done below. The SystemVerilog testbench sources can use the `BUILD_SEED` macro + // value to set some design constants (such as parameters) upon instantiation. The `BUILD_SEED`, + // if not set externally (by passing the --build-seed switch) is set to 1 in + // `hw/dv/sv/dv_utils/dv_macros.svh`. The other way is by passing the {seed} value to utility + // scripts that generate packages that contain randomized constants. These utility scripts can + // be invoked as a `pre_build_cmd`, wrapped within the `build_seed` sim mode in the DUT + // simulation configuration Hjson file. All forms of build randomization must be wrapped within + // this `build_seed` sim mode. They will all use the same {seed} value, which allows us to + // deterministically reproduce failures. The `--build-seed` switch is expected to be passed + // when running the nightly regressions. The `seed` value set by dvsim is a 32-bit unsigned + // integer (unless specified on the command-line). + { + name: build_seed + is_sim_mode: 1 + build_opts: ["+define+BUILD_SEED={seed}"] + } + ] + + run_modes: [ + { + name: uvm_trace + run_opts: ["+UVM_PHASE_TRACE", "+UVM_CONFIG_DB_TRACE", "+UVM_OBJECTION_TRACE"] + } + ] +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/dvsim/fusesoc.hjson b/hw/vendor/lowrisc_ip/dv/tools/dvsim/fusesoc.hjson new file mode 100644 index 0000000..66e282e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/dvsim/fusesoc.hjson @@ -0,0 +1,16 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +{ + sv_flist_gen_cmd: fusesoc + fusesoc_core_: "{eval_cmd} echo \"{fusesoc_core}\" | tr ':' '_'" + sv_flist_gen_opts: ["{fusesoc_cores_root_dirs}", + "run", + "{sv_flist_gen_flags}", + "--target=sim", + "--work-root={build_dir}/fusesoc-work", + "--setup {fusesoc_core}"] + fusesoc_cores_root_dirs: ["--cores-root {proj_root}/hw"] + sv_flist_gen_dir: "{build_dir}/fusesoc-work" + sv_flist: "{sv_flist_gen_dir}/{fusesoc_core_}.scr" +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/dvsim/sim.mk b/hw/vendor/lowrisc_ip/dv/tools/dvsim/sim.mk new file mode 100644 index 0000000..2a93d3b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/dvsim/sim.mk @@ -0,0 +1,137 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +export SHELL := /usr/bin/env bash +.DEFAULT_GOAL := all + +LOCK_ROOT_DIR ?= flock --timeout 3600 ${proj_root} --command + +all: build run + +############################### +## sim build and run targets ## +############################### +build: build_result + +pre_build: + @echo -e "\n[make]: pre_build" + mkdir -p ${build_dir} +ifneq (${pre_build_cmds},) + # pre_build_cmds are likely changing the in-tree sources. We hence use FLOCK + # utility to prevent multiple builds that may be running in parallel from + # stepping on each other. TODO: Enforce the list of pre_build_cmds is + # identical across all build modes. + ${LOCK_ROOT_DIR} "cd ${build_dir} && ${pre_build_cmds}" +endif + +gen_sv_flist: pre_build + @echo -e "\n[make]: gen_sv_flist" +ifneq (${sv_flist_gen_cmd},) + cd ${build_dir} && ${sv_flist_gen_cmd} ${sv_flist_gen_opts} +endif + +do_build: gen_sv_flist + @echo -e "\n[make]: build" + cd ${sv_flist_gen_dir} && ${build_cmd} ${build_opts} + +post_build: do_build + @echo -e "\n[make]: post_build" +ifneq (${post_build_cmds},) + cd ${build_dir} && ${post_build_cmds} ${post_build_opts} +endif + +build_result: post_build + @echo -e "\n[make]: build_result" + +run: run_result + +pre_run: + @echo -e "\n[make]: pre_run" + mkdir -p ${run_dir} +ifneq (${pre_run_cmds},) + cd ${run_dir} && ${pre_run_cmds} +endif + +sw_build: pre_run + @echo -e "\n[make]: sw_build" +ifneq (${sw_images},) + cd ${proj_root} && ${sw_build_cmd} --build-seed=${build_seed} +endif + +simulate: sw_build + @echo -e "\n[make]: simulate" + cd ${run_dir} && ${run_cmd} ${run_opts} + +post_run: simulate + @echo -e "\n[make]: post_run" +ifneq (${post_run_cmds},) + cd ${run_dir} && ${post_run_cmds} +endif + +run_result: post_run + @echo -e "\n[make]: run_result" + +####################### +## Load waves target ## +####################### +debug_waves: + ${debug_waves_cmd} ${debug_waves_opts} + +############################ +## coverage rated targets ## +############################ +cov_unr_build: gen_sv_flist + @echo -e "\n[make]: cov_unr_build" + cd ${sv_flist_gen_dir} && ${cov_unr_build_cmd} ${cov_unr_build_opts} + +cov_unr_vcs: cov_unr_build + @echo -e "\n[make]: cov_unr" + cd ${sv_flist_gen_dir} && ${cov_unr_run_cmd} ${cov_unr_run_opts} + +cov_unr_xcelium: + @echo -e "\n[make]: cov_unr" + mkdir -p ${cov_unr_dir} + cd ${cov_unr_dir} && ${cov_unr_run_cmd} ${cov_unr_run_opts} + +cov_unr_merge: + @echo -e "\n[make]: cov_unr_merge" + cd ${cov_unr_dir} && ${job_prefix} ${cov_merge_cmd} -init ${cov_unr_dir}/jgproject/sessionLogs/session_0/unr_imc_coverage_merge.cmd + +ifeq (${SIMULATOR}, xcelium) + cov_unr: cov_unr_xcelium cov_unr_merge +else + cov_unr: cov_unr_vcs +endif + +# Merge coverage if there are multiple builds. +cov_merge: + @echo -e "\n[make]: cov_merge" + ${job_prefix} ${cov_merge_cmd} ${cov_merge_opts} + +# Generate coverage reports. +cov_report: + @echo -e "\n[make]: cov_report" + ${cov_report_cmd} ${cov_report_opts} + +# Open coverage tool to review and create report or exclusion file. +cov_analyze: + @echo -e "\n[make]: cov_analyze" + ${cov_analyze_cmd} ${cov_analyze_opts} + +.PHONY: build \ + pre_build \ + gen_sv_flist \ + do_build \ + post_build \ + build_result \ + run \ + pre_run \ + sw_build \ + simulate \ + post_run \ + run_result \ + debug_waves \ + cov_merge \ + cov_analyze \ + cov_report diff --git a/hw/vendor/lowrisc_ip/dv/tools/dvsim/xcelium.hjson b/hw/vendor/lowrisc_ip/dv/tools/dvsim/xcelium.hjson new file mode 100644 index 0000000..045f6b7 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/dvsim/xcelium.hjson @@ -0,0 +1,283 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 +{ + build_cmd: "{job_prefix} xrun" + run_cmd: "{job_prefix} xrun" + + build_db_dir: "{build_dir}/xcelium.d" + + build_opts: ["-elaborate -64bit -sv", + // Wait to acquire a license. + "-licqueue", + // TODO: duplicate primitives between OT and Ibex #1231 + "-ALLOWREDEFINITION", + "-messages -errormax 50", + "-timescale {timescale}", + "-f {sv_flist}", + "-uvmhome CDNS-1.2", + // Specify the library name for the run step to use. + "-xmlibdirname {build_db_dir}", + // List multiple tops for the simulation. Prepend each top level with `-top`. + "{eval_cmd} echo {sim_tops} | sed -E 's/(\\S+)/-top \\1/g'", + // Set the top level elaborated entity (snapshot name) correctly since there are + // multiple tops. + "-snapshot {tb}", + // for uvm_hdl_* used by csr backdoor + "-access +rw", + // This is to fix a timescale issue due to using `resetall to reset timescale and + // `-sv` compile option. #7178 + "-enable_strict_timescale", + // Use this to conditionally compile for Xcelium (example: LRM interpretations differ + // across tools). + "+define+XCELIUM", + // Suppress printing of the copyright banner. + "-nocopyright", + // Ignore "timescale is not specified for the package" warning + "-nowarn TSNSPK", + // Ignore "IEEE 1800-2009 SystemVerilog simulation semantics" warning + "-nowarn DSEMEL", + // Ignore hierarchial ref warnings in interfaces + "-nowarn CUVIHR", + // Ignore warning "Potentially reversed dist range may cause it to be treated as + // empty". This is thrown when and expression like `var - 1` is added to a + // randomization distribution, which can potentially be a negative value. + "-nowarn REVRNG", + // Ignore warning "Include directory given but not used". This is benign. + "-nowarn SPDUSD", + // Needed for including "secded_enc.h". + "-I{build_dir}/fusesoc-work/src/lowrisc_dv_secded_enc_0", + // This warning is thrown when a scalar enum variable is assigned to an enum array. + // Other tools (e.g., FPV) treat such assignments as an error, hence we bump it to + // an error in simulation so that this can be caught early in CI. + "-xmerror ENUMERR", + // Enables LRM compliant behavior for $asserton, $assertoff and $assertkill tasks. + "-enable_abv_asrtctrl_enh" + ] + + // We want to allow the possibility of passing no test or no test sequence. Unfortunately, + // Xcelium generates an error (*E,OPTP2ND) if you pass an empty plusarg. To avoid doing so, these + // two variables expand to e.g. "+UVM_TESTNAME=foo" if we have a test and the empty string if + // not. + uvm_testname_plusarg: "{eval_cmd} echo {uvm_test} | sed -E 's/(.+)/+UVM_TESTNAME=\\1/'" + uvm_testseq_plusarg: "{eval_cmd} echo {uvm_test_seq} | sed -E 's/(.+)/+UVM_TEST_SEQ=\\1/'" + + run_opts: ["-input {run_script}", + // Suppress printing of the copyright banner. + "-nocopyright", + // Wait to acquire a license. + "-licqueue", + "-64bit -xmlibdirname {build_db_dir}", + // Use the same snapshot name set during the build step. + "-r {tb}", + "+SVSEED={svseed}", + "{uvm_testname_plusarg}", + "{uvm_testseq_plusarg}", + // Ignore "IEEE 1800-2009 SystemVerilog simulation semantics" warning + "-nowarn DSEM2009", + ] + + // Vars that need to exported to the env. + exports: [ + // Poll for an available license in all servers. + { CDS_LIC_QUEUE_POLL: 1 }, + + // Poll for an available license every 1 min. + { CDS_LIC_QUEUE_POLL_INT: 60 }, + + // X-prop related: these were suggested by Xcelium as warnings during the build time. + // These enable array corruption when the index is out of range or invalid. + { VL_ENABLE_INVALID_IDX_XPROP: 1 }, + { VL_ENABLE_OUTOFRANGE_IDX_XPROP: 1 }, + + // Export the cov_report path so that the tcl file can read these as env vars. + { cov_merge_db_dir: "{cov_merge_db_dir}" }, + { cov_report_dir: "{cov_report_dir}" } + + // Export unr related paths for make + {cov_unr_dir: "{cov_unr_dir}" } + // Add an additional single quotation because `cov_merge_cmd` has an empty space, it will cause + // trouble when exporting the entire command in the environment. + {cov_merge_cmd: "{cov_merge_cmd}"} + + // job prefix + {job_prefix: "{job_prefix}"} + + // The Verdi FSDB dumper libraries (see xcelium_fsdb_pli_opt) depend on libIUS.so, which lives + // alongside them and has no rpath, so add their directory when dumping FSDB waves. + {LD_LIBRARY_PATH: "{xcelium_fsdb_ld_library_path}"} + + ] + + // Supported wave dumping formats (in order of preference). + supported_wave_formats: ["shm", "fsdb", "vcd"] + + // Load the Verdi FSDB dumper when dumping waves in FSDB format (requires VERDI_HOME). The PLI + // provides the $fsdb* system tasks and the CFC library provides the `call fsdb*` Tcl commands + // used by waves.tcl. Both expand to nothing for other wave formats. + xcelium_fsdb_pli_opt: "{eval_cmd} [ {waves} = fsdb ] && echo -loadpli1 $VERDI_HOME/share/PLI/IUS/linux64/boot/debpli.so:novas_pli_boot || true" + xcelium_fsdb_cfc_opt: "{eval_cmd} [ {waves} = fsdb ] && echo -loadcfc $VERDI_HOME/share/PLI/IUS/linux64/boot/debcfc.so:novas_cfc_boot || true" + xcelium_fsdb_ld_library_path: "{eval_cmd} [ {waves} = fsdb ] && echo $VERDI_HOME/share/PLI/IUS/linux64/boot:$LD_LIBRARY_PATH || echo $LD_LIBRARY_PATH" + + // Default tcl script used when running the sim. Override if needed. + run_script: "{dv_root}/tools/sim.tcl" + + // Coverage related. + // By default, collect all coverage metrics: block:expr:fsm:toggle:functional. + cov_metrics: all + + // Supply the cov configuration file. + // Note that this needs to be set as -covfile . + xcelium_cov_cfg_file: "" + + // Supply the cov exclusion tcl script - passed on to IMC using the -init switch. + xcelium_cov_excl_script: "" + + // Supply the cov refinement files - passed on to IMC using the -load_refinement switch. + xcelium_cov_refine_files: [] + + // Set the coverage directories. + cov_work_dir: "{scratch_path}/coverage" + cov_db_dir: "{cov_work_dir}/{build_mode}" + + // Individual test specific coverage data - this will be deleted if the test fails + // so that coverage from failiing tests is not included in the final report. + cov_db_test_dir_name: "{run_dir_name}.{svseed}" + cov_db_test_dir: "{cov_db_dir}/{cov_db_test_dir_name}" + + // Merging coverage. + // It is constructed by the tool itself. + cov_merge_dir: "{scratch_path}/cov_merge" + cov_merge_db_dir: "{cov_merge_dir}/merged" + cov_merge_cmd: "imc" + cov_merge_opts: ["-64bit", + "-licqueue", + "-exec {dv_root}/tools/xcelium/cov_merge.tcl"] + + // Generate covreage reports in text as well as html. + cov_report_dir: "{scratch_path}/cov_report" + cov_report_cmd: "{job_prefix} imc" + cov_report_opts: ["-64bit", + "-licqueue", + "-load {cov_merge_db_dir}", + " {eval_cmd} echo {xcelium_cov_excl_script} | sed -E 's/(\\S+)/-init \\1/g' ", + " {eval_cmd} echo {xcelium_cov_refine_files} | sed -E 's/(\\S+)/-load_refinement \\1/g' ", + "-exec {dv_root}/tools/xcelium/cov_report.tcl"] + cov_report_txt: "{cov_report_dir}/cov_report.txt" + cov_report_page: "index.html" + + // Analyzing coverage - this is done by invoking --cov-analyze switch. It opens up the + // GUI for visual analysis. + cov_analyze_dir: "{scratch_path}/cov_analyze" + cov_analyze_cmd: "{job_prefix} imc" + cov_analyze_opts: ["-64bit", + "-licqueue", + "-load {cov_merge_db_dir}", + " {eval_cmd} echo {xcelium_cov_excl_script} | sed -E 's/(\\S+)/-init \\1/g' ", + " {eval_cmd} echo {xcelium_cov_refine_files} | sed -E 's/(\\S+)/-load_refinement \\1/g' "] + + cov_unr_dir: "{scratch_path}/cov_unr" + + // not needed we can reuse the last build snapshot + cov_unr_build_opts:[] + cov_unr_build_cmd:[] + + cov_unr_run_cmd: "{job_prefix} xrun" + + + cov_unr_run_opts: [// use xrun in UNR mode + "-unr", + // JasperGold switch (use formal) + "-jg", + // use the same snapshot as used for regression + "-r {tb}", + // pointer to the merged coverage data from the regression + "-covdb {cov_merge_db_dir}", + // what metrics to use + "-jg_coverage {cov_metrics}", + "-64bit", + "-xmlibdirname {build_db_dir}", + "-jgargs '-allow_unsupported_OS'", + // overwrite previous results + "-covoverwrite", + "-inst_top {dut_instance}", + // UNR Configurations + "-input {xcelium_unr_cfg_file} "] + + + // pass and fail patterns + build_fail_patterns: ["\\*E.*$"] + run_fail_patterns: ["\\*E.*$"] // Null pointer error + + build_modes: [ + { + name: xcelium_gui + is_sim_mode: 1 + build_opts: ["-createdebugdb", "-access +c"] + run_opts: ["-gui"] + } + { + name: xcelium_gui_debug + is_sim_mode: 1 + build_opts: ["-createdebugdb", "-access +c", "-uvmlinedebug", "-linedebug", + "+uvm_set_config_int=*,recording_detail,1"] + run_opts: ["-gui", + "-input '@database -open waves -into waves.shm -default; probe -create \n" + "tb -depth all -packed 32k -unpacked 32k -all -dynamic -database waves'", + "+uvm_set_config_int=*,recording_detail,1"] + } + { + name: xcelium_waves + is_sim_mode: 1 + build_opts: ["-access +c", "{xcelium_fsdb_pli_opt}"] + run_opts: ["{xcelium_fsdb_pli_opt}", "{xcelium_fsdb_cfc_opt}"] + } + { + name: xcelium_waves_off + is_sim_mode: 1 + build_opts: [] + } + { + name: xcelium_cov + is_sim_mode: 1 + build_opts: [// Enable the required cov metrics. + "-coverage {cov_metrics}", + // Limit the scope of coverage collection to the DUT. + "-covdut {dut}", + // Set the coverage configuration file + "-covfile {xcelium_cov_cfg_file}", + // Don't warn about the switches we set that will be default in future releases. + "-nowarn COVDEF", + ] + run_opts: [// Put the coverage model (*.ucm) and the database (*.ucd) together. + "-covmodeldir {cov_db_test_dir}", + // Coverage database output location. + "-covworkdir {cov_work_dir}", + // Set the scope to the build mode name. + "-covscope {build_mode}", + // Test coverage dir name to create under cov_db_dir. + "-covtest {cov_db_test_dir_name}", + // Overwrite the coverage data of a specific test/seed if it already exists. + "-covoverwrite"] + } + // TODO support profile for xcelium + { + name: xcelium_profile + is_sim_mode: 1 + build_opts: ["-perfstat"] + run_opts: ["-perfstat", "-perflog perfstat.log"] + } + { + name: xcelium_xprop + is_sim_mode: 1 + build_opts: ["-xprop F -xverbose"] + } + { + // TODO: Add build and run options to enable zero delay loop detection. + name: xcelium_loopdetect + is_sim_mode: 1 + build_opts: [] + run_opts: [] + } + ] +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/sim.tcl b/hw/vendor/lowrisc_ip/dv/tools/sim.tcl new file mode 100644 index 0000000..41e1f0b --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/sim.tcl @@ -0,0 +1,60 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +# Common TCL script invoked at run-time by the simulator. +# VCS syntax: -ucli -do +# Xcelium syntax: -input + +set dv_root "" +if {[info exists ::env(dv_root)]} { + set dv_root "$::env(dv_root)" +} else { + puts "ERROR: Script run without dv_root environment variable." + quit +} + +# Dumping waves in specific hierarchies. +# +# By default, if wave dumping is enabled, all hierarchies of the top level testbench are dumped. +# For large designs, this may slow down the simulation considerably. To bypass this and only enable +# waves in specific hierarchies, set the dump_tb_top flag to 0 (i.e. uncomment the line below), and +# specify the paths to dump on line 32. +# set dump_tb_top 0 + +source "${dv_root}/tools/common.tcl" +source "${dv_root}/tools/waves.tcl" + +global waves +global simulator +global tb_top + +# Dumping waves in specific hierarchies (example): +# wavedumpScope $waves $simulator tb.dut.foo.bar 12 +# wavedumpScope $waves $simulator tb.dut.baz 0 + +if {$simulator eq "xcelium"} { + puts "INFO: The following assertions are permamently disabled:" + assertion -list -depth all -multiline -permoff $tb_top +} + +global gui +global gui_debug +# In GUI mode, let the user take control of running the simulation. +# In GUI debug mode, run only up until the end of the UVM elaboration phase to have access to the +# dynamic objects. +if {$gui_debug == 1} { + if {$simulator eq "xcelium"} { + uvm_phase -stop_at build -end + run + } +} elseif {$gui == 0} { + run + if {$simulator eq "xcelium"} { + # Xcelium provides a `finish` tcl command instead of `quit`. The argument '2' enables the + # logging of additional resource usage information. + finish 2 + } else { + quit + } +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/waves.tcl b/hw/vendor/lowrisc_ip/dv/tools/waves.tcl new file mode 100644 index 0000000..fb92bd2 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/waves.tcl @@ -0,0 +1,163 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +# This is sourced by all supported simulators. The driver scripts +# (dvsim) need to make sure that we don't ask for an unsupported +# dumping format (SHM with VCS, for example). The adjoining common.tcl +# must be sourced prior to sourcing this file. + +if {[info proc setDefault] ne "setDefault"} { + puts "ERROR: Please ensure that common.tcl is sourced." + quit +} + +# A procedure that provides a wave-format-agnostic way to enable a scope (design heirarchy). +# +# In large designs, dumping waves on the entire hierarchy can significantly slow down the +# simulation. It is useful in that case to only dump the relevant scopes of interest during debug. +# +# waves : The wave-format (fsdb, shm, vpd, vcd, evcd, etc). +# simulator : The simulator used for running the simulation (vcs, xcelium, etc). +# scope : Design / testbench hierarchy to dump waves. Defaults to $tb_top. +# depth : Levels in the hierarchy to dump waves. Defaults to 0 (dump all levels). +# fsdb_flags : Additional string flags passed to fsdbDumpVars. Defaults to "+all", which enables +# dumping of memories, MDAs, structs, unions, power, packed structs, and SVAs. +# probe_flags : Additional string flags passed to probe command (Xcelium). Defaults to "-all". +# dump_flags : Additional string flags passed to dump command (VCS). Defaults to "-aggregates", +# which enables dumping of structs and arrays. +# +# Depending on the need, more such technology specific flags can be added in future. +proc wavedumpScope {waves simulator scope {depth 0} {fsdb_flags "+all"} {probe_flags "-all"} + {dump_flags "-aggregates"}} { + + switch $waves { + "none" { + return + } + + "fsdb" { + if {$simulator eq "xcelium"} { + call fsdbDumpvars $depth $scope $fsdb_flags + call fsdbDumpSVA $depth $scope + } else { + fsdbDumpvars $depth $scope $fsdb_flags + fsdbDumpSVA $depth $scope + } + } + + "shm" { + if {$depth == 0} { + set depth "all" + } + probe "$scope" $probe_flags -depth $depth -memories -shm + } + + "vpd" { + global vpd_fid + dump -add "$scope" -fid $vpd_fid -depth $depth $dump_flags + } + + "vcd" { + if {$simulator eq "xcelium"} { + if {$depth == 0} { + set depth "all" + } + probe "$scope" $probe_flags -depth $depth -memories -vcd + } + } + + "evcd" { + if {$simulator eq "xcelium"} { + if {$depth == 0} { + set depth "all" + } + probe "$scope" $probe_flags -depth $depth -evcd + } + } + + default { + puts "ERROR: Unknown wave format: ${waves}." + quit + } + } + + puts "INFO: Dumping waves in scope \"$scope:$depth\"." +} + +# A global variable representing the file id (fid) of the waves dumped in VPD format. +setDefault vpd_fid 0 + +# The entry point to enable dumping waves. +# +# If waves are not enabled (i.e. $waves == "none"), we do nothing. If enabled, then first, we run +# the tcl command to establish the dump file. Then, we run `wavedumpScope args...` to enable dumping +# the required hierarchies. +global waves +global simulator +if {$waves ne "none"} { + set wavedump_db "waves.$waves" + puts "INFO: Dumping waves in [string toupper $waves] format to $wavedump_db." + + # If waves are enabled, then issue the necessary tcl commands to enable the generation of waves. + # To explicitly list the hierarchies to dump, use the wavedumpScope proc instead. + switch $waves { + "fsdb" { + if {$simulator eq "xcelium"} { + call fsdbDumpfile $wavedump_db + } else { + fsdbDumpfile $wavedump_db + } + } + + "shm" { + checkEq simulator "xcelium" + database -open $wavedump_db -default -shm + } + + "vpd" { + checkEq simulator "vcs" + global vpd_fid + set vpd_fid [dump -file $wavedump_db -type VPD] + } + + "vcd" { + if {$simulator eq "xcelium"} { + database -open $wavedump_db -default -vcd + } else { + puts "ERROR: Simulator $simulator does not support dumping waves in VCD." + quit + } + } + + "evcd" { + if {$simulator eq "xcelium"} { + database -open $wavedump_db -default -evcd + } else { + puts "ERROR: Simulator $simulator does not support dumping waves in EVCD." + quit + } + } + + default { + puts "ERROR: Unknown wave format: ${waves}." + quit + } + } + + # Decide whether to dump the entire testbench hierarchy by default. + # + # If this variable is not set externally, it is set to 1 by default here. When set to 1, it adds + # the entire top-level testbench instance for dumping waves. For larger designs, this may slow + # down the simulation. The user can if needed, set it to 0 in the external tcl script that sources + # this script and manually add the hierarchies of interest in there, using the wavedumpScope proc. + # See the adjoining sim.tcl for an example. + setDefault dump_tb_top 1 + + if {$dump_tb_top == 1} { + global tb_top + wavedumpScope $waves $simulator $tb_top 0 + } else { + puts "INFO: the hierarchies to be dumped are expected to be indicated externally." + } +} diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/common.ccf b/hw/vendor/lowrisc_ip/dv/tools/xcelium/common.ccf new file mode 100644 index 0000000..f0e6b3a --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/common.ccf @@ -0,0 +1,56 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Common coverage commands that apply to all DUTs. +// +// This coverge config file is provided by Xcelium and is located at: +// ${XCELIUM_HOME}/tools/icc/include/all_coverage.ccf +// Xcelium recommends including it, since it bundles together the common set of commands that enable +// coverage collection on various design elements, that are otherwise turned off by default. We +// maintain it locally with minor amends. + +// Enables expression coverage of various Verilog operators. +set_expr_coverable_operators -all -event_or + +// Enables expression coverage of operators in various conditions and assignments. +set_expr_coverable_statements -procassign -event_control -misc + +// Enables scoring of Verilog modules compiled with -v/-y or -libcell option but continues to +// disable the scoring of Verilog modules defined with the 'celldefine compiler directive. +set_libcell_scoring + +// Enables scoring of SystemVerilog continuous assignments, which is by disabled by default. +set_assign_scoring + +// Scores branches together with block coverage. +set_branch_scoring + +// Scores statements within a block. +set_statement_scoring + +// Enables Toggle scoring and reporting of SystemVerilog enumerations and multidimensional static +// arrays , vectors, packed union, modport and generate blocks. +set_toggle_scoring -sv_enum enable_mda -sv_struct_with_enum -sv_modport -sv_mda 16 -sv_mda_of_struct -sv_generate -sv_packed_union + +// Enable toggle coverage only on ports. +set_toggle_portsonly + +// Enable scoring of FSM arcs (state transitions). +// TODO: re-enable this setting, temp disable due to #12544 +// set_fsm_arc_scoring + +// Include X->1|0 for toggle coverage collection. #10332 +set_toggle_includex + +// For ternary operator in default SOP mode +set_expr_scoring -vlog_short_circuit + +// Enable Constant Object Marking (COM) so that coverage items which can never be exercised because +// they are driven by constants inside the DUT are automatically detected during elaboration, marked +// IGN, and omitted from the coverage figures. It prevents statically-tied inputs (e.g. reinit +// inputs on generated register blocks that are tied to zero at integration) from showing up as +// false coverage holes. When the testbench is built, we pass -covdut, which ensures genuine DUT ports +// are considered variable. This avoids any inferred constant variables from undriven ports. +// `-log` writes the list of marked items to `icc.com` for auditing. +set_com -on -log diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/common_cov_excl.tcl b/hw/vendor/lowrisc_ip/dv/tools/xcelium/common_cov_excl.tcl new file mode 100644 index 0000000..f38f26e --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/common_cov_excl.tcl @@ -0,0 +1,10 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +exclude -inst $::env(DUT_TOP) -toggle '*tl_i.a_user.rsvd' -comment "\[UNSUPPORTED\] Based on our Comportability Spec. Exercising this will result in assertion errors thrown." +exclude -inst $::env(DUT_TOP) -toggle '*tl_i.a_param' -comment "\[UNSUPPORTED\] Based on our Comportability Spec. Exercising this will result in assertion errors thrown." +exclude -inst $::env(DUT_TOP) -toggle '*tl_o.d_param' -comment "\[UNR\] Follows tl_i.a_param which is unsupported." +exclude -inst $::env(DUT_TOP) -toggle '*tl_o.d_sink' -comment "\[UNR\] Based on our Comportability Spec." +exclude -inst $::env(DUT_TOP) -toggle '*tl_o.d_user.rsp_intg'\[6\] -comment "\[UNR\] Due to the ECC logics" +exclude -inst $::env(DUT_TOP).gen_alert_tx*.u_prim_alert_sender -toggle '*alert*.ping_*' -comment "\[LOW_RISK\] Verified in prim_alert_receiver TB." diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_merge.tcl b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_merge.tcl new file mode 100644 index 0000000..7c4291c --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_merge.tcl @@ -0,0 +1,26 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +# Merge coverage with IMC, across tests, scopes and previous regression runs. + +# Set the input coverage directories across all available scopes and previous runs, +# using the env var 'cov_db_dirs' (which is a space separated list of directories). +# Append each of these directories with /* wildcard at the end to allow the tool to +# find all available test databases. +set cov_db_dirs_env [string trim $::env(cov_db_dirs) " \"'"] +foreach i $cov_db_dirs_env { append cov_db_dirs "[string trim $i]/* "; } +puts "Input coverage directories:\n$cov_db_dirs" + +# Set the output directory for the merged database using the env var 'cov_merge_db_dir'. +# The supplied env var may have quotes or spaces that needs to be trimmed. +puts "Output directory for merged coverage:" +set cov_merge_db_dir [string trim $::env(cov_merge_db_dir) " \"'"] + +# Run the merge command. +merge $cov_db_dirs -out $cov_merge_db_dir -overwrite -initial_model union_all + +# Create a file with the path to the cover dirs +# Replace spaces with newlines so each run is on its own line for the 'rank' command +set cov_db_dirs_rank [string map {" " "\n"} [string trim $cov_db_dirs]] +exec sh -c "cat << 'EOF' > $cov_merge_db_dir/runs.txt\n$cov_db_dirs_rank\nEOF" diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_report.tcl b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_report.tcl new file mode 100644 index 0000000..1585b6f --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cov_report.tcl @@ -0,0 +1,75 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 + +# Generate reports for the merged coverage in HTML and text format. +# +# This file is passed to IMC using the -exec switch. Ensure that the merged coverage database, the +# exclusion script and the coverage refinement files are passed to the IMC invocation using the +# -load, -init and -load_refinement switches respectively (whichever ones are applicable). + +# Generate "detachable" reports that work despite browser Cross-Origin Request Security protection. +# They have the downside that you have to select the .report file yourself in-browser. +config reports.detachable_report_data -set true + +# Set the output directory for the reports database using the env var 'cov_report_dir'. +# The supplied env var may have quotes or spaces that needs to be trimmed. +set cov_report_dir [string trim $::env(cov_report_dir) " \"'"] + +# Set the input merged coverage database directory using the env var 'cov_merge_db_dir'. +# The supplied env var may have quotes or spaces that needs to be trimmed. +set cov_merge_db_dir [string trim $::env(cov_merge_db_dir) " \"'"] + +# Set the DUT name. +set dut [string trim $::env(DUT_TOP)] +set dut_uc [string toupper $dut] + +# Generate the text report (summary is sufficient). +report -summary \ + -inst uvm_pkg $dut \ + -metrics all \ + -all \ + -cumulative on \ + -local off \ + -grading covered \ + -out $cov_report_dir/cov_report.txt + +# Generate a detailed exclusion report +# +# This is the only place the attribution appears. The HTML report below passes -exclComments as +# well, but the exported report_data carries the rule kind and nothing else, so the report here is +# what makes the attribution available. The comment is what tells a UNR exclusion apart from a hand +# written one, since IMC records both as ordinary refinement rules. +# This information is useful to better understand what the tool or the user has excluded and the +# reasons. +report -detail \ + -inst $dut \ + -metrics all \ + -excludes \ + -exclComments \ + -out $cov_report_dir/cov_excl_report.txt + +# Generate the functional coverage report for tracking. +report -summary \ + -type \ + -all \ + -metrics covergroup \ + -source off \ + -out $cov_report_dir/cov_report_cg.txt + +# Generate the HTML reports. +report_metrics \ + -out $cov_report_dir \ + -overwrite \ + -title $dut_uc \ + -detail \ + -metrics all \ + -kind aggregate \ + -source on \ + -exclComments \ + -assertionStatus \ + -allAssertionCounters \ + -all + +# rank the test runs +rank -runfile $cov_merge_db_dir/runs.txt -html -out_html $cov_report_dir/grading -overwrite diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/cover.ccf b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cover.ccf new file mode 100644 index 0000000..3964c64 --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/cover.ccf @@ -0,0 +1,53 @@ +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// Include our common coverage CCF. +include_ccf ${dv_root}/tools/xcelium/common.ccf + +// enable coverage on dut and below + +select_coverage -befts -module ${DUT_TOP}... + +// Black-box pre-verified IPs from coverage collection. +deselect_coverage -betfs -module pins_if +deselect_coverage -betfs -module clk_rst_if +deselect_coverage -betfs -module prim_alert_sender... +deselect_coverage -betfs -module prim_alert_receiver... +deselect_coverage -betfs -module prim_count... +deselect_coverage -betfs -module prim_esc_sender... +deselect_coverage -betfs -module prim_esc_receiver... +deselect_coverage -betfs -module prim_onehot_check... +deselect_coverage -betfs -module prim_prince... +deselect_coverage -betfs -module prim_lfsr... +deselect_coverage -betfs -module prim_secded_inv_64_57_dec... +deselect_coverage -betfs -module prim_secded_inv_39_32_dec... +deselect_coverage -betfs -module prim_secded_inv_64_57_enc... +deselect_coverage -betfs -module prim_secded_inv_39_32_enc... + +// Black-box DV CDC module. +deselect_coverage -betfs -module prim_cdc_rand_delay + +// csr_assert_fpv is an auto-generated csr read assertion module. So only assertion coverage is +// meaningful to collect. +deselect_coverage -betf -module *csr_assert_fpv... +select_coverage -assert -module *csr_assert_fpv + +// Only enable assertion coverage +deselect_coverage -betf -module *tlul_assert... +select_coverage -assert -module *tlul_assert + +// Only collect toggle coverage on the DUT and the black-boxed IP (above) ports. +deselect_coverage -toggle -module ${DUT_TOP}... +select_coverage -toggle -module ${DUT_TOP} + +select_coverage -toggle -module prim_alert_sender +select_coverage -toggle -module prim_alert_receiver +select_coverage -toggle -module prim_count +select_coverage -toggle -module prim_esc_sender +select_coverage -toggle -module prim_esc_receiver +select_coverage -toggle -module prim_onehot_check +select_coverage -toggle -module prim_prince +select_coverage -toggle -module prim_lfsr +select_coverage -toggle -module prim_secded_inv_64_57_dec +select_coverage -toggle -module prim_secded_inv_39_32_dec diff --git a/hw/vendor/lowrisc_ip/dv/tools/xcelium/unr.cfg b/hw/vendor/lowrisc_ip/dv/tools/xcelium/unr.cfg new file mode 100644 index 0000000..7918eff --- /dev/null +++ b/hw/vendor/lowrisc_ip/dv/tools/xcelium/unr.cfg @@ -0,0 +1,15 @@ +# Copyright lowRISC contributors (OpenTitan project). +# Licensed under the Apache License, Version 2.0, see LICENSE for details. +# SPDX-License-Identifier: Apache-2.0 +check_unr -setup + +#Setup the clock and reset the design +clock -infer +reset ~dut.rst_ni +get_reset_info + +set_prove_time_limit 5m +check_unr -prove +check_unr -list -type unreachable +database -export_unicov +report -detailed