Search is not available for this dataset
| content
				 stringlengths 0 376M | 
|---|
| 
	[//]: # (Copyright 2021 Massachusetts Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
# CEP Changelog
## [v4.20] - 2022-08-03
### Added
* Added kgetc to bare metal console routines
* Verified firemarshal generated linux build boots on the Arty100T, VC707, and VCU118.  Instructions added to [README.md](./README.md)
* Added `helloworld` and `gpiotest` to ./software/linux.  Makefiles allow application's install to firemarshal's buildroot.
* Added VC707 CEP FPGA target thanks to the folks at NECSTLab (https://github.com/necst)
* Added VCU118 CEP FPGA target
### Changed
* Unified console print routines across bootroms, cosim baremetal, and standalone bare metal code.  Bare metal prints are now handled using stdio functions with
  putchar, getchar, and putstr being mapped to the console versions
### Known issues
* cep_cosim
  * Cadence XCellium on RHEL7 *occasionally* fails some of the bareMetal tests.  Root cause has not been determined, but it is recommended that the test be re-run.
  * Known est failures: 
    * ./testSuites/bfmTests/macroMix - GPS Test - First core passes, subsequent cores fail.
    * Virtual mode ISA tests - Failure on Questsim/Ubuntu, passes on XCellium/RHEL7
    * ./testSuites/isaTests/rv64mi-p-csr
    * ./testSuites/isaTests/rv64si-p-csr
    * ./testSuites/bfmTests/srotErrorTest
    * ./testSuites/bareMetalTests/plicPrioIntr
    * ./testSuites/bareMetalTests/extIntr
    * ./testSuites/bareMetalTests/lsrcOps
    * ./testSuites/isaTests/dtmTest
## [v4.10] - 2022-07-01
### Added
* Added a bareMetal/aesMacro test for running on the Arty100T build, which currently only has one AES core and the SRoT
### Changed
* Unified/debugged console printf functionality when building bare metal executables.  By default, it is disabled, but can be enabled with the ENABLE_KPRINTF directive
* Arty100T and cep_sim use the same 'sd.c' source file, but leverage different makefiles.
* Misc. code and readme cleanup
* Bumped Chipyard to 1.7.0 from 1.5.0.  See [CHANGELOG](./CHANGELOG.md).
* Rocket-Chip bumped to v1.5
### Fixed
* iDFT test code fixed in cep_idft.cc
## [v4.00] - 2022-06-21
### Added
* Chipyard Arty100t branch merged in (Commit 4440db0, March 4, 2022)
### Changed
* CHANGELOG.CEP.md updated based on guidance from *keep a changelog* (https://keepachangelog.com/en/1.0.0/)
* CEP has been completely ported to the UCB Chipyard Framework (https://github.com/ucb-bar/chipyard)
* Arty-A7 100T FPGA target running bare-metal code is currently supported (Linux is not currently supported)
## v3.41 - (10 September 2021)
* CEP Configuration nows includes 4xGPS and 4xSHA-256 cores
* Integrated configurable co-simulation environment (provide a co-sim that can more easily adapt to CEP architecture changes)
* Known Issues:
  - Some idft test vectors fail under QuestaSim (xcellium regression ran successfully)
  - Multithreaded test (#23) non-functional under linux
##v3.4 - (6 August 2021)
* Added external interrupt test (extIntr)
* Added test to boot rom to verify code execution out of scratchpad is working
* Added cryptoMask to cep_srot to support individual key loading only if enable
* Restructured cosim Makefiles to support re-use from other repos
* Modified cadence Makefile to enable partial toggle scoring
* Changed un-initialized main memory default state (from 0 -> 1) to improve coverage
* Addressed an LLKI bug in which the LLKI-PP component would send a respond to the SRoT before llkid_key_complete is asserted by the mock_tss_fsm
* Fixed GPS port directions in verilog
* Scratchpad RAM changed to blackbox implementation to facilitate ASIC development
* OpenSSL replaced by Cryptopp for crypto-related tests (cosim + linux)
##v3.3 - (19 May 2021)
* Increased capacity for LLKI key size including larger KeyRAM (2048 64-bit words)
* Added Cosim JTAG/OpenOCD 
* Stability fixes for cep_diag under Linux 
* Virtual Address TLB test suite is added to regression (not 100% complete)
* Expanded cep_diag
* New simulation ONLY interrupt tests for CLINT and PLIC modules (on going)
* Re-capture vectors for unit sim due to changes in LLKI key size
* Bootrom size is increased to 32K bytes (8kx32) to accomodate new built-in test (execute codes out of bootrom without main memory)
##v3.2 - (16 April 2021)
* LLKI bug fixes 
* Scratchpad RAM added
* Cadenece xcelium simulator and coverage support added
* Linux tests updated and expanded
* New tests added to cosim focused on LLKI and Scratchpad RAM
##v3.11 - (29 March 2021)
* Unit Simulations updated for full LLKI support
* GPS core bugfix to provide specification compliance and increase functional coverage
* SRoT tests added
* SRoT has been updated to use a single port (1RW) RAM.
* Misc. bug fixes and README cleanup
* Known Issues:
  - cep_diag (on Linux) has NOT been updated to work with the LLKI.  Thus, running the tests that use
    the CEP cores (e.g., cep_aes, cep_des3, etc.) will result in failure
##v3.1 - (22 February 2021) 
* Full LLKI support (All CEP cores are now LLKI enabled)
* Known Issues:
  - cep_diag (on Linux) has NOT been updated to work with the LLKI.  Thus, running the tests that use
    the CEP cores (e.g., cep_aes, cep_des3, etc.) will result in failure
  - rv64si-p-dirty ISA test fails
  - unit_simulations need to be updated to be compatible with the LLKI
##v3.01 - (19 December 2020)
* Removed used flash model reference in cep_tb.v
##v3.0 - (18 December 2020)
* Initial LLKI release with Surrogate Root of Trust
* AES core replaced with LLKI-enabled AES core, all other cores remain unchanged
##v2.71 - (2 November 2020)
* Corrected README.md issue
##v2.7 - (28 October 2020)
* Added support for RISC-V ISA tests (under ./cosim/isaTests)
* Updated license statements to BSD-2-Clause
* KNOWN ISSUES:
  - The iCacheCoherency passes when running bare-metal simulation, but fails when running on the VC-707.  There is an issue with
    the iCache protocol that the tight-looped iCache coherency test results in one or more of the Rocket Cores (there are 4 in 
    the CEP) L1 iCache not getting the value associated with the most recent write to instruction memory.
    Functionally, this should only cause an issue when dealing with self-modifying code, which is an atypical coding practice.
  - The following cosim tests fail when run under RHEL using the "new" RISC-V toolchain:
    - bareMetalTests/cacheCoherence
    - isaTests/rv64mi-p-access 
    - isaTests/rv64ud-p-ldst
##v2.61 - (2 October 2020)
  - Added initial simulation support for Cadence XCellium
  - Cosim: Expanded DDR3 memory size to support "larger" bare-metal executables created by the new RISCV toolchain released with v2.6
##v2.6 - (18 September 2020)
* Rocket-Chip and Freedom repositories updated.  Source responsitory list:
    https://github.com/sifive/freedom/tree/8622a684e7e54d0a20df90659285b9c587772629              - Aug 19, 2020
    https://github.com/chipsalliance/rocket-chip/tree/d2210f9545903fad40c9860389cdcf9c28515dba   - Apr  2, 2020
    https://github.com/sifive/fpga-shells/tree/19d0818deda5d295154992bd4e2c490b7c905df9          - Jan 28, 2020
    https://github.com/sifive/sifive-blocks/tree/12bdbe50636b6c57c8dc997e483787fdb5ee540b        - Dec 17, 2019
    https://github.com/mcd500/freedom-u-sdk/tree/29fe529f8dd8e1974fe1743184b3e13ebb2a21dc        - Apr 12, 2019
* riscv-tools (formerly under rocket-chip) now located in ./software/riscv-gnu-toolchain
* KNOWN ISSUES:
    - The iCacheCoherency passes when running bare-metal simulation, but fails when running on the VC-707.  There is an issue with
      the iCache protocol that the tight-looped iCache coherency test results in one or more of the Rocket Cores (there are 4 in 
      the CEP) L1 iCache not getting the value associated with the most recent write to instruction memory.
      Functionally, this should only cause an issue when dealing with self-modifying code, which is an atypical coding practice.
##v2.52 - (2 September 2020)
* Added ./doc/CEP_TestDescriptions.pdf
##v2.51 - (7 August 2020)
* Legacy unused core wrapper files (axi4lite and wb) removed
##v2.5 - (31 July 2020)
* All Unit-level testbenches have been expanded to optional support the Logic Locking Keying Interface (LLKI)
  for both cycle-level and transactional-level modes
##v2.4 - (5 June 2020)
* CEP core test coverage expanded
* Unit testbenches transactional-level support added
* AES-derived and FIR-derived generated cores added
* Misc. bug fixes
##v2.3 - (17 April 2020)
* Added unit-level testbenches for all CEP cores.  Co-simulation modified to generate unit-level test stimulus.  
##v2.2 - (31 January 2020)
* Added co-simulation environment that supports both Bus Functional Model (BFM) and Baremetal simulation modes.  Additional diagnostic capabilities within Linux.
##v2.1 - (31 October 2019)
* Integrated DES3, GPS, MD5, RSA, SHA256, DFT, IDFT, and IIR cores.
##v2.0 - (16 August 2019)
* Major Update: mor1k proceesor core replaced with the UCB Rocket-Chip within the SiFive Freedom U500 Platform.  All modules have been updated to support TileLink natively.  Currently only the AES and FIR cores have been integrated, but v2.1 will include the re-release of all the CEP cores.   
##v1.2 - (15 November 2018)
* Major Update: The underlying bus has been converted from Wishbone-B4 to AXI4-Lite.  All cores as well as the MOR1KX has been wrapped with translation modules.  All the wrapping logic and interconnect are now in SystemVerilog.
* Regression Suite: In additon to each core's unit tests, a regression test suite has been included.  When compiled by the or1k toolchain, it be loaded/synthesized into the CEP RAM block and run at boot time.
* Modelsim Testing: Unit-level and system-level modelsim-based testbenches added
* GPS clkgen: The GPS clock gen component has been moved to the top level of the CEP, simplifying its replacement when targetting an ASIC.
* Misc. bug fixes
##v1.1.1 - (27 September 2018)
* Added CEP\_utilization\_placed.rpt in implSummaries directory.  This summarizes utlization of the CEP v1.1 targetted to the VC707 using Vivado 2018.1.
##v1.1 - (19 July 2018)
* Directory structure has been reorganized (details below)
* Upgraded to the non-deprecated mor1kx (added as a subnodule)
* Verified with both the pre-built and build-your-own version of the Newlib toolchain as described on [http://openrisc.io](http://openrisc.io)
* In addition to test vectors for each of the cores, some additional test_software, such as "hello world", have been added for reference
* Expanded testbench (details below)
* Bug fixes and general code cleanup [Additional details in the git commit history]
##v1.0 - Initial release (15 Aug 2017)
#### Return to the root CEP [README](./README.md) | 
| 
	# Changelog
This changelog follows the format defined here: https://keepachangelog.com/en/1.0.0/
## [1.7.0] - 2022-06-18
FireSim bump for local (on-premises) FPGA and distributed metasimulation support. Hammer now supports the OpenROAD open-source EDA tools for a fully open-source RTL-to-GDS VLSI flow.
### Added
* Add a FireSim config with no mem port (#1172)
* Hammer OpenROAD plugins: Yosys (syn), OpenROAD (par), Magic (drc), Netgen (lvs) (#1183)
### Changed
* Bump FireSim to 1.14.0
* Give the PRCI widgets valnames to clean up module naming (#1152)
### Fixed
* Add missing Apache commons dependencies (fixes #1144) (#1147)
* Disable Boost for spike (#1168)
* VCS enhancements (#1150)
    * Support multi-thread VCS simv option like FGP, Xprof etc.
    * Idle tsi in the target thread
* Don't shallow clone submodules (revert #1064) (#1143)
* Remove extra spaces in FPGA makefile (#1135)
## [1.6.3] - 2022-04-06
FireSim bump for various fixes. Revert shallow cloning. Various CI fixes.
### Fixed
* Bump to FireSim 1.13.4 (changelog: https://github.com/firesim/firesim/blob/1.13.4/CHANGELOG.md#1134---2022-04-06)
* Revert shallow cloning.
* Various CI fixes.
## [1.6.2] - 2022-03-01
Minor fixes to FireSim.
### Fixed
* Bump to FireSim 1.13.3 (#1134)
## [1.6.1] - 2022-03-01
Minor fixes to FireSim.
### Fixed
* Bump to FireSim 1.13.2 (#1133)
## [1.6.0] - 2022-02-15
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/913
### Added
* Diplomatic IOBinder-like approach to setting up PRCI across different deployment targets (#900)
* Default set of MMIO-controlled reset-setters and clock-gaters (#900)
* Added simulation makefile options `torture` and `torture-overnight` for running Torture (#992)
* FSDB waveform support (#1072, #1102)
* Use GitHub Actions for CI (#1004, #999, #1090, #1092)
* Add MAKE variable in `build-toolchains.sh` (#1021)
* Cleanup GH issue and PR templates (#1029, #1032)
* Add support for Ibex core (#979)
* Add system bus width fragment (#1071)
* Add support for FSDB waveform files (#1072, #1102)
* Document simulator timeout settings (#1094)
* Add FFT Generator (#1067)
* Add waveforms for post-PNR and power (#1108)
* Have PRCI control registers use clock of corresponding bus (#1109)
* Add check to verify that user is running on tagged release (#1114)
* Hammer tutorial in Sky130 (#1115)
### Changed
* Bump CVA6 (#909 )
* Bump Hammer tutorial for ASAP7 r1p7 (#934)
* Use Published Chisel, FIRRTL, Treadle, FIRRTLInterpreter packages instead of building from source. #1054
* Change serialTL width to 32. Speeds up simulations (#1040)
* Update how sbt flag is overridden (by using `SBT_BIN` variable) (#1041)
* Use published dependencies for Chisel, FIRRTL, Treadle, and FIRRTLInterpreter (#1054)
* Split `ConfigFragments.scala` into multiple files (with more organization) (#1061)
* Avoid initializing nvdla software by default (#1063)
* Update ASAP to 1.7 in Hammer (#934)
* Shorten Gemmini docs and point to repo (#1078)
* Bump Gemmini to 0.6.2 (#1083)
* Use python2 for tracegen script (#1107)
* Bump to Chisel/FIRRTL 3.5.1 (#1060, #1113)
* Bump to FireMarshal 1.12.1 (#1116)
* Bump to FireSim 1.13.0 (#1118 )
### Fixed
* Fix UART portmap for Arty (#968)
* Support changing make variable `MODEL` from the cmdline (#1030)
* Force FIRRTL to 1.4.1 (#1052)
* Fix MMIO IOBinder (#1045)
* Mask `fd` warning when running make (#1057)
* Fix Sodor 5-stage hazard check (#1086)
* Fix Sodor val io issue (#1089)
* Fix BOOM reference in Readme (#1104)
* Fix waveforms for post-P&R power analysis (#1108)
### Removed
* Remove duplicate `WithUARTIOCells` fragment (#1047)
* Remove MaxPermSize in java variables (#1082)
* Remove support for CircleCI (#1105)
## [1.5.0] - 2021-06-13
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/773
### Added
* FireMarshal support for FPGA prototypes (#849)
* Hammer update to include power estimation flows, rail analysis, hierarchical sim support, and improved ASAP7 plugin with dummy SRAMs (#886)
* Docker image
* Support specifying architecture when building tools. (#802)
* Add Config fragments: WithMultiRoCCFromBuildRoCC, PMP (#809, #821)
* Add support for simulating an AXI memory interface over the default TL serial link (#812)
* Add option to add async queues between chip-serialIO and harness serdes (#828)
* Spike support for multiple extensions, and add sha3 spike model to esp-tools (#837, #897)
* Default generator support for I2C and PWM (#885)
### Changed
* Gemmini bump to version 0.5
* FireSim bump to version 1.12
* FireMarshal bump to version 1.12
* Changes default FireSim frequency from 3.2 GHz (dual clock domains) to 1 GHz (single clock domain)
* Bump pygments from 2.2.0 to 2.7.4 in docs
* Hammer tutorial example is now a TinyRocketConfig (#886)
* Sha3 Spike model moved from sha3 repo to esp-isa-sim
### Fixed
* Avoid permissions conflict on shared protocjar.webcache (#774)
* Passing MBus clock frequency to SimDRAM (#790)
* Fix parsing of --ignore-qemu option (#791)
* FPGA Prototype - Support Adding Pullup R's to Bringup GPIOs (#806)
* Use "tile" instead of "core" to assign frequencies in WithTileFrequency config. fragment (#807)
* Fix IOCell generation for clock and reset to use IOCellKey (#824)
* Fix TileResetCtrl to be ahead of reset synchronizers (#826)
* Fix memory alignment in character count RoCC test (#853)
* Synchronize JTAG reset to JTAG.TCK. (#859)
* Updates to system requirements scripts (#874)
* Rocket-dsp-utils integration and cleanup for dsptools (#888)
### Removed
* Dummy DCO collateral from Hammer tutorial example (#886)
## [1.4.0] - 2021-01-19
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/599
### Added
* OpenSBI Support (#633)
* Support for Diplomacy-based clocking (#614, #682)
* Support for Diplomacy-based IOBinders (#699)
* Sodor core integration (#648)
* Simple Divider-Only PLL for Multiclock RTL Simulation (#676)
* Enable parallel Hammer simulations (#600)
* OpenRoad nangate45 Hammer backend (#608)
* Add support for "LBWIF" backing memory through serialized TileLink (#673)
* Add variable to control FIRRTL logging verbosity (#627)
* Add RANDOM_SEED variable to set random init for VCS and Verilator simulations (#629)
* Fast LoadMem support (#635)
* Multithreaded Verilator (#654)
* Support for custom Verilator optimization flags (#728)
* Add config-fragment to use broadcast manager instead of L2 for coherence (#721)
* Added optional ignore QEMU flag to `build-toolchains.sh` (#709)
* Split `JAVA_ARGS` into `JAVA_OPTS` and `SBT_OPTS` (#719)
* Experimental support for SBT thin client. Enable with `export ENABLE_SBT_THIN_CLIENT=1` (https://github.com/sbt/sbt/pull/5620) (#719)
* Helper `make` targets to launch SBT console (`sbt`) and shutdown/start thin server (<start/shutdown>-sbt-server) (#719)
* Allow users to override `CC` and `CXX` for `build-toolchains.sh` (#739)
* Support VCU118/Arty local FPGA prototypes through `fpga-shells` (#747)
* A 16-core LargeBOOM configuration has been added to FireChip to highlight the resource-optimizing platform configurations added to FireSim in firesim/firesim#636 (#756)
### Changed
* Bump Chisel to 3.4.1.x (#742, #719, #751)
* Bump RocketChip to a7b016e (#742, #719)
* Bump FireSim to 1.11
* Bump Gemmini to v0.5
* Bump to SBT 1.4.4 (#719)
* Split IOBinders into IOBinders and HarnessBinders | punch out clocks to harness for simwidgets and bridges (#670, #674)
* Have FireSim build recipes use Chipyard configs rather than FireChip configs (#695)
* FireMarshal boot default to OpenSBI rather than BBL (#633)
* Override default baud rate for FireChip (#625)
* DTM only supports HTIF in DMI mode (#672)
* Unify HTIF implementation between Chipyard and Firesim (#683)
* Renamed Ariane to CVA6 (#710)
* `build.sbt` refactoring/fixes for RC/Chisel/Firrtl bump (#719)
* Use `; x; y; z;` syntax to run multiple SBT commands (#719)
* CI Improvements: Cleanup `check-commit` printout. Don't transfer `.git` folders. (#750)
### Fixed
* Multi-SHA3 configs (#597)
* Allow dramsim_ini folder to be set at the command line (#598)
* Emit HTIF Node in device tree (#607)
* Fixes for AXI4 MMIO and FBus ports (#618)
* Only punch realistic subset of DebugIO through chiptop | default to JTAG+Serial (#664)
* IceNet bug fixes (#720)
* smartelf2hex.sh bug fixes (#677, #693)
* env.sh zsh compatibility (#705)
* build-toolchains.sh bug fixes (#745 #739)
* Bump Dromajo to work with older version of glibc (#709)
### Removed
* Support for synchronous ChipTop reset (#703)
* Split `JAVA_ARGS` into `JAVA_OPTS` and `SBT_OPTS` (#719)
## [1.3.0] - 2020-05-31
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/500
### Added
* A new Top-level module, ChipTop, has been created. ChipTop instantiates a "system" module specified by BuildSystem. (#480)
* A new BuildSystem key has been added, which by default builds DigitalTop (#480)
* The IOBinders API has changed. IOBinders are now called inside of ChipTop and return a tuple3 of (IO ports, IO cells, harness functions). The harness functions are now called inside the TestHarness (this is analogous to the previous IOBinder functions). (#480)
* IO cell models have been included in ChipTop. These can be replaced with real IO cells for tapeout, or used as-is for simulation. (#480)
* CI now checks documentation changes (#485)
* Support FireSim multi-clock (#468)
* Allows make variables to be injected into build system (#499)
* Various documentation/comment updates (#511,#517,#518,#537,#533,#542,#570,#569)
* DSPTools documentation and example (#457, #568)
* Support for no UART configs (#536)
* Assemble firrtl-test.jar (#551)
* Add SPI flash configurations (#546)
* Add Dromajo + FireSim Dromajo simulation support (#523, #553, #560)
* NVDLA integration (#505, #559, #580)
* Add support for Hammer Sim (#512,#581,#580,#582)
### Changed
* Bump FireSim to version 1.10 (#574,#586)
* Bump BOOM to version 3.0 (#523, #574,#580)
* Bump Gemmini to version 0.3 (#575, #579)
* Bump SPEC17 workload (#504, #574)
* Bump Hwacha for fixes (#580)
* Bump SHA3 for Linux 5.7rc3 support (#580)
* Bump Rocket Chip to commit 1872f5d (including stage/phase compilation) (#503,#544)
* Bump FireMarshal to version 1.9.0 (#574)
* Chisel 3.3 and FIRRTL 1.3 (#503,#544)
* BuildTop now builds a ChipTop dut module in the TestHarness by default (#480)
* The default for the TOP make variable is now ChipTop (was Top) (#480)
* Top has been renamed to DigitalTop (#480)
* Bump libgloss (#508, #516, #580)
* The default version of Verilator has changed to v4.034 (#547). Since this release adds enhanced support for Verilog timescales, the build detects if Verilator v4.034 or newer is visible in the build environment and sets default timescale flags appropriately.
* Use Scalatests for FireSim CI (#528)
* Cleanup Ariane pre-processing (#505)
* Modify Issue Template to be more explicit (#557)
* FireChip uses Chipyard generator (#554)
* Have all non-synthesizeable constructs in test harness (#572)
### Fixed
* Aligned esp-tools spike with Gemmini (#509)
* Fix debug rule in Verilator (#513)
* Clean up SBT HTTP warnings (#526,#549)
* Artefacts dropped in FireSim (#534)
* Working IceNet + TestChipIP Unit Tests (#525)
* Don't initialize non-existent Midas submodule (#552)
* Verilator now supports +permissive similar to VCS (#565)
* Fix direction of IOCell OE (#586)
### Deprecated
* N/A
### Removed
* Removed MIDAS examples CI (until a better solution that is faster is found) (#589)
## [1.2.0] - 2020-03-14
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/418
### Added
* Ring Topology System Bus NoC (#461)
* Integration of the Ariane core into Chipyard (#448)
* FireMarshal now generates an extra copy of linux kernel with dwarf debugging info for use in FirePerf (#427)
* Add option to use blackboxed SimDRAM instead of SimAXIMem (#449)
* Log `init-submodules` script (#433)
* Moved the Docker image used for CI into Chipyard (prev. in BOOM) (#463)
### Changed
* Bump FireSim to 1.9.0 - Includes FirePerf TracerV Flame Graph features
* IOBinders and BuildTop unification between FireChip and Chipyard (#390)
* Bump BOOM to version 2.2.4 (#463)
* Bump Gemmini to version 0.2 (#469)
* Update to CircleCI 2.1 config. syntax and cleanup CI file (#421)
* FireMarshal moved from FireSim to Chipyard (#415)
* Rename config. mixins to config fragments (#451)
### Fixed
* `git status` should be clean. (Although you will need to manually cleanup the libgloss and qemu directories after first setup). (#411, #414)
* Fix Hetero. BOOM + Rocket + Hwacha config (#413)
* Fix VCS stdout (#417)
* Add a git version check to the init scripts and make them work outside of the repo root (#459)
* Fix generation of env.sh for zsh (#435)
* GCD example bug (#465)
### Deprecated
* N/A
### Removed
* N/A
## [1.1.0] - 2020-01-25
A more detailed account of everything included is included in the dev to master PR for this release: https://github.com/ucb-bar/chipyard/pull/367
### Added
* Gemmini generator and config (PR #356 )
* Coremark + SPEC2017 benchmarks (PR #326, #338, #344)
* Add Hwacha tests to CI (PR #284)
* Add Hwacha tests to benchmark and assembly test suites (PR #284)
* Added Hwacha + Large Boom Config (PR #315)
* Add multi-core config with a small Rocket core attached on the side (PR #361 )
* Add UART and Test Harness UART Adapter to all configurations (PR #348)
* User can specify $RISCV directory in build-toolchains.sh (PR #334)
* Checksum offload in IceNet (PR #364)
### Changed
* Rocketchip bumped to commit [4f0cdea](https://github.com/chipsalliance/rocket-chip/tree/4f0cdea85c8a2b849fd582ccc8497892001d06b0), for chisel version 3.2.0 which includes Async reset support
* FireSim release 1.8.0
* FireMarshal release 1.8.0
* BOOM release 2.2.3 (PR #397)
* baremetal software toolchains, using libgloss and newlib instead of in-house syscalls.
* Add toolchain specific `env.sh` (PR #304)
* `run-binary`-like interface now dumps `.log` (stdout) and `.out` (stderr) files (PR #308)
* Split the VLSI build dir on type of design (PR #331)
* Reduce Ctags runtime and only look at scala, C, C++, and Python files (PR #346)
* Top/Top-level-traits now behave as a configurable generator (PR #347)
* Test suite makefrag generator includes Hwacha test suites (PR #342)
### Fixed
* Fix VLSI makefile requirements for SRAM generation (PR #318)
* Only filter header files from common simulation files (PR #322)
* Bump MacroCompiler for bugfixes (PR #332)
* commit-on-master check has specific behavior based on source branch (PR #345)
* Makefile filtering of blackbox resource files only omits .h files (PR #322)
* Parallel make fixed (PR #386 #392)
### Deprecated
* No longer need to specify `WithXTop`, default `Top` is a generator for all `Top`s (PR #347)
### Removed
* N/A
## [1.0.0] - 2019-10-19
### Added
* This repository used to be "project-template", a template for Chisel-based projects. Through tighter integration of multiple projects from the Berkeley Architecture Research group at UC Berkeley, this repository is re-released as Chipyard - a framework for agile hardware development of RISC-V based Systems-on-Chip.
 | 
| 
	Contributing to Chipyard
=============================
### Branch management:
1) github:com/ucb-bar/chipyard: main = pre-release non-stable branch with latest features. All merges to main must go through PR.
2) github:com/ucb-bar/chipyard: specific tag / tagged branch = official chipyard release.
3) Other dependencies pointed at by Chipyard (e.g. firesim, boom): master/main should be the version submoduled in ucb-bar/chipyard main.
 | 
| 
	BSD 3-Clause License
Copyright (c) 2017-2020, The Regents of the University of California (Regents)
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 | 
| 
	Common Evaluation Platform Licensing Information
Title               : aes
Source              : https://opencores.org/project,tiny_aes
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/aes
License Description : Apache 2.0
License terms       : http://www.apache.org/licenses/LICENSE-2.0.html
Function            : This core provides a standard AES encryption function, where the key is 192 bits long.  It will be integrated as a HW accelerator into the SoC.
Title               : des3
Source              : http://asics.ws/v6/free-ip-cores/#
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/des3
License Description : BSD-based
License terms       :   Copyright (C) 2000-2009, ASICs World Services, LTD. , AUTHORS All rights reserved. Redistribution and use in source, netlist, 
                        binary and silicon forms, with or without modification, are permitted provided that the following conditions are met: 
                        Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
                        Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 
                        in the documentation and/or other materials provided with the distribution.
                        Neither the name of ASICS World Services, the Authors and/or the names of its contributors may be used to endorse or promote 
                        products derived from this software without specific prior written permission.
                        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
                        BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
                        SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
                        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
                        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
                        OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Function            :  This core provides a standard MD5 hash function.  It will be integrated as a HW accelerator into the SoC.
Title               : dsp (FIR and IIR filters)
Source              : Copyright (c) 2005-2014 Peter A. Milder for the Spiral Project, Carnegie Mellon University
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/dsp
License Description : BSD
License Terms       : http://www.opensource.org/licenses/bsd-license.php
Function            : Provides logic for the FIR and IIR
Title               : dsp (DFT) and IDFT)
Source              : Copyright (c) 2005-2014 Peter A. Milder for the Spiral Project, Carnegie Mellon University
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/generated_dsp_code
License Description : Custom
License Terms       : The generated code is NOT included within the CEP repository due to license constraints.  
                      Pointers to generating these files are included for information purposes only.
                      This design is provided for internal, non-commercial research use only
                      and is not for redistribution, with or without modifications.
                      You may not use the name "Carnegie Mellon University" or derivations
                      thereof to endorse or promote products derived from this software.
 
                      THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER
                      EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY
                      THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS OR BE ERROR-FREE AND ANY
                      IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
                      TITLE, OR NON-INFRINGEMENT.  IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
                      BE LIABLE FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT,
                      SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN
                      ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY,
                      CONTRACT, TORT OR OTHERWISE).
Function            : Provides logic for the DFT and IDFT cores
Title               : gps
Source              : MIT Lincoln Laboratory
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/gps
License Description : BSD 2-Clause
License terms       : https://opensource.org/licenses/BSD-2-Clause
Function            : Surrogate GPS core for CA, P, and L code generation
                    : L-code leverages the aes core mentioned above
Title               : md5
Source              : http://pancham.sourceforge.net/
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/md5
License Description : LGPL 2.1
License terms       : https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
Function            : This core provides a standard MD5 hash function.  It will be integrated as a HW accelerator into the SoC.
Title               : rsa
Source              : http://git.level2crm.com/cryptech/core-math-modexp/tree/master
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/rsa
License Description : LGPL-ish
License terms       : // Author: Joachim Strombergson
                      // Copyright (c) 2013, Secworks Sweden AB
                      // All rights reserved.
                      //
                      // Redistribution and use in source and binary forms, with or
                      // without modification, are permitted provided that the following
                      // conditions are met:
                      //
                      // 1. Redistributions of source code must retain the above copyright
                      //    notice, this list of conditions and the following disclaimer.
                      //
                      // 2. Redistributions in binary form must reproduce the above copyright
                      //    notice, this list of conditions and the following disclaimer in
                      //    the documentation and/or other materials provided with the
                      //    distribution.
                      //
                      // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
                      // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
                      // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
                      // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
                      // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
                      // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
                      // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
                      // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
                      // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
                      // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                      // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
                      // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Function:             This core provides the mathematical base (modular exponentiation) required to implement a standard 2048-bit 
                      RSA public-key encryption function.  It will be integrated as a HW accelerator into the SoC.
Title               : sha256
Source              : http://git.level2crm.com/cryptech/core-hash-sha256/tree/master
CEP Directory       : ./generators/mitll-blocks/src/main/resources/vsrc/sha256
License Description : LGPL-ish
License terms       : // Author: Joachim Strombergson
                      // Copyright (c) 2013, Secworks Sweden AB
                      // All rights reserved.
                      //
                      // Redistribution and use in source and binary forms, with or
                      // without modification, are permitted provided that the following
                      // conditions are met:
                      //
                      // 1. Redistributions of source code must retain the above copyright
                      //    notice, this list of conditions and the following disclaimer.
                      //
                      // 2. Redistributions in binary form must reproduce the above copyright
                      //    notice, this list of conditions and the following disclaimer in
                      //    the documentation and/or other materials provided with the
                      //    distribution.
                      //
                      // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
                      // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
                      // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
                      // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
                      // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
                      // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
                      // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
                      // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
                      // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
                      // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
                      // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
                      // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Function            : This core provides a standard SHA hash function, where the resulting hash value is 256 bits.  It will be integrated as a HW accelerator into the SoC.
Title               : opentitan
Source              : https://github.com/lowRISC/opentitan
CEP Directory       : ./opentitan
License Description : Apache License v2.0
License Terms       : https://github.com/lowRISC/opentitan/blob/master/LICENSE
Function            : OpenTitan is the first open source project building a transparent, high-quality reference design and integration guidelines for silicon root of trust (RoT) chips.
                      Main website: www.opentitan.org
Title               : SD Card model for CEP Co-Simulation
Source              : SD SPI Simulation Model originally released by [email protected] and subsequented extracted from "Warke, Tejas Pravin, "Verification of 
                      SD/MMC Controller IP Using UVM" (2018). Thesis. Rochester Institute of Technology"
CEP Directory       : ./sims/cep_cosim/dvt/sd_spi_model.v
License Description : Unknown
License Terms       : Unknown
Function            : Provides an SD Card Model for simulation of a "full boot" of the CEP
Title               : UART Model for CEP Co-Simulation
Source              : https://github.com/ben-marshall/uart
CEP Directory       : ./sims/cep_cosim/dvt/uart_rx.v
License Description : MIT License
License Terms       : https://github.com/ben-marshall/uart/blob/master/LICENSE
Function            : Provides a simple UART Receiver for the CEP testbench
Title               : Free FFT and convolution (C)
Source              : https://www.nayuki.io/page/free-small-fft-in-multiple-languages
CEP Directory       : ./sims/cep_cosim/drivers/cep_tests/fft[.cc/.h]
License Description : MIT License
License Terms       : Copyright (c) 2018 Project Nayuki. (MIT License)
                      * Permission is hereby granted, free of charge, to any person obtaining a copy of
                      * this software and associated documentation files (the "Software"), to deal in
                      * the Software without restriction, including without limitation the rights to
                      * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
                      * the Software, and to permit persons to whom the Software is furnished to do so,
                      * subject to the following conditions:
                      * - The above copyright notice and this permission notice shall be included in
                      *   all copies or substantial portions of the Software.
                      * - The Software is provided "as is", without warranty of any kind, express or
                      *   implied, including but not limited to the warranties of merchantability,
                      *   fitness for a particular purpose and noninfringement. In no event shall the
                      *   authors or copyright holders be liable for any claim, damages or other
                      *   liability, whether in an action of contract, tort or otherwise, arising from,
                      *   out of or in connection with the Software or the use or other dealings in the
                      *   Software.
Title               : libgpiod-example
Source              : https://github.com/starnight/libgpiod-example
CEP Directory       : ./software/linux/gpiotest
License Description : BSD 3-Clause
Title               : Chipyard VC707 FPGA build target
Source              : https://github.com/necst/chipyard-vc707
CEP Directory       : ./fpga/src/main/scala/vc707
License Description : BSD 3-Clause
 | 
| 
	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | 
| 
	
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/
   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
   1. Definitions.
      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.
      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.
      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.
      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.
      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.
      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.
      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).
      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.
      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."
      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.
   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.
   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.
   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:
      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and
      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and
      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and
      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.
      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.
   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.
   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.
   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.
   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.
   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.
   END OF TERMS AND CONDITIONS
   APPENDIX: How to apply the Apache License to your work.
      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.
   Copyright 2016-2017 SiFive, Inc.
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 | 
| 
	
# Chipyard Framework [](https://github.com/ucb-bar/chipyard/actions)
## Quick Links
* **Stable Documentation**: https://chipyard.readthedocs.io/
* **User Question Forum**: https://groups.google.com/forum/#!forum/chipyard
* **Bugs and Feature Requests**: https://github.com/ucb-bar/chipyard/issues
## Using Chipyard
To get started using Chipyard, see the stable documentation on the Chipyard documentation site: https://chipyard.readthedocs.io/
## What is Chipyard
Chipyard is an open source framework for agile development of Chisel-based systems-on-chip.
It will allow you to leverage the Chisel HDL, Rocket Chip SoC generator, and other [Berkeley][berkeley] projects to produce a [RISC-V][riscv] SoC with everything from MMIO-mapped peripherals to custom accelerators.
Chipyard contains processor cores ([Rocket][rocket-chip], [BOOM][boom], [CVA6 (Ariane)][cva6]), accelerators ([Hwacha][hwacha], [Gemmini][gemmini], [NVDLA][nvdla]), memory systems, and additional peripherals and tooling to help create a full featured SoC.
Chipyard supports multiple concurrent flows of agile hardware development, including software RTL simulation, FPGA-accelerated simulation ([FireSim][firesim]), automated VLSI flows ([Hammer][hammer]), and software workload generation for bare-metal and Linux-based systems ([FireMarshal][firemarshal]).
Chipyard is actively developed in the [Berkeley Architecture Research Group][ucb-bar] in the [Electrical Engineering and Computer Sciences Department][eecs] at the [University of California, Berkeley][berkeley].
## Resources
* Chipyard Stable Documentation: https://chipyard.readthedocs.io/
* Chipyard (x FireSim) Tutorial: https://fires.im/tutorial
* Chipyard Basics slides: https://fires.im/isca22-slides-pdf/02_chipyard_basics.pdf
* Chipyard Tutorial Exercise slides: https://fires.im/isca22-slides-pdf/03_building_custom_socs.pdf
## Need help?
* Join the Chipyard Mailing List: https://groups.google.com/forum/#!forum/chipyard
* If you find a bug or would like propose a feature, post an issue on this repo: https://github.com/ucb-bar/chipyard/issues
## Contributing
* See [CONTRIBUTING.md](/CONTRIBUTING.md)
## Attribution and Chipyard-related Publications
If used for research, please cite Chipyard by the following publication:
```
@article{chipyard,
  author={Amid, Alon and Biancolin, David and Gonzalez, Abraham and Grubb, Daniel and Karandikar, Sagar and Liew, Harrison and Magyar,   Albert and Mao, Howard and Ou, Albert and Pemberton, Nathan and Rigge, Paul and Schmidt, Colin and Wright, John and Zhao, Jerry and Shao, Yakun Sophia and Asanovi\'{c}, Krste and Nikoli\'{c}, Borivoje},
  journal={IEEE Micro},
  title={Chipyard: Integrated Design, Simulation, and Implementation Framework for Custom SoCs},
  year={2020},
  volume={40},
  number={4},
  pages={10-21},
  doi={10.1109/MM.2020.2996616},
  ISSN={1937-4143},
}
```
* **Chipyard**
    * A. Amid, et al. *IEEE Micro'20* [PDF](https://ieeexplore.ieee.org/document/9099108).
    * A. Amid, et al. *DAC'20* [PDF](https://ieeexplore.ieee.org/document/9218756).
    * A. Amid, et al. *ISCAS'21* [PDF](https://ieeexplore.ieee.org/abstract/document/9401515).
These additional publications cover many of the internal components used in Chipyard. However, for the most up-to-date details, users should refer to the Chipyard docs.
* **Generators**
    * **Rocket Chip**: K. Asanovic, et al., *UCB EECS TR*. [PDF](http://www2.eecs.berkeley.edu/Pubs/TechRpts/2016/EECS-2016-17.pdf).
    * **BOOM**: C. Celio, et al., *Hot Chips 30*. [PDF](https://old.hotchips.org/hc30/1conf/1.03_Berkeley_BROOM_HC30.Berkeley.Celio.v02.pdf).
      * **SonicBOOM (BOOMv3)**: J. Zhao, et al., *CARRV'20*. [PDF](https://carrv.github.io/2020/papers/CARRV2020_paper_15_Zhao.pdf).
      * **COBRA (BOOM Branch Prediction)**: J. Zhao, et al., *ISPASS'21*. [PDF](https://ieeexplore.ieee.org/document/9408173).
    * **Hwacha**: Y. Lee, et al., *ESSCIRC'14*. [PDF](http://hwacha.org/papers/riscv-esscirc2014.pdf).
    * **Gemmini**: H. Genc, et al., *DAC'21*. [PDF](https://arxiv.org/pdf/1911.09925).
* **Sims**
    * **FireSim**: S. Karandikar, et al., *ISCA'18*. [PDF](https://sagark.org/assets/pubs/firesim-isca2018.pdf).
        * **FireSim Micro Top Picks**: S. Karandikar, et al., *IEEE Micro, Top Picks 2018*. [PDF](https://sagark.org/assets/pubs/firesim-micro-top-picks2018.pdf).
        * **FASED**: D. Biancolin, et al., *FPGA'19*. [PDF](https://people.eecs.berkeley.edu/~biancolin/papers/fased-fpga19.pdf).
        * **Golden Gate**: A. Magyar, et al., *ICCAD'19*. [PDF](https://davidbiancolin.github.io/papers/goldengate-iccad19.pdf).
        * **FirePerf**: S. Karandikar, et al., *ASPLOS'20*. [PDF](https://sagark.org/assets/pubs/fireperf-asplos2020.pdf).
* **Tools**
    * **Chisel**: J. Bachrach, et al., *DAC'12*. [PDF](https://people.eecs.berkeley.edu/~krste/papers/chisel-dac2012.pdf).
    * **FIRRTL**: A. Izraelevitz, et al., *ICCAD'17*. [PDF](https://ieeexplore.ieee.org/document/8203780).
    * **Chisel DSP**: A. Wang, et al., *DAC'18*. [PDF](https://ieeexplore.ieee.org/document/8465790).
    * **FireMarshal**: N. Pemberton, et al., *ISPASS'21*. [PDF](https://ieeexplore.ieee.org/document/9408192).
* **VLSI**
    * **Hammer**: E. Wang, et al., *ISQED'20*. [PDF](https://www.isqed.org/English/Archives/2020/Technical_Sessions/113.html).
## Acknowledgements
This work is supported by the NSF CCRI ENS Chipyard Award #201662.
[hwacha]:https://www2.eecs.berkeley.edu/Pubs/TechRpts/2015/EECS-2015-262.pdf
[hammer]:https://github.com/ucb-bar/hammer
[firesim]:https://fires.im
[ucb-bar]: http://bar.eecs.berkeley.edu
[eecs]: https://eecs.berkeley.edu
[berkeley]: https://berkeley.edu
[riscv]: https://riscv.org/
[rocket-chip]: https://github.com/freechipsproject/rocket-chip
[boom]: https://github.com/riscv-boom/riscv-boom
[firemarshal]: https://github.com/firesim/FireMarshal/
[cva6]: https://github.com/openhwgroup/cva6/
[gemmini]: https://github.com/ucb-bar/gemmini
[nvdla]: http://nvdla.org/
 | 
| 
	[//]: # (Copyright 2022 Massachusetts Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
# ---- ARCHIVED REPOSITORY ----
## The CEP now resides here [here](https://www.github.com/CommonEvaluationPlatform/CEP.git).
# Common Evaluation Platform v4.2
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
    <img src="./cep_docs/cep_logo.jpg" width="375" height="159">
</p>
<p align="center">
   Copyright 2022 Massachusetts Institute of Technology
</p>
<p align="center">
   <img src="./cep_docs/cep_architecture.jpg" width="1114" height="450">
</p>
<p align="center">
    <img src="./cep_docs/related_logos.jpg" width="442" height="120">
</p>
The Common Evaluation Platform (CEP) is an SoC design that contains only license-unencumbered, freely available components.  The CEP includes a range of accelerator cores coupled with a key delivery mechanism, and parametrically-defined challenge modules which can be synthesized to support developmental testing. The implementation of the CEP includes a comprehensive verification environment to ensure modifications do not impede intended functionality. It is intended to be targeted to either an FPGA or ASIC implementation. 
Please check the [CEP changelog](./CHANGELOG.CEP.md) for release history.
Beginning with CEP v4.0, the platform has been ported to the UCB Chipyard Framework.  The original Chipyard Readme can be found [here](./README.Chipyard.md).
Throughout the CEP READMEs, `<CEP_ROOT>` refers to the root directory of the cloned CEP repository.
## Pre-requisites (validated test/build configurations):
The following items describe the configuration of the system that CEP has been developed and tested on:
* Ubuntu 18.04 LTS x86_64 with Modelsim Questa Sim-64 v2019.1 (for co-simulation)
* Red Hat Enterprise Linux 7 with Cadence XCELIUMAGILE20.09.001, VMANAGERAGILE20.06.001
* Xilinx Vivado 2020.1 (needed for building FPGA targets)
  - Plus Digilent Adept Drivers for programming the FPGA target, https://reference.digilentinc.com/reference/software/adept/start?redirect=1#software_downloads)
* Terminal emulator (such as `minicom`)
* bash
Other configurations may work, but they have not been explicitly verified.
Instructions on how to modelsim, xcelium, and Vivado are beyond the scope of this README.
## Setting up your environment
To build the CEP, several packages and toolsets must be installed and built.  The typical steps are listed below.  Additional information can be found in the Chipyard Documentation [here](https://chipyard.readthedocs.io/en/latest/Chipyard-Basics/index.html).
A note about proxies: If your system is behind a proxy, you'll want to ensure your environment is properly configured.  Exact details vary by system, but the proxy needs to be available to apt / yum, curl, and sbt (Simple Build Tool for Scala)
If using RHEL7, you need to ensure gcc 7.x.x+ is installed.  This can be found in the `rhel-workstation-rhscl-7-rpms`  or `rhel-server-rhscl-7-rpms` repos, whose available is RHEL subscription dependent.  Once the repo is enabled, the appropriate gcc can be installed by running `sudo yum install devtoolset-7-gcc-c++`.  Once installed, you want to run `scl enable devtoolset-7 bash` (or whatever version you have installed) to ensure g++ maps to the new version.
* Install git if not already present on your system
  * Ubuntu - `sudo apt install git`
  * RHEL7  - `sudo yum install git`
* Clone the CEP repository, change to the directory of the clone
  * `git clone https://github.com/mit-ll/CEP.git`
* Install package dependencies.  Copies of these files can also be found in the Chipyard Documentation listed above
  * Ubuntu - `./scripts/ubuntu-reqs.sh`
  * RHEL7  - `./scripts/centos-reqs.sh`
* Initialize all the git submodules (including FPGA-related submodules).  There may be a warning about this not being a true chipyard repository which you can answer yes to.
  * `./scripts/init-submodules-no-riscv-tools.sh`
  * `./scripts/init-fpga.sh`
* Build the RISC-V Toolchain.  
  * Depending on your available hardware, you can expedite the build by executing `export MAKEFLAGS=-jN` prior to running the build script.  N is the number of cores you can devote to the build.
  * `./scripts/build-toolchains.sh riscv-tools`
* RHEL7: The chipyard build needs make v4.x or later, which is not included in the default packages.  Recommend building from source (https://ftp.gnu.org/gnu/make/).  Once installed, you can force the version of make used using the following: `MAKE=/usr/local/bin/make ./scripts/build-toolchains.sh riscv-tools`
* It is advisable to move the compiled toolchain outside of the current repo if you plan to have multiple CEP working directories.  Complete directions are beyond the scope of this document, but they do include moving the `riscv-tools-install` directory and `env-riscv-tools.sh` file.  Modification of the aforementioned file as well as `env.sh` will required for smooth operation
* Sometimes the toolchain build may fail.  One may need to run the build several times.
* Once the toolchain is built, your want to source the new environment script: `source <CEP_ROOT>/env.sh`.
## Repository Directory Structure
Providing a complete directory structure is impractical, but some items are highlighted here.  It is worth noting that most of the structure is inherited from Chipyard.
```
<CEP_ROOT> 
  |- ./sims/cep_cosim/ -  
  |     Defines the CEP co-simulation evironment for performing "chip" level simulations of the CEP in 
  |     either bare metal or bus functional model (BFM) mode.  
  |- ./generators/mitll-blocks/
  |   |- src/main/scala - Contains all the custom CEP Chisel code
  |   |- src/main/resources/vsrc/ - SystemVerilog / Verilog files associated with the CEP build
  |       |- generated_dsp_code - Location to place the `dft_top.v` and `idft_top.v'
  |       |- opentitan  - Soft-link to the opentitan submodule located at ./opentitan
  |       |- aeees      - Challenge module.  Read the README.md in this directory for more information.
  |       |- auto-fir   - Challenge module.  Read the README.md in this directory for more information.
  |       |- shaaa      - Challenge module.  Read the README.md in this directory for more information.
  |- ./cep_docs - Documents and images unique to the CEP
  |- ./software/baremetal - Examples of bare metal code that can be run on the Arty100T FPGA target
                            independent of the CEP Co-Simulation environment
```
### Building the CEP FPGA
Multiple Chipyard *SUB_PROJECTS* have been defined for the CEP when targetting FPGA Development boards.
These subprojects define the system configuration and are as follows:
`cep_arty100t` - Arty100T Development Board 
- 50 MHz Core Frequency
- 98% LUT Utilization
- 1x WithNBigCore
- CEP Registers
- AES Core
- Surrogate Root of Trust (SRoT)
`cep_vc707` - VC707 Development Board
- 100 MHz Core Frequency4
- 11% LUT Utilization
- 1x WithNBigCore
- CEP Registers
- AES Core
- Surrogate Root of Trust (SRoT)
`cep_big_vc707` - VC707 Development Board
- 100 MHz Core Frequency
- 70% LUT Utilization
- 4x WithNBigCores
- CEP Registers
- AES Core
- DES3 Core
- FIR Core
- IIR Core
- DFT Core
- IDFT Core
- MD5 Core
- 4x GPS Cores
- 4x SHA-256 Cores
- RSA Core
- Surrogate Root of Trust
`cep_vcu118` - VCU118 Development Board
- 100 MHz Core Frequency
- 5% LUT Utilization
- 1x WithNBigCore
- CEP Registers
- AES Core
- Surrogate Root of Trust (SRoT)
Assuming the Vivado environment scripts have been sourced within your current shell, the following commands can be used to build and program the FPGA *SUB_PROJECT*.  Programming requires that the digilent drivers have been installed and that you have a USB connection to the JTAG USB-port of you preffered FPGA board.
Default CEP builds can be customized by following the instructions in the Chipyard documentation.
The FPGA boards will configure from FLASH or JTAG based on the state of the MODE jumper.  Additional information can be found:
* Arty100T - [here](https://digilent.com/shop/arty-a7-artix-7-fpga-development-board/).
* VC707    - [here](https://www.xilinx.com/products/boards-and-kits/ek-v7-vc707-g.html/).
* VCU118   - [here](https://www.xilinx.com/products/boards-and-kits/vcu118.html/).
```
cd <REPO_ROOT>/fpga
make SUB_PROJECT=<cep_arty100t | cep_vc707 | cep_vcu118>
./program_<arty100t | vc707 | vcu118>_flash.sh - Create the MCS file & program the development board's flash.  Power needs to be cycled or the *PROG* button needs to be asserted to reboot with the new configuration.
OR
./program_<arty100t | vc707 | vcu118>_jtag.sh - Program the FPGA via JTAG.  System will automatically reset or you can use the *RESET* button.
```
### Building Bare Metal software for the CEP FPGA
The Arty100T shares a single microUSB connector for JTAG and UART, while the VC707 and VCU118 have seperate ports for each.
For the Arty100T, connect a Digilent SD or microSD PMOD board o connector JA.  For the VCU118, connect the same to the PMOD connector on the right side of the board.  The PMOD connectors can be ordered from Digikey, Digilent, or other distributors.
Additional information can be found here: (https://digilent.com/shop/pmod-sd-full-sized-sd-card-slot/ or https://digilent.com/shop/pmod-microsd-microsd-card-slot/).
As noted, for the Arty100T the microUSB port uses an FTDI chip to provide both JTAG and UART functionality.  Your system may differ, but typically the UART shows up as `/dev/ttyUSB0` or `/dev/ttyUSB1`.  UART settings are 115200baud, 8N1 and should be visible to any terminal program.  Both HW and SW flow control should be disabled.  
It is worth noting that *minicom* enables HW flow control by default.
Once released from reset, the CEP's bootrom will read the baremetal executable from the SD card, copy it DDR memory, and then jump to that location and execute the program.  The bootrom's default payload size is large enough for a linux boot.  For bare metal executables, the payloads are typically much smaller.  The payload size can be overriden at boot time by holding *BTN0* on the Arty100T or *SWN* on the VC707/VCU118 when the chip is released from reset.
An example UART output for the baremetal gpiotest follows:
```
---          Common Evaluation Platform v4.20            ---
---         Based on the UCB Chipyard Framework          ---
--- Copyright 2022 Massachusetts Institute of Technology ---
---     BootRom Image built on Aug  1 2022 12:41:36      ---
INIT
CMD0
CMD8
ACMD41
CMD58
CMD16
CMD18
LOADING 128kB PAYLOAD
....
BOOT
--------------------------
     RISC-V GPIO Test     
--------------------------
     Built for VCU118
   Console Echo Enabled   
gpio = 00000010
gpio = 00000000
gpio = 00000020
gpio = 00000000
gpio = 00000080
gpio = 00000000
gpio = 00000040
gpio = 00000000
...
```
A developer may use baremetal software from the CEP cosimulation or the examples as provided in `<CEP_ROOT>/software/baremetal`.  
The (micro)SD card needs to be partitioned as described in (https://chipyard.readthedocs.io/en/latest/Prototyping/VCU118.html#running-linux-on-vcu118-designs).  Once partitioned, proceed to the next step.
In either case, it is important to note what device your (micro)SD card gets mapped to (e.g., `/dev/sdd`).
Using `<CEP_ROOT>/sims/cep_cosim/testSuites/bareMetal/regTest` as an example, the following steps will build and load the executable onto the (micro)SD card.
```
cd <CEP_ROOT>/sims/cep_cosim/testSuites/bareMetal/regTest
make DISABLE_KPRINTF=0 riscv_wrapper            <-- builds riscv_wrapper.img with console printf enabled
make DISK=/dev/sdd1 riscv_wrapper_sd_write      <-- copies riscv_wrapper.img to partition /dev/sdd1 (subsitute with your partition name)
```
In the above example, the bare metal regTest is built with the console printf function enabled.
The steps in `<CEP_ROOT>/software/baremetal/gpiotest` are slight different.
```
cd <CEP_ROOT>/software/baremetal/gpiotest
make DISK=/dev/sdd1 sd_write                    <-- copies gpiotest.img to partition /dev/sdd1 (subsitute with your device name)
```
It is worth noting that the examples in `<CEP_ROOT>/software/baremetal` do not require the compilation of the all the cosimulation libraries, but as a result, will not have access to those support functions.
### Booting Linux
The CEP Arty100T/VC707/VCU118 builds has been verified to support a firemarshall-based linux build by following the default workload instructions [here](https://chipyard.readthedocs.io/en/latest/Prototyping/VCU118.html#running-linux-on-vcu118-designs).
A couple of notes:
- The SD card must be partitioned as instructed
- Due to a bug in libguestfs on Ubuntu, the firemarshal build *may* fail.  Ensure your current shell has active sudo permissions before running the build.  I used a quick `sudo su`, exited the root shell, and then ran the build.
- Customization of the linux build will affect the resulting image size `<CEP_ROOT>/software/firemarshal/images/br-base-bin-nodisk-flat`.  Ensure that `PAYLOAD_SIZE_B` in `<CEP_ROOT>/sims/cep_cosim/bootrom/sd.c` is sized to accomodated the image.
### Linux Applications
You can install an example application in firemarshal's buildroot prior to building linux by running `make MAINPROGRAM=<prog name> install` from <CEP_ROOT>/software/linux.  Applications include `helloworld` and `gpiotest`. 
It is advisable to clean the buildroot build, should you change the configuration.  This can accomplished by running `make clean` within `<CEP_ROOT>/software/firemarshal/boards/prototype/distros/br/buildroot/`.
If you ncurses-based gpiotest application crashes before cleanup, executing the `reset` command should restore terminal behavior.
### CEP Co-Simulation
For simulation using the CEP Co-Simulation environment, the `cep_cosim` and `cep_cosim_asic` *SUB_PROJECTS* are defined in `<CEP_ROOT>/variables.mk`.  At this time, due to licensing constraints, the CEP ASIC build is not available as part of this repository.  As a result, any attempt to build it will fail given that a multitude of files are missing.  
Instructions on the CEP Co-Simulation (including the Chipyard build) can be found [here](./sims/cep_cosim/README.md).
### Generated DSP code notes
Due to licensing contraints, two of the DSP cores used during CEP development cannot be included in our repository.  Instructions on generating all the cores can be found [here](./generators/mitll-blocks/src/main/resources/vsrc/dsp/README.md).
## Errors? Ommissions? Questions?
Please feel free to file a github issue which the CEP developers check frequently.
## Citation Information
Citation information is contained [here](./citation.cff)
## Licensing
As the CEP has been developed with input from many sources, multiple licenses apply.  Please refer to the following files for licensing info. 
* [CEP License](./LICENSE.md)
* [CEP Components Licenses](./LICENSE.md)
* [Chipyard License](./LICENSE.md)
* [SiFive License](./LICENSE.SiFive.md)
## DISTRIBUTION STATEMENT A. Approved for public release. Distribution is unlimited.
This material is based upon work supported by the Defense Advanced Research Projects Agency under Air Force Contract No. FA8702-15-D-0001. Any opinions, findings, conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the Defense Advanced Research Projects Agency.
© 2022 Massachusetts Institute of Technology
The software/firmware is provided to you on an As-Is basis.
Delivered to the U.S. Government with Unlimited Rights, as defined in DFARS Part 252.227-7013 or 7014 (Feb 2014). Notwithstanding any copyright notice, U.S. Government rights in this work are defined by DFARS 252.227-7013 or DFARS 252.227-7014 as detailed above. Use of this work other than as specifically authorized by the U.S. Government may violate any copyrights that exist in this work
 | 
| 
	General
-------
This DockerFile contains the necessary steps to build a Docker container that can run
projects with riscv-tools, chisel3, firrtl, and verilator. When run up to the base stage, it installs the necessary
apt-get packages and sets the environment variables needed for CircleCI. When run up to the base-with-tools stage, it initializes and installs the necessary toolchains for running simulations and testing projects.
Build and Deploy the Container
------------------------------
    sudo docker build --target base . # to build the image for the CI
    sudo docker build --target base --build-arg CHIPYARD_HASH=<COMMIT_HASH> . # to build the image for the CI from a specific chipyard commit
    sudo docker build --target base-with-tools . # to build the full image
    sudo docker tag <IMAGE_ID> <PATH_NAME>:tag . # to tag the image after the build (ex. 0.0.3)
    sudo docker login # login into the account to push to
    sudo docker push <PATH_NAME>:tag # to push to repo with tag
    sudo docker run -it --privileged <IMAGE_ID> bash # to run an interactive version of the container
Path Names
----------
Older docker images (when this Dockerfile was in `riscv-boom/riscv-boom`) can be found in the <PATH_NAME> `riscvboom/riscvboom-images`.
Current up-to-date images are located in <PATH_NAME> `ucbbar/chipyard-image`. NOTE: Less recent images in this path may not have toolchains initialized
Current up-to-date CI images are located in <PATH_NAME> `ucbbar/chipyard-ci-image`.
 | 
| 
	// See LICENSE.SiFive for license details.
//VCS coverage exclude_file
`ifndef RESET_DELAY
 `define RESET_DELAY 777.7
`endif
`ifndef CLOCK_PERIOD
 `define CLOCK_PERIOD 1.0
`endif
`ifndef MODEL
 `define MODEL Arty100TFPGATestHarness
`endif
module Arty100TTestDriver;
  reg clock = 1'b0;
  reg reset = 1'b1;
  // the ArtyFPGATestHarness expects an active low reset, because the reset
  // switch on the dev board is also active low. the rest of the TestDriver
  // logic depends on active high reset. just give resetn to the test harness.
  wire resetn = !reset;
  always #(`CLOCK_PERIOD/2.0) clock = ~clock;
  initial #(`RESET_DELAY) reset = 0;
  // Read input arguments and initialize
  reg verbose = 1'b0;
  wire printf_cond = verbose && !reset;
  reg [63:0] max_cycles = 0;
  reg [63:0] dump_start = 0;
  reg [63:0] trace_count = 0;
  reg [2047:0] fsdbfile = 0;
  reg [2047:0] vcdplusfile = 0;
  reg [2047:0] vcdfile = 0;
  int unsigned rand_value;
  initial
  begin
    void'($value$plusargs("max-cycles=%d", max_cycles));
    void'($value$plusargs("dump-start=%d", dump_start));
    verbose = $test$plusargs("verbose");
    // do not delete the lines below.
    // $random function needs to be called with the seed once to affect all
    // the downstream $random functions within the Chisel-generated Verilog
    // code.
    // $urandom is seeded via cmdline (+ntb_random_seed in VCS) but that
    // doesn't seed $random.
    rand_value = $urandom;
    rand_value = $random(rand_value);
    if (verbose) begin
`ifdef VCS
      $fdisplay(stderr, "testing $random %0x seed %d", rand_value, unsigned'($get_initial_random_seed));
`else
      $fdisplay(stderr, "testing $random %0x", rand_value);
`endif
    end
`ifdef DEBUG
    if ($value$plusargs("vcdplusfile=%s", vcdplusfile))
    begin
`ifdef VCS
      $vcdplusfile(vcdplusfile);
`else
      $fdisplay(stderr, "Error: +vcdplusfile is VCS-only; use +vcdfile instead or recompile with VCS=1");
      $fatal;
`endif
    end
    if ($value$plusargs("fsdbfile=%s", fsdbfile))
    begin
`ifdef FSDB
      $fsdbDumpfile(fsdbfile);
      $fsdbDumpvars("+all");
      //$fsdbDumpSVA;
`else
      $fdisplay(stderr, "Error: +fsdbfile is FSDB-only; use +vcdfile/+vcdplus instead or recompile with FSDB=1");
      $fatal;
`endif
    end
    if ($value$plusargs("vcdfile=%s", vcdfile))
    begin
      $dumpfile(vcdfile);
      $dumpvars(0, testHarness);
    end
`ifdef FSDB
`define VCDPLUSON $fsdbDumpon;
`define VCDPLUSCLOSE $fsdbDumpoff;
`elsif VCS
`define VCDPLUSON $vcdpluson(0); $vcdplusmemon(0);
`define VCDPLUSCLOSE $vcdplusclose; $dumpoff;
`else
`define VCDPLUSON $dumpon;
`define VCDPLUSCLOSE $dumpoff;
`endif
`else
  // No +define+DEBUG
`define VCDPLUSON
`define VCDPLUSCLOSE
    if ($test$plusargs("vcdplusfile=") || $test$plusargs("vcdfile=") || $test$plusargs("fsdbfile="))
    begin
      $fdisplay(stderr, "Error: +vcdfile, +vcdplusfile, or +fsdbfile requested but compile did not have +define+DEBUG enabled");
      $fatal;
    end
`endif
    if (dump_start == 0)
    begin
      // Start dumping before first clock edge to capture reset sequence in waveform
      `VCDPLUSON
    end
  end
`ifdef TESTBENCH_IN_UVM
  // UVM library has its own way to manage end-of-simulation.
  // A UVM-based testbench will raise an objection, watch this signal until this goes 1, then drop the objection.
  reg finish_request = 1'b0;
`endif
  reg [255:0] reason = "";
  reg failure = 1'b0;
  wire success;
  integer stderr = 32'h80000002;
  always @(posedge clock)
  begin
`ifdef GATE_LEVEL
    if (verbose)
    begin
      $fdisplay(stderr, "C: %10d", trace_count);
    end
`endif
    trace_count = trace_count + 1;
    if (trace_count == dump_start)
    begin
      `VCDPLUSON
    end
    if (!reset)
    begin
      if (max_cycles > 0 && trace_count > max_cycles)
      begin
        reason = " (timeout)";
        failure = 1'b1;
      end
      if (failure)
      begin
        $fdisplay(stderr, "*** FAILED ***%s after %d simulation cycles", reason, trace_count);
        `VCDPLUSCLOSE
        $fatal;
      end
      if (success)
      begin
        if (verbose)
          $fdisplay(stderr, "*** PASSED *** Completed after %d simulation cycles", trace_count);
        `VCDPLUSCLOSE
`ifdef TESTBENCH_IN_UVM
        finish_request = 1;
`else
        $finish;
`endif
      end
    end
  end
  `MODEL testHarness(
    .sys_clock(clock),
    .reset(resetn),
    .success(success)
  );
endmodule
 | 
| 
	// See LICENSE.SiFive for license details.
//VCS coverage exclude_file
`ifndef RESET_DELAY
 `define RESET_DELAY 777.7
`endif
`ifndef CLOCK_PERIOD
 `define CLOCK_PERIOD 1.0
`endif
`ifndef MODEL
 `define MODEL ArtyFPGATestHarness
`endif
module ArtyTestDriver;
  reg clock = 1'b0;
  reg reset = 1'b1;
  // the ArtyFPGATestHarness expects an active low reset, because the reset
  // switch on the dev board is also active low. the rest of the TestDriver
  // logic depends on active high reset. just give resetn to the test harness.
  wire resetn = !reset;
  always #(`CLOCK_PERIOD/2.0) clock = ~clock;
  initial #(`RESET_DELAY) reset = 0;
  // Read input arguments and initialize
  reg verbose = 1'b0;
  wire printf_cond = verbose && !reset;
  reg [63:0] max_cycles = 0;
  reg [63:0] dump_start = 0;
  reg [63:0] trace_count = 0;
  reg [2047:0] fsdbfile = 0;
  reg [2047:0] vcdplusfile = 0;
  reg [2047:0] vcdfile = 0;
  int unsigned rand_value;
  initial
  begin
    void'($value$plusargs("max-cycles=%d", max_cycles));
    void'($value$plusargs("dump-start=%d", dump_start));
    verbose = $test$plusargs("verbose");
    // do not delete the lines below.
    // $random function needs to be called with the seed once to affect all
    // the downstream $random functions within the Chisel-generated Verilog
    // code.
    // $urandom is seeded via cmdline (+ntb_random_seed in VCS) but that
    // doesn't seed $random.
    rand_value = $urandom;
    rand_value = $random(rand_value);
    if (verbose) begin
`ifdef VCS
      $fdisplay(stderr, "testing $random %0x seed %d", rand_value, unsigned'($get_initial_random_seed));
`else
      $fdisplay(stderr, "testing $random %0x", rand_value);
`endif
    end
`ifdef DEBUG
    if ($value$plusargs("vcdplusfile=%s", vcdplusfile))
    begin
`ifdef VCS
      $vcdplusfile(vcdplusfile);
`else
      $fdisplay(stderr, "Error: +vcdplusfile is VCS-only; use +vcdfile instead or recompile with VCS=1");
      $fatal;
`endif
    end
    if ($value$plusargs("fsdbfile=%s", fsdbfile))
    begin
`ifdef FSDB
      $fsdbDumpfile(fsdbfile);
      $fsdbDumpvars("+all");
      //$fsdbDumpSVA;
`else
      $fdisplay(stderr, "Error: +fsdbfile is FSDB-only; use +vcdfile/+vcdplus instead or recompile with FSDB=1");
      $fatal;
`endif
    end
    if ($value$plusargs("vcdfile=%s", vcdfile))
    begin
      $dumpfile(vcdfile);
      $dumpvars(0, testHarness);
    end
`ifdef FSDB
`define VCDPLUSON $fsdbDumpon;
`define VCDPLUSCLOSE $fsdbDumpoff;
`elsif VCS
`define VCDPLUSON $vcdpluson(0); $vcdplusmemon(0);
`define VCDPLUSCLOSE $vcdplusclose; $dumpoff;
`else
`define VCDPLUSON $dumpon;
`define VCDPLUSCLOSE $dumpoff;
`endif
`else
  // No +define+DEBUG
`define VCDPLUSON
`define VCDPLUSCLOSE
    if ($test$plusargs("vcdplusfile=") || $test$plusargs("vcdfile=") || $test$plusargs("fsdbfile="))
    begin
      $fdisplay(stderr, "Error: +vcdfile, +vcdplusfile, or +fsdbfile requested but compile did not have +define+DEBUG enabled");
      $fatal;
    end
`endif
    if (dump_start == 0)
    begin
      // Start dumping before first clock edge to capture reset sequence in waveform
      `VCDPLUSON
    end
  end
`ifdef TESTBENCH_IN_UVM
  // UVM library has its own way to manage end-of-simulation.
  // A UVM-based testbench will raise an objection, watch this signal until this goes 1, then drop the objection.
  reg finish_request = 1'b0;
`endif
  reg [255:0] reason = "";
  reg failure = 1'b0;
  wire success;
  integer stderr = 32'h80000002;
  always @(posedge clock)
  begin
`ifdef GATE_LEVEL
    if (verbose)
    begin
      $fdisplay(stderr, "C: %10d", trace_count);
    end
`endif
    trace_count = trace_count + 1;
    if (trace_count == dump_start)
    begin
      `VCDPLUSON
    end
    if (!reset)
    begin
      if (max_cycles > 0 && trace_count > max_cycles)
      begin
        reason = " (timeout)";
        failure = 1'b1;
      end
      if (failure)
      begin
        $fdisplay(stderr, "*** FAILED ***%s after %d simulation cycles", reason, trace_count);
        `VCDPLUSCLOSE
        $fatal;
      end
      if (success)
      begin
        if (verbose)
          $fdisplay(stderr, "*** PASSED *** Completed after %d simulation cycles", trace_count);
        `VCDPLUSCLOSE
`ifdef TESTBENCH_IN_UVM
        finish_request = 1;
`else
        $finish;
`endif
      end
    end
  end
  `MODEL testHarness(
    .CLK100MHZ(clock),
    .ck_rst(resetn),
    .success(success)
  );
endmodule
 | 
| 
	// See LICENSE for license details.
/**
  * An unsynthesizable divide-by-N clock divider.
  * Duty cycle is 100 * (ceil(DIV / 2)) / DIV.
  */
module ClockDividerN #(parameter DIV = 1)(output logic clk_out = 1'b0, input clk_in);
    localparam CWIDTH = $clog2(DIV);
    localparam LOW_CYCLES = DIV / 2;
    localparam HIGH_TRANSITION = LOW_CYCLES - 1;
    localparam LOW_TRANSITION = DIV - 1;
    generate
        if (DIV == 1) begin
            // This needs to be procedural because of the assignment on declaration
            always @(clk_in) begin
                clk_out = clk_in;
            end
        end else begin
            reg [CWIDTH - 1: 0] count = HIGH_TRANSITION[CWIDTH-1:0];
            // The blocking assignment to clock out is used to conform what was done
            // in RC's clock dividers.
            // It should have the effect of preventing registers in the divided clock
            // domain latching register updates launched by the fast clock-domain edge
            // that occurs at the same simulated time (as the divided clock edge).
            always @(posedge clk_in) begin
                if (count == LOW_TRANSITION[CWIDTH-1:0]) begin
                    clk_out = 1'b0;
                    count <= '0;
                end
                else begin
                    if (count == HIGH_TRANSITION[CWIDTH-1:0]) begin
                        clk_out = 1'b1;
                    end
                    count <= count + 1'b1;
                end
            end
        end
    endgenerate
endmodule // ClockDividerN
 | 
| 
	// DOC include start: GCD portlist
module GCDMMIOBlackBox
  #(parameter WIDTH)
   (
    input                  clock,
    input                  reset,
    output                 input_ready,
    input                  input_valid,
    input [WIDTH-1:0]      x,
    input [WIDTH-1:0]      y,
    input                  output_ready,
    output                 output_valid,
    output reg [WIDTH-1:0] gcd,
    output                 busy
    );
// DOC include end: GCD portlist
   localparam S_IDLE = 2'b00, S_RUN = 2'b01, S_DONE = 2'b10;
   reg [1:0]               state;   
   reg [WIDTH-1:0]         tmp;
   assign input_ready = state == S_IDLE;
   assign output_valid = state == S_DONE;
   assign busy = state != S_IDLE;
   always @(posedge clock) begin
      if (reset)
        state <= S_IDLE;
      else if (state == S_IDLE && input_valid)
        state <= S_RUN;
      else if (state == S_RUN && tmp == 0)
        state <= S_DONE;
      else if (state == S_DONE && output_ready)
        state <= S_IDLE;
   end
   
   always @(posedge clock) begin
      if (state == S_IDLE && input_valid) begin
         gcd <= x;
         tmp <= y;
      end else if (state == S_RUN) begin  
         if (gcd > tmp)
           gcd <= gcd - tmp;
         else
           tmp <= tmp - gcd;
      end
   end
endmodule // GCDMMIOBlackBox
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      cep_tb.v
// Program:        Common Evaluation Platform (CEP)
// Description:    CEP Co-Simulation Top Level Testbench 
// Notes:          
//
//--------------------------------------------------------------------------------------
module pll_wrapper (
  input   clk_in,
  input   reset_in,
  output  clk_out,
  output  reset_out
);
  assign clk_out    = clk_in;
  assign reset_out  = reset_in;
endmodule // pll_wrapper | 
| 
	[//]: # (Copyright 2022 Massachusets Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   Copyright 2022 Massachusets Institute of Technology
</p>
## AEEES-WB - Advanced Egregiously Extended Encryption Standard, White-Box Edition
The aeees.py script generates extended variants of the AES-128 core with the option of
"baking in the key" if desired.  
Executing `aeees.py -h` will print a complete list of script options.
Example usage:
```
    ./aeees.py -k 12345 -r 100 -t 500 -v    <- Generate a 100-round variant of AES-128 with the
                                               key fixed at "12345".  Generate 500 test vectors.
                                               Run in verbose mode
    ./aeees.py -nk -r 200 -t 250            <- Generate a 200-round variant of AES-128 with a
                                               key schedule.  Generate 250 test vectors.                                                 
```
Generated outputs from the first run example:
```
    aeees_roundfn.vi    - Utility functions for the AES rounds 
    aeees_rounds.v      - Individual definitions of all (100) AES rounds    
    aeees_box_XXX.vi    - Generated AES S-Box for round XXX with "baked-in" key
    aeees.v             - Top level AEEES module
    aeees_tb.v          - AEEES module testbench
    aeees_stimulus.v    - Stimulus file for the AEEES testbench
    Makefile            - Simulation makefile - just run "make"
    vsim.do             - Simulation TCL script
```
Generated outputs from the second run example:
```
    aeees_rounds.v      - Individual definitions of all (250) AES rounds    
    aeees_table.v       - AES S-Box definition
    aeees.v             - Top level AEEES module
    aeees_stimulus.csv  - Stimulus file for the AEEES testbench
    aeees_tb.sv         - AEEES module testbench
    Makefile            - Simulation makefile - just run "make"
    vsim.do             - Simulation TCL script
```
All generated files are implicitly included in .gitignore and are thus not tracked by git.
Caution should be taken when running the aeees.py script with the `--clean` switch.  
The following files will be deleted with `--clean`:
```
    aeees.v
    aeees_rounds.v
    eees_table.v
    aeees_stimulus.csv
    aeees_tb.sv
    Makefile
    vsim.do
    aeees_roundfn.vi
    aeees_box_*.vi
```
#### Return to the root CEP [README](../../README.md)
 | 
| 
	/*
 * Copyright 2012, Homer Hsing <[email protected]>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// assumes input does not change between start going high and out_valid
module aes_128(clk, rst, start, state, key, out, out_valid);
input          clk;
input          rst;
input          start;
input  [127:0] state, key;
output [127:0] out;
output         out_valid;
reg    [127:0] s0, k0;
wire   [127:0] s1, s2, s3, s4, s5, s6, s7, s8, s9,
       k1, k2, k3, k4, k5, k6, k7, k8, k9,
       k0b, k1b, k2b, k3b, k4b, k5b, k6b, k7b, k8b, k9b;
reg start_r;
always @(posedge clk or posedge rst)
    begin
    	if (rst)
    		start_r	<= 1'b0;
    	else
        	start_r <= start;
    end
wire start_posedge = start & ~start_r;
reg [4:0] validCounter;
always @ (posedge clk or posedge rst)
    begin
    	if (rst) begin
    		s0 				<= 0;
    		k0 			 	<= 0;
    		validCounter	<= 0;
    	end else begin
        	if(start_posedge)
            	begin
                	s0 <= state ^ key;
                	k0 <= key;
                	validCounter <= 21;
            	end
        	else if(~out_valid)
	            begin
                	validCounter <= validCounter - 1;
            	end
    	end // end if (rst)
    end // end always
assign out_valid = (validCounter == 0);
expand_key_128
    a1 (clk, rst, k0, k1, k0b, 8'h1),
    a2 (clk, rst, k1, k2, k1b, 8'h2),
    a3 (clk, rst, k2, k3, k2b, 8'h4),
    a4 (clk, rst, k3, k4, k3b, 8'h8),
    a5 (clk, rst, k4, k5, k4b, 8'h10),
    a6 (clk, rst, k5, k6, k5b, 8'h20),
    a7 (clk, rst, k6, k7, k6b, 8'h40),
    a8 (clk, rst, k7, k8, k7b, 8'h80),
    a9 (clk, rst, k8, k9, k8b, 8'h1b),
    a10 (clk, rst, k9,  , k9b, 8'h36);
one_round
    r1 (clk, rst, s0, k0b, s1),
    r2 (clk, rst, s1, k1b, s2),
    r3 (clk, rst, s2, k2b, s3),
    r4 (clk, rst, s3, k3b, s4),
    r5 (clk, rst, s4, k4b, s5),
    r6 (clk, rst, s5, k5b, s6),
    r7 (clk, rst, s6, k6b, s7),
    r8 (clk, rst, s7, k7b, s8),
    r9 (clk, rst, s8, k8b, s9);
final_round
    rf (clk, rst, s9, k9b, out);
endmodule
    module expand_key_128(clk, rst, in, out_1, out_2, rcon);
input              clk;
input			   rst;
input      [127:0] in;
input      [7:0]   rcon;
output reg [127:0] out_1;
output     [127:0] out_2;
wire       [31:0]  k0, k1, k2, k3,
           v0, v1, v2, v3;
reg        [31:0]  k0a, k1a, k2a, k3a;
wire       [31:0]  k0b, k1b, k2b, k3b, k4a;
assign {k0, k1, k2, k3} = in;
assign v0 = {k0[31:24] ^ rcon, k0[23:0]};
assign v1 = v0 ^ k1;
assign v2 = v1 ^ k2;
assign v3 = v2 ^ k3;
always @ (posedge clk or posedge rst)
begin
	if (rst) begin
		k0a		<= 0;
		k1a		<= 0;
		k2a		<= 0;
		k3a		<= 0;
    end else begin
    	{k0a, k1a, k2a, k3a} <= {v0, v1, v2, v3};
    end
end
S4
    S4_0 (clk, rst, {k3[23:0], k3[31:24]}, k4a);
assign k0b = k0a ^ k4a;
assign k1b = k1a ^ k4a;
assign k2b = k2a ^ k4a;
assign k3b = k3a ^ k4a;
always @ (posedge clk or posedge rst)
begin
	if (rst)
	    out_1 <= 0;
	else
	    out_1 <= {k0b, k1b, k2b, k3b};
end
assign out_2 = {k0b, k1b, k2b, k3b};
endmodule
 | 
| 
	/*
 * Copyright 2012, Homer Hsing <[email protected]>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// This is a fully unrolled implementation
module aes_192 (clk, rst, start, state, key, out, out_valid);
    input wire          clk; 
    input wire          rst; 
    input wire          start;
    input wire [127:0]  state;
    input wire [191:0]  key;
    output wire [127:0] out;
    output wire         out_valid;
    // Internals signals and such
    reg    [127:0]  s0;
    reg    [191:0]  k0;
    wire   [127:0]  s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;
    wire   [191:0]  k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11;
    wire   [127:0]  k0b, k1b, k2b, k3b, k4b, k5b, k6b, k7b, k8b, k9b, k10b, k11b;
    reg             start_r;
    wire            start_posedge;
    reg    [4:0]    validCounter;
    
    assign start_posedge = start & ~start_r;
    always @(posedge clk)
    begin
        if (rst)
            start_r <= 1'b0;
        else
            start_r <= start;
    end // end always
    always @ (posedge clk)
    begin
        if (rst) begin
            s0              <= 0;
            k0              <= 0;
            validCounter    <= 0;
        end else
            if(start_posedge)
                begin
                    s0 <= state ^ key[191:64];
                    k0 <= key;
                    validCounter <= 26;
                end
            else if(validCounter > 1)
                begin
                    validCounter <= validCounter - 1;
                end
    end // end always
    assign out_valid = (validCounter == 1);
    
    expand_key_type_D_192  a0 (clk, rst, k0, 8'h1,   k1,  k0b);
    expand_key_type_B_192  a1 (clk, rst, k1,         k2,  k1b);
    expand_key_type_A_192  a2 (clk, rst, k2, 8'h2,   k3,  k2b);
    expand_key_type_C_192  a3 (clk, rst, k3, 8'h4,   k4,  k3b);
    expand_key_type_B_192  a4 (clk, rst, k4,         k5,  k4b);
    expand_key_type_A_192  a5 (clk, rst, k5, 8'h8,   k6,  k5b);
    expand_key_type_C_192  a6 (clk, rst, k6, 8'h10,  k7,  k6b);
    expand_key_type_B_192  a7 (clk, rst, k7,         k8,  k7b);
    expand_key_type_A_192  a8 (clk, rst, k8, 8'h20,  k9,  k8b);
    expand_key_type_C_192  a9 (clk, rst, k9, 8'h40,  k10, k9b);
    expand_key_type_B_192 a10 (clk, rst, k10,        k11, k10b);
    expand_key_type_A_192 a11 (clk, rst, k11, 8'h80,    , k11b);
    one_round
        r1 (clk, rst, s0, k0b, s1),
        r2 (clk, rst, s1, k1b, s2),
        r3 (clk, rst, s2, k2b, s3),
        r4 (clk, rst, s3, k3b, s4),
        r5 (clk, rst, s4, k4b, s5),
        r6 (clk, rst, s5, k5b, s6),
        r7 (clk, rst, s6, k6b, s7),
        r8 (clk, rst, s7, k7b, s8),
        r9 (clk, rst, s8, k8b, s9),
        r10 (clk, rst, s9, k9b, s10),
        r11 (clk, rst, s10, k10b, s11);
    final_round
        rf (clk, rst, s11, k11b, out);
endmodule
/* expand k0,k1,k2,k3 for every two clock cycles */
module expand_key_type_A_192 (clk, rst, in, rcon, out_1, out_2);
    input wire          clk;
    input wire          rst;
    input wire  [191:0] in;
    input wire  [7:0]   rcon;
    output reg  [191:0] out_1;
    output wire [127:0] out_2;
    // Internal signals
    wire       [31:0]  k0, k1, k2, k3, k4, k5, v0, v1, v2, v3;
    reg        [31:0]  k0a, k1a, k2a, k3a, k4a, k5a;
    wire       [31:0]  k0b, k1b, k2b, k3b, k4b, k5b, k6a;
    assign {k0, k1, k2, k3, k4, k5} = in;
    assign v0 = {k0[31:24] ^ rcon, k0[23:0]};
    assign v1 = v0 ^ k1;
    assign v2 = v1 ^ k2;
    assign v3 = v2 ^ k3;
    always @ (posedge clk) 
    begin
        if (rst)
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {32'd0, 32'd0, 32'd0, 32'd0, 32'd0, 32'd0};
        else
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {v0, v1, v2, v3, k4, k5};
    end // end always
    S4 S4_0 (clk, rst, {k5[23:0], k5[31:24]}, k6a);
    assign k0b = k0a ^ k6a;
    assign k1b = k1a ^ k6a;
    assign k2b = k2a ^ k6a;
    assign k3b = k3a ^ k6a;
    assign {k4b, k5b} = {k4a, k5a};
    always @ (posedge clk)
    begin
        if (rst)
            out_1 <= 0;
        else
            out_1 <= {k0b, k1b, k2b, k3b, k4b, k5b};
    end // end always
    assign out_2 = {k0b, k1b, k2b, k3b};
endmodule   // end module expand_key_type_A_192
/* expand k2,k3,k4,k5 for every two clock cycles */
module expand_key_type_B_192 (clk, rst, in, out_1, out_2);
    input wire          clk;
    input wire          rst;
    input wire  [191:0] in;
    output reg  [191:0] out_1;
    output wire [127:0] out_2;
    wire        [31:0]  k0, k1, k2, k3, k4, k5, v2, v3, v4, v5;
    reg         [31:0]  k0a, k1a, k2a, k3a, k4a, k5a;
    assign {k0, k1, k2, k3, k4, k5} = in;
    assign v2 = k1 ^ k2;
    assign v3 = v2 ^ k3;
    assign v4 = v3 ^ k4;
    assign v5 = v4 ^ k5;
    always @ (posedge clk)
    begin
        if (rst)
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {32'd0, 32'd0, 32'd0, 32'd0, 32'd0, 32'd0};
        else
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {k0, k1, v2, v3, v4, v5};
    end // end always
    always @ (posedge clk)
    begin
        if (rst)
            out_1   <= 0;
        else
            out_1   <= {k0a, k1a, k2a, k3a, k4a, k5a};
    end
    assign out_2 = {k2a, k3a, k4a, k5a};
endmodule   // end expand_key_type_B_192
/* expand k0,k1,k4,k5 for every two clock cycles */
module expand_key_type_C_192 (clk, rst, in, rcon, out_1, out_2);
    input wire          clk;
    input wire          rst;
    input wire  [191:0] in;
    input wire  [7:0]   rcon;
    output reg  [191:0] out_1;
    output wire [127:0] out_2;
    wire       [31:0]  k0, k1, k2, k3, k4, k5, v4, v5, v0, v1;
    reg        [31:0]  k0a, k1a, k2a, k3a, k4a, k5a;
    wire       [31:0]  k0b, k1b, k2b, k3b, k4b, k5b, k6a;
    assign {k0, k1, k2, k3, k4, k5} = in;
    
    assign v4 = k3 ^ k4;
    assign v5 = v4 ^ k5;
    assign v0 = {k0[31:24] ^ rcon, k0[23:0]};
    assign v1 = v0 ^ k1;
    always @ (posedge clk)
    begin
        if (rst)
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {32'd0, 32'd0, 32'd0, 32'd0, 32'd0, 32'd0};
        else
            {k0a, k1a, k2a, k3a, k4a, k5a} <= {v0, v1, k2, k3, v4, v5};
    end
    S4 S4_0 (clk, rst, {v5[23:0], v5[31:24]}, k6a);
    assign k0b = k0a ^ k6a;
    assign k1b = k1a ^ k6a;
    assign {k2b, k3b, k4b, k5b} = {k2a, k3a, k4a, k5a};
    always @ (posedge clk)
    begin
        if (rst)
            out_1   <= 0;
        else
            out_1   <= {k0b, k1b, k2b, k3b, k4b, k5b};
    end
    assign out_2 = {k4b, k5b, k0b, k1b};
endmodule   // end expand_key_type_C_192
/* expand k0,k1 for every two clock cycles */
module expand_key_type_D_192 (clk, rst, in, rcon, out_1, out_2);
    input wire          clk;
    input wire          rst;
    input wire  [191:0] in;
    input wire  [7:0]   rcon;
    output reg  [191:0] out_1;
    output wire [127:0] out_2;
    wire       [31:0]  k0, k1, k2, k3, k4, k5, v0, v1;
    reg        [31:0]  k0a, k1a, k2a, k3a, k4a, k5a;
    wire       [31:0]  k0b, k1b, k2b, k3b, k4b, k5b, k6a;
    assign {k0, k1, k2, k3, k4, k5} = in;
    assign v0 = {k0[31:24] ^ rcon, k0[23:0]};
    assign v1 = v0 ^ k1;
    always @ (posedge clk)
    begin
        if (rst)
            {k0a, k1a, k2a, k3a, k4a, k5a}  <= {32'd0, 32'd0, 32'd0, 32'd0, 32'd0, 32'd0};
        else
            {k0a, k1a, k2a, k3a, k4a, k5a}  <= {v0, v1, k2, k3, k4, k5};
    end // end always
    S4 S4_0 (clk, rst, {k5[23:0], k5[31:24]}, k6a);
    assign k0b = k0a ^ k6a;
    assign k1b = k1a ^ k6a;
    assign {k2b, k3b, k4b, k5b} = {k2a, k3a, k4a, k5a};
    always @ (posedge clk)
    begin
        if (rst)
            out_1   <= 0;
        else
            out_1   <= {k0b, k1b, k2b, k3b, k4b, k5b};
    end // end always
    assign out_2 = {k4b, k5b, k0b, k1b};
endmodule   // end expand_key_type_D_192   
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       aes_192_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module aes_192_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst, 
    // Core I/O
    input wire            start,
    input wire [127:0]    state,
    input wire [191:0]    key,
    output wire [127:0]   out,
    output wire           out_valid,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = AES_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [(64*KEY_WORDS) - 1:0]   mock_tss_state;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  genvar i;
  generate
    for (i = 0; i < KEY_WORDS; i = i + 1) begin
      assign mock_tss_state[64*i +: 64] = AES_MOCK_TSS_KEY_WORDS[i] ^
                                          llkid_key_register[64*i +: 64] ^
                                          state[64*i +: 64];
    end
  endgenerate
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  aes_192 aes_192_inst (
    .clk          (clk),
    .rst          (rst),
    .start        (start),
    .state        (mock_tss_state),
    .key          (key),
    .out          (out),
    .out_valid    (out_valid)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	/*
 * Copyright 2012, Homer Hsing <[email protected]>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* verilator lint_off UNOPTFLAT */
/* one AES round for every two clock cycles */
module one_round (clk, rst, state_in, key, state_out);
input              clk;
input              rst;
input      [127:0] state_in, key;
output reg [127:0] state_out;
wire       [31:0]  s0,  s1,  s2,  s3,
           z0,  z1,  z2,  z3,
           p00, p01, p02, p03,
           p10, p11, p12, p13,
           p20, p21, p22, p23,
           p30, p31, p32, p33,
           k0,  k1,  k2,  k3;
assign {k0, k1, k2, k3} = key;
assign {s0, s1, s2, s3} = state_in;
table_lookup
    t0 (clk, rst, s0, p00, p01, p02, p03),
    t1 (clk, rst, s1, p10, p11, p12, p13),
    t2 (clk, rst, s2, p20, p21, p22, p23),
    t3 (clk, rst, s3, p30, p31, p32, p33);
assign z0 = p00 ^ p11 ^ p22 ^ p33 ^ k0;
assign z1 = p03 ^ p10 ^ p21 ^ p32 ^ k1;
assign z2 = p02 ^ p13 ^ p20 ^ p31 ^ k2;
assign z3 = p01 ^ p12 ^ p23 ^ p30 ^ k3;
always @ (posedge clk)
    state_out <= {z0, z1, z2, z3};
endmodule
    /* AES final round for every two clock cycles */
    module final_round (clk, rst, state_in, key_in, state_out);
input              clk;
input              rst;
input      [127:0] state_in;
input      [127:0] key_in;
output reg [127:0] state_out;
wire [31:0] s0,  s1,  s2,  s3,
     z0,  z1,  z2,  z3,
     k0,  k1,  k2,  k3;
wire [7:0]  p00, p01, p02, p03,
     p10, p11, p12, p13,
     p20, p21, p22, p23,
     p30, p31, p32, p33;
assign {k0, k1, k2, k3} = key_in;
assign {s0, s1, s2, s3} = state_in;
S4
    S4_1 (clk, rst, s0, {p00, p01, p02, p03}),
    S4_2 (clk, rst, s1, {p10, p11, p12, p13}),
    S4_3 (clk, rst, s2, {p20, p21, p22, p23}),
    S4_4 (clk, rst, s3, {p30, p31, p32, p33});
assign z0 = {p00, p11, p22, p33} ^ k0;
assign z1 = {p10, p21, p32, p03} ^ k1;
assign z2 = {p20, p31, p02, p13} ^ k2;
assign z3 = {p30, p01, p12, p23} ^ k3;
always @ (posedge clk)
    if (rst)
      state_out <= 0;
    else
      state_out <= {z0, z1, z2, z3};
endmodule
 | 
| 
	/*
 * Copyright 2012, Homer Hsing <[email protected]>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* verilator lint_off UNOPTFLAT */
module table_lookup (clk, rst, state, p0, p1, p2, p3);
    input clk;
    input rst;
    input [31:0] state;
    output [31:0] p0, p1, p2, p3;
    
    wire [7:0] b0, b1, b2, b3;
    assign {b0, b1, b2, b3} = state;
    T
        t0 (clk, rst, b0, {p0[23:0], p0[31:24]}),
        t1 (clk, rst, b1, {p1[15:0], p1[31:16]}),
        t2 (clk, rst, b2, {p2[7:0],  p2[31:8]} ),
        t3 (clk, rst, b3, p3);
endmodule   // end table_lookup
/* substitue four bytes in a word */
module S4 (clk, rst, in, out);
    input clk;
    input rst;
    input [31:0] in;
    output [31:0] out;
    S
        S_0 (clk, rst, in[31:24], out[31:24]),
        S_1 (clk, rst, in[23:16], out[23:16]),
        S_2 (clk, rst, in[15:8],  out[15:8] ),
        S_3 (clk, rst, in[7:0],   out[7:0]  );
endmodule   // end S4
/* S_box, S_box, S_box*(x+1), S_box*x */
module T (clk, rst, in, out);
    input         clk;
    input         rst;
    input  [7:0]  in;
    output [31:0] out;
    S
        s0 (clk, rst, in, out[31:24]);
    assign out[23:16] = out[31:24];
    xS
        s4 (clk, rst, in, out[7:0]);
    assign out[15:8] = out[23:16] ^ out[7:0];
endmodule   // end T
/* S box */
module S (clk, rst, in, out);
    input clk;
    input rst;
    input [7:0] in;
    output reg [7:0] out;
    always @ (posedge clk)
        if (rst)
            out <= 8'd0;
        else
            case (in)
            8'h00:  out <= 8'h63;
            8'h01:  out <= 8'h7c;
            8'h02:  out <= 8'h77;
            8'h03:  out <= 8'h7b;
            8'h04:  out <= 8'hf2;
            8'h05:  out <= 8'h6b;
            8'h06:  out <= 8'h6f;
            8'h07:  out <= 8'hc5;
            8'h08:  out <= 8'h30;
            8'h09:  out <= 8'h01;
            8'h0a:  out <= 8'h67;
            8'h0b:  out <= 8'h2b;
            8'h0c:  out <= 8'hfe;
            8'h0d:  out <= 8'hd7;
            8'h0e:  out <= 8'hab;
            8'h0f:  out <= 8'h76;
            8'h10:  out <= 8'hca;
            8'h11:  out <= 8'h82;
            8'h12:  out <= 8'hc9;
            8'h13:  out <= 8'h7d;
            8'h14:  out <= 8'hfa;
            8'h15:  out <= 8'h59;
            8'h16:  out <= 8'h47;
            8'h17:  out <= 8'hf0;
            8'h18:  out <= 8'had;
            8'h19:  out <= 8'hd4;
            8'h1a:  out <= 8'ha2;
            8'h1b:  out <= 8'haf;
            8'h1c:  out <= 8'h9c;
            8'h1d:  out <= 8'ha4;
            8'h1e:  out <= 8'h72;
            8'h1f:  out <= 8'hc0;
            8'h20:  out <= 8'hb7;
            8'h21:  out <= 8'hfd;
            8'h22:  out <= 8'h93;
            8'h23:  out <= 8'h26;
            8'h24:  out <= 8'h36;
            8'h25:  out <= 8'h3f;
            8'h26:  out <= 8'hf7;
            8'h27:  out <= 8'hcc;
            8'h28:  out <= 8'h34;
            8'h29:  out <= 8'ha5;
            8'h2a:  out <= 8'he5;
            8'h2b:  out <= 8'hf1;
            8'h2c:  out <= 8'h71;
            8'h2d:  out <= 8'hd8;
            8'h2e:  out <= 8'h31;
            8'h2f:  out <= 8'h15;
            8'h30:  out <= 8'h04;
            8'h31:  out <= 8'hc7;
            8'h32:  out <= 8'h23;
            8'h33:  out <= 8'hc3;
            8'h34:  out <= 8'h18;
            8'h35:  out <= 8'h96;
            8'h36:  out <= 8'h05;
            8'h37:  out <= 8'h9a;
            8'h38:  out <= 8'h07;
            8'h39:  out <= 8'h12;
            8'h3a:  out <= 8'h80;
            8'h3b:  out <= 8'he2;
            8'h3c:  out <= 8'heb;
            8'h3d:  out <= 8'h27;
            8'h3e:  out <= 8'hb2;
            8'h3f:  out <= 8'h75;
            8'h40:  out <= 8'h09;
            8'h41:  out <= 8'h83;
            8'h42:  out <= 8'h2c;
            8'h43:  out <= 8'h1a;
            8'h44:  out <= 8'h1b;
            8'h45:  out <= 8'h6e;
            8'h46:  out <= 8'h5a;
            8'h47:  out <= 8'ha0;
            8'h48:  out <= 8'h52;
            8'h49:  out <= 8'h3b;
            8'h4a:  out <= 8'hd6;
            8'h4b:  out <= 8'hb3;
            8'h4c:  out <= 8'h29;
            8'h4d:  out <= 8'he3;
            8'h4e:  out <= 8'h2f;
            8'h4f:  out <= 8'h84;
            8'h50:  out <= 8'h53;
            8'h51:  out <= 8'hd1;
            8'h52:  out <= 8'h00;
            8'h53:  out <= 8'hed;
            8'h54:  out <= 8'h20;
            8'h55:  out <= 8'hfc;
            8'h56:  out <= 8'hb1;
            8'h57:  out <= 8'h5b;
            8'h58:  out <= 8'h6a;
            8'h59:  out <= 8'hcb;
            8'h5a:  out <= 8'hbe;
            8'h5b:  out <= 8'h39;
            8'h5c:  out <= 8'h4a;
            8'h5d:  out <= 8'h4c;
            8'h5e:  out <= 8'h58;
            8'h5f:  out <= 8'hcf;
            8'h60:  out <= 8'hd0;
            8'h61:  out <= 8'hef;
            8'h62:  out <= 8'haa;
            8'h63:  out <= 8'hfb;
            8'h64:  out <= 8'h43;
            8'h65:  out <= 8'h4d;
            8'h66:  out <= 8'h33;
            8'h67:  out <= 8'h85;
            8'h68:  out <= 8'h45;
            8'h69:  out <= 8'hf9;
            8'h6a:  out <= 8'h02;
            8'h6b:  out <= 8'h7f;
            8'h6c:  out <= 8'h50;
            8'h6d:  out <= 8'h3c;
            8'h6e:  out <= 8'h9f;
            8'h6f:  out <= 8'ha8;
            8'h70:  out <= 8'h51;
            8'h71:  out <= 8'ha3;
            8'h72:  out <= 8'h40;
            8'h73:  out <= 8'h8f;
            8'h74:  out <= 8'h92;
            8'h75:  out <= 8'h9d;
            8'h76:  out <= 8'h38;
            8'h77:  out <= 8'hf5;
            8'h78:  out <= 8'hbc;
            8'h79:  out <= 8'hb6;
            8'h7a:  out <= 8'hda;
            8'h7b:  out <= 8'h21;
            8'h7c:  out <= 8'h10;
            8'h7d:  out <= 8'hff;
            8'h7e:  out <= 8'hf3;
            8'h7f:  out <= 8'hd2;
            8'h80:  out <= 8'hcd;
            8'h81:  out <= 8'h0c;
            8'h82:  out <= 8'h13;
            8'h83:  out <= 8'hec;
            8'h84:  out <= 8'h5f;
            8'h85:  out <= 8'h97;
            8'h86:  out <= 8'h44;
            8'h87:  out <= 8'h17;
            8'h88:  out <= 8'hc4;
            8'h89:  out <= 8'ha7;
            8'h8a:  out <= 8'h7e;
            8'h8b:  out <= 8'h3d;
            8'h8c:  out <= 8'h64;
            8'h8d:  out <= 8'h5d;
            8'h8e:  out <= 8'h19;
            8'h8f:  out <= 8'h73;
            8'h90:  out <= 8'h60;
            8'h91:  out <= 8'h81;
            8'h92:  out <= 8'h4f;
            8'h93:  out <= 8'hdc;
            8'h94:  out <= 8'h22;
            8'h95:  out <= 8'h2a;
            8'h96:  out <= 8'h90;
            8'h97:  out <= 8'h88;
            8'h98:  out <= 8'h46;
            8'h99:  out <= 8'hee;
            8'h9a:  out <= 8'hb8;
            8'h9b:  out <= 8'h14;
            8'h9c:  out <= 8'hde;
            8'h9d:  out <= 8'h5e;
            8'h9e:  out <= 8'h0b;
            8'h9f:  out <= 8'hdb;
            8'ha0:  out <= 8'he0;
            8'ha1:  out <= 8'h32;
            8'ha2:  out <= 8'h3a;
            8'ha3:  out <= 8'h0a;
            8'ha4:  out <= 8'h49;
            8'ha5:  out <= 8'h06;
            8'ha6:  out <= 8'h24;
            8'ha7:  out <= 8'h5c;
            8'ha8:  out <= 8'hc2;
            8'ha9:  out <= 8'hd3;
            8'haa:  out <= 8'hac;
            8'hab:  out <= 8'h62;
            8'hac:  out <= 8'h91;
            8'had:  out <= 8'h95;
            8'hae:  out <= 8'he4;
            8'haf:  out <= 8'h79;
            8'hb0:  out <= 8'he7;
            8'hb1:  out <= 8'hc8;
            8'hb2:  out <= 8'h37;
            8'hb3:  out <= 8'h6d;
            8'hb4:  out <= 8'h8d;
            8'hb5:  out <= 8'hd5;
            8'hb6:  out <= 8'h4e;
            8'hb7:  out <= 8'ha9;
            8'hb8:  out <= 8'h6c;
            8'hb9:  out <= 8'h56;
            8'hba:  out <= 8'hf4;
            8'hbb:  out <= 8'hea;
            8'hbc:  out <= 8'h65;
            8'hbd:  out <= 8'h7a;
            8'hbe:  out <= 8'hae;
            8'hbf:  out <= 8'h08;
            8'hc0:  out <= 8'hba;
            8'hc1:  out <= 8'h78;
            8'hc2:  out <= 8'h25;
            8'hc3:  out <= 8'h2e;
            8'hc4:  out <= 8'h1c;
            8'hc5:  out <= 8'ha6;
            8'hc6:  out <= 8'hb4;
            8'hc7:  out <= 8'hc6;
            8'hc8:  out <= 8'he8;
            8'hc9:  out <= 8'hdd;
            8'hca:  out <= 8'h74;
            8'hcb:  out <= 8'h1f;
            8'hcc:  out <= 8'h4b;
            8'hcd:  out <= 8'hbd;
            8'hce:  out <= 8'h8b;
            8'hcf:  out <= 8'h8a;
            8'hd0:  out <= 8'h70;
            8'hd1:  out <= 8'h3e;
            8'hd2:  out <= 8'hb5;
            8'hd3:  out <= 8'h66;
            8'hd4:  out <= 8'h48;
            8'hd5:  out <= 8'h03;
            8'hd6:  out <= 8'hf6;
            8'hd7:  out <= 8'h0e;
            8'hd8:  out <= 8'h61;
            8'hd9:  out <= 8'h35;
            8'hda:  out <= 8'h57;
            8'hdb:  out <= 8'hb9;
            8'hdc:  out <= 8'h86;
            8'hdd:  out <= 8'hc1;
            8'hde:  out <= 8'h1d;
            8'hdf:  out <= 8'h9e;
            8'he0:  out <= 8'he1;
            8'he1:  out <= 8'hf8;
            8'he2:  out <= 8'h98;
            8'he3:  out <= 8'h11;
            8'he4:  out <= 8'h69;
            8'he5:  out <= 8'hd9;
            8'he6:  out <= 8'h8e;
            8'he7:  out <= 8'h94;
            8'he8:  out <= 8'h9b;
            8'he9:  out <= 8'h1e;
            8'hea:  out <= 8'h87;
            8'heb:  out <= 8'he9;
            8'hec:  out <= 8'hce;
            8'hed:  out <= 8'h55;
            8'hee:  out <= 8'h28;
            8'hef:  out <= 8'hdf;
            8'hf0:  out <= 8'h8c;
            8'hf1:  out <= 8'ha1;
            8'hf2:  out <= 8'h89;
            8'hf3:  out <= 8'h0d;
            8'hf4:  out <= 8'hbf;
            8'hf5:  out <= 8'he6;
            8'hf6:  out <= 8'h42;
            8'hf7:  out <= 8'h68;
            8'hf8:  out <= 8'h41;
            8'hf9:  out <= 8'h99;
            8'hfa:  out <= 8'h2d;
            8'hfb:  out <= 8'h0f;
            8'hfc:  out <= 8'hb0;
            8'hfd:  out <= 8'h54;
            8'hfe:  out <= 8'hbb;
            8'hff:  out <= 8'h16;
        endcase
endmodule
/* S box * x */
module xS (clk, rst, in, out);
    input clk;
    input rst;
    input [7:0] in;
    output reg [7:0] out;
    always @ (posedge clk)
        if (rst)
            out <= 8'd0;
        else
            case (in)
            8'h00:  out <= 8'hc6;
            8'h01:  out <= 8'hf8;
            8'h02:  out <= 8'hee;
            8'h03:  out <= 8'hf6;
            8'h04:  out <= 8'hff;
            8'h05:  out <= 8'hd6;
            8'h06:  out <= 8'hde;
            8'h07:  out <= 8'h91;
            8'h08:  out <= 8'h60;
            8'h09:  out <= 8'h02;
            8'h0a:  out <= 8'hce;
            8'h0b:  out <= 8'h56;
            8'h0c:  out <= 8'he7;
            8'h0d:  out <= 8'hb5;
            8'h0e:  out <= 8'h4d;
            8'h0f:  out <= 8'hec;
            8'h10:  out <= 8'h8f;
            8'h11:  out <= 8'h1f;
            8'h12:  out <= 8'h89;
            8'h13:  out <= 8'hfa;
            8'h14:  out <= 8'hef;
            8'h15:  out <= 8'hb2;
            8'h16:  out <= 8'h8e;
            8'h17:  out <= 8'hfb;
            8'h18:  out <= 8'h41;
            8'h19:  out <= 8'hb3;
            8'h1a:  out <= 8'h5f;
            8'h1b:  out <= 8'h45;
            8'h1c:  out <= 8'h23;
            8'h1d:  out <= 8'h53;
            8'h1e:  out <= 8'he4;
            8'h1f:  out <= 8'h9b;
            8'h20:  out <= 8'h75;
            8'h21:  out <= 8'he1;
            8'h22:  out <= 8'h3d;
            8'h23:  out <= 8'h4c;
            8'h24:  out <= 8'h6c;
            8'h25:  out <= 8'h7e;
            8'h26:  out <= 8'hf5;
            8'h27:  out <= 8'h83;
            8'h28:  out <= 8'h68;
            8'h29:  out <= 8'h51;
            8'h2a:  out <= 8'hd1;
            8'h2b:  out <= 8'hf9;
            8'h2c:  out <= 8'he2;
            8'h2d:  out <= 8'hab;
            8'h2e:  out <= 8'h62;
            8'h2f:  out <= 8'h2a;
            8'h30:  out <= 8'h08;
            8'h31:  out <= 8'h95;
            8'h32:  out <= 8'h46;
            8'h33:  out <= 8'h9d;
            8'h34:  out <= 8'h30;
            8'h35:  out <= 8'h37;
            8'h36:  out <= 8'h0a;
            8'h37:  out <= 8'h2f;
            8'h38:  out <= 8'h0e;
            8'h39:  out <= 8'h24;
            8'h3a:  out <= 8'h1b;
            8'h3b:  out <= 8'hdf;
            8'h3c:  out <= 8'hcd;
            8'h3d:  out <= 8'h4e;
            8'h3e:  out <= 8'h7f;
            8'h3f:  out <= 8'hea;
            8'h40:  out <= 8'h12;
            8'h41:  out <= 8'h1d;
            8'h42:  out <= 8'h58;
            8'h43:  out <= 8'h34;
            8'h44:  out <= 8'h36;
            8'h45:  out <= 8'hdc;
            8'h46:  out <= 8'hb4;
            8'h47:  out <= 8'h5b;
            8'h48:  out <= 8'ha4;
            8'h49:  out <= 8'h76;
            8'h4a:  out <= 8'hb7;
            8'h4b:  out <= 8'h7d;
            8'h4c:  out <= 8'h52;
            8'h4d:  out <= 8'hdd;
            8'h4e:  out <= 8'h5e;
            8'h4f:  out <= 8'h13;
            8'h50:  out <= 8'ha6;
            8'h51:  out <= 8'hb9;
            8'h52:  out <= 8'h00;
            8'h53:  out <= 8'hc1;
            8'h54:  out <= 8'h40;
            8'h55:  out <= 8'he3;
            8'h56:  out <= 8'h79;
            8'h57:  out <= 8'hb6;
            8'h58:  out <= 8'hd4;
            8'h59:  out <= 8'h8d;
            8'h5a:  out <= 8'h67;
            8'h5b:  out <= 8'h72;
            8'h5c:  out <= 8'h94;
            8'h5d:  out <= 8'h98;
            8'h5e:  out <= 8'hb0;
            8'h5f:  out <= 8'h85;
            8'h60:  out <= 8'hbb;
            8'h61:  out <= 8'hc5;
            8'h62:  out <= 8'h4f;
            8'h63:  out <= 8'hed;
            8'h64:  out <= 8'h86;
            8'h65:  out <= 8'h9a;
            8'h66:  out <= 8'h66;
            8'h67:  out <= 8'h11;
            8'h68:  out <= 8'h8a;
            8'h69:  out <= 8'he9;
            8'h6a:  out <= 8'h04;
            8'h6b:  out <= 8'hfe;
            8'h6c:  out <= 8'ha0;
            8'h6d:  out <= 8'h78;
            8'h6e:  out <= 8'h25;
            8'h6f:  out <= 8'h4b;
            8'h70:  out <= 8'ha2;
            8'h71:  out <= 8'h5d;
            8'h72:  out <= 8'h80;
            8'h73:  out <= 8'h05;
            8'h74:  out <= 8'h3f;
            8'h75:  out <= 8'h21;
            8'h76:  out <= 8'h70;
            8'h77:  out <= 8'hf1;
            8'h78:  out <= 8'h63;
            8'h79:  out <= 8'h77;
            8'h7a:  out <= 8'haf;
            8'h7b:  out <= 8'h42;
            8'h7c:  out <= 8'h20;
            8'h7d:  out <= 8'he5;
            8'h7e:  out <= 8'hfd;
            8'h7f:  out <= 8'hbf;
            8'h80:  out <= 8'h81;
            8'h81:  out <= 8'h18;
            8'h82:  out <= 8'h26;
            8'h83:  out <= 8'hc3;
            8'h84:  out <= 8'hbe;
            8'h85:  out <= 8'h35;
            8'h86:  out <= 8'h88;
            8'h87:  out <= 8'h2e;
            8'h88:  out <= 8'h93;
            8'h89:  out <= 8'h55;
            8'h8a:  out <= 8'hfc;
            8'h8b:  out <= 8'h7a;
            8'h8c:  out <= 8'hc8;
            8'h8d:  out <= 8'hba;
            8'h8e:  out <= 8'h32;
            8'h8f:  out <= 8'he6;
            8'h90:  out <= 8'hc0;
            8'h91:  out <= 8'h19;
            8'h92:  out <= 8'h9e;
            8'h93:  out <= 8'ha3;
            8'h94:  out <= 8'h44;
            8'h95:  out <= 8'h54;
            8'h96:  out <= 8'h3b;
            8'h97:  out <= 8'h0b;
            8'h98:  out <= 8'h8c;
            8'h99:  out <= 8'hc7;
            8'h9a:  out <= 8'h6b;
            8'h9b:  out <= 8'h28;
            8'h9c:  out <= 8'ha7;
            8'h9d:  out <= 8'hbc;
            8'h9e:  out <= 8'h16;
            8'h9f:  out <= 8'had;
            8'ha0:  out <= 8'hdb;
            8'ha1:  out <= 8'h64;
            8'ha2:  out <= 8'h74;
            8'ha3:  out <= 8'h14;
            8'ha4:  out <= 8'h92;
            8'ha5:  out <= 8'h0c;
            8'ha6:  out <= 8'h48;
            8'ha7:  out <= 8'hb8;
            8'ha8:  out <= 8'h9f;
            8'ha9:  out <= 8'hbd;
            8'haa:  out <= 8'h43;
            8'hab:  out <= 8'hc4;
            8'hac:  out <= 8'h39;
            8'had:  out <= 8'h31;
            8'hae:  out <= 8'hd3;
            8'haf:  out <= 8'hf2;
            8'hb0:  out <= 8'hd5;
            8'hb1:  out <= 8'h8b;
            8'hb2:  out <= 8'h6e;
            8'hb3:  out <= 8'hda;
            8'hb4:  out <= 8'h01;
            8'hb5:  out <= 8'hb1;
            8'hb6:  out <= 8'h9c;
            8'hb7:  out <= 8'h49;
            8'hb8:  out <= 8'hd8;
            8'hb9:  out <= 8'hac;
            8'hba:  out <= 8'hf3;
            8'hbb:  out <= 8'hcf;
            8'hbc:  out <= 8'hca;
            8'hbd:  out <= 8'hf4;
            8'hbe:  out <= 8'h47;
            8'hbf:  out <= 8'h10;
            8'hc0:  out <= 8'h6f;
            8'hc1:  out <= 8'hf0;
            8'hc2:  out <= 8'h4a;
            8'hc3:  out <= 8'h5c;
            8'hc4:  out <= 8'h38;
            8'hc5:  out <= 8'h57;
            8'hc6:  out <= 8'h73;
            8'hc7:  out <= 8'h97;
            8'hc8:  out <= 8'hcb;
            8'hc9:  out <= 8'ha1;
            8'hca:  out <= 8'he8;
            8'hcb:  out <= 8'h3e;
            8'hcc:  out <= 8'h96;
            8'hcd:  out <= 8'h61;
            8'hce:  out <= 8'h0d;
            8'hcf:  out <= 8'h0f;
            8'hd0:  out <= 8'he0;
            8'hd1:  out <= 8'h7c;
            8'hd2:  out <= 8'h71;
            8'hd3:  out <= 8'hcc;
            8'hd4:  out <= 8'h90;
            8'hd5:  out <= 8'h06;
            8'hd6:  out <= 8'hf7;
            8'hd7:  out <= 8'h1c;
            8'hd8:  out <= 8'hc2;
            8'hd9:  out <= 8'h6a;
            8'hda:  out <= 8'hae;
            8'hdb:  out <= 8'h69;
            8'hdc:  out <= 8'h17;
            8'hdd:  out <= 8'h99;
            8'hde:  out <= 8'h3a;
            8'hdf:  out <= 8'h27;
            8'he0:  out <= 8'hd9;
            8'he1:  out <= 8'heb;
            8'he2:  out <= 8'h2b;
            8'he3:  out <= 8'h22;
            8'he4:  out <= 8'hd2;
            8'he5:  out <= 8'ha9;
            8'he6:  out <= 8'h07;
            8'he7:  out <= 8'h33;
            8'he8:  out <= 8'h2d;
            8'he9:  out <= 8'h3c;
            8'hea:  out <= 8'h15;
            8'heb:  out <= 8'hc9;
            8'hec:  out <= 8'h87;
            8'hed:  out <= 8'haa;
            8'hee:  out <= 8'h50;
            8'hef:  out <= 8'ha5;
            8'hf0:  out <= 8'h03;
            8'hf1:  out <= 8'h59;
            8'hf2:  out <= 8'h09;
            8'hf3:  out <= 8'h1a;
            8'hf4:  out <= 8'h65;
            8'hf5:  out <= 8'hd7;
            8'hf6:  out <= 8'h84;
            8'hf7:  out <= 8'hd0;
            8'hf8:  out <= 8'h82;
            8'hf9:  out <= 8'h29;
            8'hfa:  out <= 8'h5a;
            8'hfb:  out <= 8'h1e;
            8'hfc:  out <= 8'h7b;
            8'hfd:  out <= 8'ha8;
            8'hfe:  out <= 8'h6d;
            8'hff:  out <= 8'h2c;
        endcase
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      filter_tb.v
// Program:        Common Evaluation Platform (CEP)
// Description:    This is a unit level testbench for the generated
//                 IIR filters.  It operates in two modes (controlled
//                 via a DEFINE passed to the simulator.
// Notes:          Usable defines:
//                 CAPTURE - If defined, the test bench will generate
//                   NUM_SAMPLES of random inputs and capture the outputs
//                   to CAPTURE_FILE for subsequent verification.
//                 VERIFY - If defined (CAPTURE has a higher priority),
//                   the testbench will use the CAPTURE_FILE to verify the
//                   device under test still behaves as expected.
//
//************************************************************************
`timescale 1ns/1ns
// Provide a default for NUM_SAMPLES in the event it was not
// previously defined
`ifndef NUM_SAMPLES
    `define NUM_SAMPLES     100
`endif
        
// Define the default capture file (if not defined)
`ifndef CAPTURE_FILE
    `define CAPTURE_FILE    filter_tb_capture.log
`endif
// Define the DUT if not define
`ifndef DUT_NAME
    `define DUT_NAME        filter
`endif
// Misc. Defines
`define     DATA_WIDTH      64
`define     CLK_PERIOD      10
module filter_tb;
    // DUT Signals and other things
    reg                     clk     = 0;
    reg                     reset   = 1;
    reg [`DATA_WIDTH-1:0]   inData  = 0;
    wire [`DATA_WIDTH-1:0]  outData;
    integer                 errCnt  = 0;
    // Clocking block
    initial begin
        forever #(`CLK_PERIOD/2) clk = !clk;
    end
    // Instantiate the DUT
    `DUT_NAME u1(
        .inData     (inData), 
        .clk        (clk), 
        .reset      (!reset), 
        .outData    (outData)
    );
    // The testbench must have either CAPTURE or VERIFY defined (but NOT both)
    `ifndef CAPTURE
        `ifndef VERIFY
            initial begin
                $display("ERROR: CAPTURE or VERIFY must be defined");
                $fatal;
            end
        `endif
    `endif
    `ifdef CAPTURE
        `ifdef VERIFY
            initial begin
                $display("ERROR: CAPTURE and VERIFY cannot both be defined");
                $fatal;
            end
        `endif
    `endif
    // CAPTURE mode
    // When operating in CAPTURE mode, the testbench will generate a random set of
    // input vectors (64-bits each) and capture the output (following a release
    // from reset).  The I/O pair will be saved to CAPTURE_FILE
    `ifdef CAPTURE
        initial begin
            inData  = 0;
            reset   = 1;
            repeat (5) @(posedge clk);
            reset   = 0;
            repeat (5) @(posedge clk);
            captureData();       
            $finish;
        end
    `endif
    // VERIFY mode  
    // When operating in VERIFY mode, the testbench will read input and output pairs
    // and check that they behave as expected
    `ifdef VERIFY
        initial begin
            inData  = 0;
            reset   = 1;
            repeat (5) @(posedge clk);
            reset   = 0;
            repeat (5) @(posedge clk);
            // Display some status
            playbackData();       
            $finish;
        end
    `endif
    //
    // Task     : captureData
    // Funcion  : 
    //
    task captureData;
        // File Pointer 
        integer fp;
        // Loop variable
        integer i;
        
        begin
            // open file to store input/output
            $display("Capturing %0d samples into file %s", `NUM_SAMPLES, `CAPTURE_FILE);
            fp = $fopen(`CAPTURE_FILE, "w");
            // Generate NUM_SAMPLES random samples
            for (i = 0; i < `NUM_SAMPLES; i = i + 1) begin
                // Jump to positive edge of the clock
                @(posedge clk);
                // Generate a random 64-bit vector
                // A single $urandom call will only give up to 32-bits
                inData[63:32] = $urandom;
                inData[31:0]  = $urandom;
                // Write the random number to the capture file
                $fwrite(fp, "%016x_", inData);
                // Plan to capture the data at the negative clock edge
                @(negedge clk);
                // Write the output data
                $fwrite(fp, "%016x\n", outData);
            end
            // Close the capture file
            $fclose(fp);
        end
    endtask // end captureData
    //
    // Task     : playbackData
    // Funcion  : 
    //
    task playbackData;
        // Loop variable
        integer i;
        // Temporary buffer
        reg [`DATA_WIDTH*2 - 1 : 0] buffer[`NUM_SAMPLES - 1 : 0];
        // Hold the expected data for comparison
        reg [`DATA_WIDTH - 1:0] expData;
        begin
            // Display some status
            $display("Verifying %0d samples from file %s", `NUM_SAMPLES, `CAPTURE_FILE);
            // Read the samples data from the capture file
            $readmemh(`CAPTURE_FILE, buffer);
            // Read NUM_SAMPLES from file, stimulate the input, and compare to the expected output
            for (i = 0; i < `NUM_SAMPLES; i = i + 1) begin
                // Jump to positive edge of the clock
                @(posedge clk);
                // Extract data from the currently selected buffer
                {inData, expData}   = buffer[i];
                // Plan to capture the data at the negative clock edge
                @(negedge clk);
                // Compare expected vs actual output data
                if (outData != expData) begin
                    $display("ERROR: miscompared at sample %0d outData (exp/act) = %016x / %016x", i, expData, outData);
                    errCnt = errCnt + 1;
                end
            end     // end for
            //
            // print summary
            //
            if (errCnt) begin
                $display("==== TEST FAILED with %0d errors ====", errCnt);
            end else begin
                $display("==== TEST PASSED  ====");
            end
      
      end
    endtask // end captureData
endmodule   // end filter_tb | 
| 
	[//]: # (Copyright 2022 Massachusets Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   Copyright 2022 Massachusets Institute of Technology
</p>
## Auto-FIR Script
The auto-fir.py script generates a randomized variant of the filter as described here: [Spiral Project Filter Gen](http://www.spiral.net/hardware/filter.html)
Executing `auto-fir.py -h` will print a complete list of script options.
Simulation performs cycle level comparisons and assumes Modelsim/Questasim is in the current path.
Example usage:
```
  ./auto-fir.py -b -v -a    <-- Build the FIR generator (if not available) and 
                                generate a filter with default settings.  Verilog 
                                identifiers will be randomized
  ./auto-fir.py -sg -v      <-- With the filter built, generate a series of random 
                                test vectors and save the results
  ./auto-fir.py -sv -v      <-- Re-run the simulation and verify the vectors still pass
```
All generated files are implicitly included in .gitignore and are thus not tracked by git.
Caution should be taken when running the auto-fir.py script with the `--clean` or `--allclean` switches.  
The following files will be deleted with `--clean`:
```
    ./firgen/*
    ./synth/*
    ./outputs/*
    ./work/*
    ./__pycache__/*
    transcript
    *.firlog
```
If `--allclean` is specified, then following ADDITIONAL files will be deleted:
```
    firgen.tgz
    rm -f synth-jan-14-2009.tar.gz
```
## Ubuntu 18.04 note:
If running the build on Ubuntu 18.04, you'll need to ensure rthe Verilog-Perl module is installed.
This can be accomplished by running the following command:
```
sudo cpan install Verilog-Perl
```
#### Return to the root CEP [README](../../README.md)
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  CRP                                                        ////
////  DES Crypt Module                                           ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  crp(clk,reset, P, R, K_sub);
/* verilator lint_off LITENDIAN */
output [1:32] P;
input [1:32] R;
input [1:48] K_sub;
input reset;
input clk;
wire [1:48] E;
wire [1:48] X;
wire [1:32] S;
/* verilator lint_on LITENDIAN */
assign E[1:48] = { R[32], R[1], R[2], R[3], R[4], R[5], R[4], R[5],
                   R[6], R[7], R[8], R[9], R[8], R[9], R[10], R[11],
                   R[12], R[13], R[12], R[13], R[14], R[15], R[16],
                   R[17], R[16], R[17], R[18], R[19], R[20], R[21],
                   R[20], R[21], R[22], R[23], R[24], R[25], R[24],
                   R[25], R[26], R[27], R[28], R[29], R[28], R[29],
                   R[30], R[31], R[32], R[1]};
assign X = E ^ K_sub;
sbox1 u0( .addr(X[01:06]), .dout(S[01:04]) , .reset(reset), .clk(clk));
sbox2 u1( .addr(X[07:12]), .dout(S[05:08]) , .reset(reset), .clk(clk));
sbox3 u2( .addr(X[13:18]), .dout(S[09:12]) , .reset(reset), .clk(clk));
sbox4 u3( .addr(X[19:24]), .dout(S[13:16]) , .reset(reset), .clk(clk));
sbox5 u4( .addr(X[25:30]), .dout(S[17:20]) , .reset(reset), .clk(clk));
sbox6 u5( .addr(X[31:36]), .dout(S[21:24]) , .reset(reset), .clk(clk));
sbox7 u6( .addr(X[37:42]), .dout(S[25:28]) , .reset(reset), .clk(clk));
sbox8 u7( .addr(X[43:48]), .dout(S[29:32]) , .reset(reset), .clk(clk));
assign P[1:32] = { S[16], S[7], S[20], S[21], S[29], S[12], S[28],
                   S[17], S[1], S[15], S[23], S[26], S[5], S[18],
                   S[31], S[10], S[2], S[8], S[24], S[14], S[32],
                   S[27], S[3], S[9], S[19], S[13], S[30], S[6],
                   S[22], S[11], S[4], S[25]};
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  DES                                                        ////
////  DES Top Level module                                       ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module des3(clk, reset, desOut, out_valid, start, desIn, key1, key2, key3, decrypt);
output reg[63:0] desOut;
output           out_valid;
input            start;
input     [63:0] desIn;
input     [55:0] key1;
input     [55:0] key2;
input     [55:0] key3;
input            decrypt;
input            clk;
input            reset;
/* verilator lint_off LITENDIAN */
wire [1:48] K_sub;
wire [1:64] IP, FP;
reg  [1:64] FP_R;
reg  [1:32] L, R;
wire [1:32] Xin;
wire [1:32] Lout;
wire [1:32] Rout;
wire [1:32] out;
/* verilator lint_on LITENDIAN */
reg [5:0] roundSel;
reg start_r;
always @(posedge clk)
    begin
        if (reset)
          start_r <= 1'b0;
        else
          start_r <= start;
    end
wire start_posedge = start & ~start_r;
// tony duong 04/21/2020: not used at all so removed
//reg [7:0] validCounter;
wire [63:0] des;
always @ (posedge clk)
    begin
        if (reset | start_posedge)
            begin
                roundSel <= 6'h00;
            end
        else if(~out_valid)
            begin
                roundSel <= roundSel +1;
            end
    end
assign out_valid = (roundSel == 6'h30);
always @ (posedge clk)
    begin
        if (reset)
          begin
            desOut <= 64'h0000000000000000;
          end
        else if(!out_valid)
          begin
            desOut <= des;
          end
    end
crp u0(
        .clk(clk),
        .reset(reset),
        .P(out),
        .R(Lout),
        .K_sub(K_sub));
// Select a subkey from key.
key_sel3 u1(
             .clk(clk),
             .reset(reset),
             .K_sub(K_sub),
             .key1(key1),
             .key2(key2),
             .key3(key3),
             .roundSel(roundSel),
             .decrypt(decrypt)
         );
assign Lout = (roundSel ==  0) ? IP[33:64] : ((roundSel == 16) ? FP_R[33:64] : ((roundSel == 32) ? FP_R[33:64] : R));
assign Xin  = (roundSel ==  0) ? IP[01:32] : ((roundSel == 16) ? FP_R[01:32] : ((roundSel == 32) ? FP_R[01:32] : L));
assign Rout = Xin ^ out;
assign FP = { Rout, Lout};
always @(posedge clk)
  begin
    if (reset)
      begin
        FP_R <= 0;
        L <= 0;
        R <= 0;
      end 
    else
      begin
        L <= Lout;
        R <= Rout;
        FP_R <= FP;
      end
  end
// Perform initial permutation
assign IP[1:64] = {desIn[06], desIn[14], desIn[22], desIn[30], desIn[38], desIn[46],
                   desIn[54], desIn[62], desIn[04], desIn[12], desIn[20], desIn[28],
                   desIn[36], desIn[44], desIn[52], desIn[60], desIn[02], desIn[10],
                   desIn[18], desIn[26], desIn[34], desIn[42], desIn[50], desIn[58],
                   desIn[00], desIn[08], desIn[16], desIn[24], desIn[32], desIn[40],
                   desIn[48], desIn[56], desIn[07], desIn[15], desIn[23], desIn[31],
                   desIn[39], desIn[47], desIn[55], desIn[63], desIn[05], desIn[13],
                   desIn[21], desIn[29], desIn[37], desIn[45], desIn[53], desIn[61],
                   desIn[03], desIn[11], desIn[19], desIn[27], desIn[35], desIn[43],
                   desIn[51], desIn[59], desIn[01], desIn[09], desIn[17], desIn[25],
                   desIn[33], desIn[41], desIn[49], desIn[57] };
// Perform final permutation
assign des = {FP[40], FP[08], FP[48], FP[16], FP[56], FP[24], FP[64], FP[32],
              FP[39], FP[07], FP[47], FP[15], FP[55], FP[23], FP[63], FP[31],
              FP[38], FP[06], FP[46], FP[14], FP[54], FP[22], FP[62], FP[30],
              FP[37], FP[05], FP[45], FP[13], FP[53], FP[21], FP[61], FP[29],
              FP[36], FP[04], FP[44], FP[12], FP[52], FP[20], FP[60], FP[28],
              FP[35], FP[03], FP[43], FP[11], FP[51], FP[19], FP[59], FP[27],
              FP[34], FP[02], FP[42], FP[10], FP[50], FP[18], FP[58], FP[26],
              FP[33], FP[01], FP[41], FP[09], FP[49], FP[17], FP[57], FP[25] };
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       des3_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module des3_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst, 
    // Core I/O
    input wire            start,
    input wire [63:0]     desIn,
    input wire [55:0]     key1,
    input wire [55:0]     key2,
    input wire [55:0]     key3,
    input wire            decrypt,
    output wire [63:0]    desOut,
    output wire           out_valid,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = DES3_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [(64*KEY_WORDS) - 1:0]   mock_tss_desIn;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  genvar i;
  generate
    for (i = 0; i < KEY_WORDS; i = i + 1) begin
      assign mock_tss_desIn[64*i +: 64] = DES3_MOCK_TSS_KEY_WORDS[i] ^
                                          llkid_key_register[64*i +: 64] ^
                                          desIn[64*i +: 64];
    end
  endgenerate
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  des3 des3_inst (
    .clk          (clk),
    .reset        (rst),
    .start        (start),
    .desIn        (mock_tss_desIn),
    .key1         (key1),
    .key2         (key2),
    .key3         (key3),
    .decrypt      (decrypt),
    .desOut       (desOut),
    .out_valid    (out_valid)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  KEY_SEL                                                    ////
////  Select one of 16 sub-keys for round                        ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  key_sel3(clk, reset, K_sub, key1, key2, key3, roundSel, decrypt);
/* verilator lint_off LITENDIAN */
output [1:48] K_sub;
/* verilator lint_on LITENDIAN */
input [55:0] key1, key2, key3;
input [5:0] roundSel;
input  decrypt;
input clk;
input reset;
wire  decrypt_int;
reg [55:0] K;
reg [1:48] K_sub;
/* verilator lint_off LITENDIAN */
wire [1:48] K1, K2, K3, K4, K5, K6, K7, K8, K9;
wire [1:48] K10, K11, K12, K13, K14, K15, K16;
/* verilator lint_on LITENDIAN */
always @(clk)
    begin
        if (reset)
            K = 56'b0;
        else
    case ({decrypt, roundSel[5:4]})  // synopsys full_case parallel_case
        3'b0_00:
            K = key1;
        3'b0_01:
            K = key2;
        3'b0_10:
            K = key3;
        3'b1_00:
            K = key3;
        3'b1_01:
            K = key2;
        3'b1_10:
            K = key1;
        3'b0_11:
            K = 56'b0;
        3'b1_11:
            K = 56'b0;
    endcase
end
assign decrypt_int = (roundSel[5:4]==2'h1) ? !decrypt : decrypt;
always @(*)
    begin
            case(roundSel[3:0])  // synopsys full_case parallel_case
                0:
                    K_sub = K1;
                1:
                    K_sub = K2;
                2:
                    K_sub = K3;
                3:
                    K_sub = K4;
                4:
                    K_sub = K5;
                5:
                    K_sub = K6;
                6:
                    K_sub = K7;
                7:
                    K_sub = K8;
                8:
                    K_sub = K9;
                9:
                    K_sub = K10;
                10:
                    K_sub = K11;
                11:
                    K_sub = K12;
                12:
                    K_sub = K13;
                13:
                    K_sub = K14;
                14:
                    K_sub = K15;
                15:
                    K_sub = K16;
            endcase
    end
assign K16[1] = decrypt_int ? K[47] : K[40];
assign K16[2] = decrypt_int ? K[11] : K[4];
assign K16[3] = decrypt_int ? K[26] : K[19];
assign K16[4] = decrypt_int ? K[3] : K[53];
assign K16[5] = decrypt_int ? K[13] : K[6];
assign K16[6] = decrypt_int ? K[41] : K[34];
assign K16[7] = decrypt_int ? K[27] : K[20];
assign K16[8] = decrypt_int ? K[6] : K[24];
assign K16[9] = decrypt_int ? K[54] : K[47];
assign K16[10] = decrypt_int ? K[48] : K[41];
assign K16[11] = decrypt_int ? K[39] : K[32];
assign K16[12] = decrypt_int ? K[19] : K[12];
assign K16[13] = decrypt_int ? K[53] : K[46];
assign K16[14] = decrypt_int ? K[25] : K[18];
assign K16[15] = decrypt_int ? K[33] : K[26];
assign K16[16] = decrypt_int ? K[34] : K[27];
assign K16[17] = decrypt_int ? K[17] : K[10];
assign K16[18] = decrypt_int ? K[5] : K[55];
assign K16[19] = decrypt_int ? K[4] : K[54];
assign K16[20] = decrypt_int ? K[55] : K[48];
assign K16[21] = decrypt_int ? K[24] : K[17];
assign K16[22] = decrypt_int ? K[32] : K[25];
assign K16[23] = decrypt_int ? K[40] : K[33];
assign K16[24] = decrypt_int ? K[20] : K[13];
assign K16[25] = decrypt_int ? K[36] : K[29];
assign K16[26] = decrypt_int ? K[31] : K[51];
assign K16[27] = decrypt_int ? K[21] : K[14];
assign K16[28] = decrypt_int ? K[8] : K[1];
assign K16[29] = decrypt_int ? K[23] : K[16];
assign K16[30] = decrypt_int ? K[52] : K[45];
assign K16[31] = decrypt_int ? K[14] : K[7];
assign K16[32] = decrypt_int ? K[29] : K[22];
assign K16[33] = decrypt_int ? K[51] : K[44];
assign K16[34] = decrypt_int ? K[9] : K[2];
assign K16[35] = decrypt_int ? K[35] : K[28];
assign K16[36] = decrypt_int ? K[30] : K[23];
assign K16[37] = decrypt_int ? K[2] : K[50];
assign K16[38] = decrypt_int ? K[37] : K[30];
assign K16[39] = decrypt_int ? K[22] : K[15];
assign K16[40] = decrypt_int ? K[0] : K[52];
assign K16[41] = decrypt_int ? K[42] : K[35];
assign K16[42] = decrypt_int ? K[38] : K[31];
assign K16[43] = decrypt_int ? K[16] : K[9];
assign K16[44] = decrypt_int ? K[43] : K[36];
assign K16[45] = decrypt_int ? K[44] : K[37];
assign K16[46] = decrypt_int ? K[1] : K[49];
assign K16[47] = decrypt_int ? K[7] : K[0];
assign K16[48] = decrypt_int ? K[28] : K[21];
assign K15[1] = decrypt_int ? K[54] : K[33];
assign K15[2] = decrypt_int ? K[18] : K[54];
assign K15[3] = decrypt_int ? K[33] : K[12];
assign K15[4] = decrypt_int ? K[10] : K[46];
assign K15[5] = decrypt_int ? K[20] : K[24];
assign K15[6] = decrypt_int ? K[48] : K[27];
assign K15[7] = decrypt_int ? K[34] : K[13];
assign K15[8] = decrypt_int ? K[13] : K[17];
assign K15[9] = decrypt_int ? K[4] : K[40];
assign K15[10] = decrypt_int ? K[55] : K[34];
assign K15[11] = decrypt_int ? K[46] : K[25];
assign K15[12] = decrypt_int ? K[26] : K[5];
assign K15[13] = decrypt_int ? K[3] : K[39];
assign K15[14] = decrypt_int ? K[32] : K[11];
assign K15[15] = decrypt_int ? K[40] : K[19];
assign K15[16] = decrypt_int ? K[41] : K[20];
assign K15[17] = decrypt_int ? K[24] : K[3];
assign K15[18] = decrypt_int ? K[12] : K[48];
assign K15[19] = decrypt_int ? K[11] : K[47];
assign K15[20] = decrypt_int ? K[5] : K[41];
assign K15[21] = decrypt_int ? K[6] : K[10];
assign K15[22] = decrypt_int ? K[39] : K[18];
assign K15[23] = decrypt_int ? K[47] : K[26];
assign K15[24] = decrypt_int ? K[27] : K[6];
assign K15[25] = decrypt_int ? K[43] : K[22];
assign K15[26] = decrypt_int ? K[38] : K[44];
assign K15[27] = decrypt_int ? K[28] : K[7];
assign K15[28] = decrypt_int ? K[15] : K[49];
assign K15[29] = decrypt_int ? K[30] : K[9];
assign K15[30] = decrypt_int ? K[0] : K[38];
assign K15[31] = decrypt_int ? K[21] : K[0];
assign K15[32] = decrypt_int ? K[36] : K[15];
assign K15[33] = decrypt_int ? K[31] : K[37];
assign K15[34] = decrypt_int ? K[16] : K[50];
assign K15[35] = decrypt_int ? K[42] : K[21];
assign K15[36] = decrypt_int ? K[37] : K[16];
assign K15[37] = decrypt_int ? K[9] : K[43];
assign K15[38] = decrypt_int ? K[44] : K[23];
assign K15[39] = decrypt_int ? K[29] : K[8];
assign K15[40] = decrypt_int ? K[7] : K[45];
assign K15[41] = decrypt_int ? K[49] : K[28];
assign K15[42] = decrypt_int ? K[45] : K[51];
assign K15[43] = decrypt_int ? K[23] : K[2];
assign K15[44] = decrypt_int ? K[50] : K[29];
assign K15[45] = decrypt_int ? K[51] : K[30];
assign K15[46] = decrypt_int ? K[8] : K[42];
assign K15[47] = decrypt_int ? K[14] : K[52];
assign K15[48] = decrypt_int ? K[35] : K[14];
assign K14[1] = decrypt_int ? K[11] : K[19];
assign K14[2] = decrypt_int ? K[32] : K[40];
assign K14[3] = decrypt_int ? K[47] : K[55];
assign K14[4] = decrypt_int ? K[24] : K[32];
assign K14[5] = decrypt_int ? K[34] : K[10];
assign K14[6] = decrypt_int ? K[5] : K[13];
assign K14[7] = decrypt_int ? K[48] : K[24];
assign K14[8] = decrypt_int ? K[27] : K[3];
assign K14[9] = decrypt_int ? K[18] : K[26];
assign K14[10] = decrypt_int ? K[12] : K[20];
assign K14[11] = decrypt_int ? K[3] : K[11];
assign K14[12] = decrypt_int ? K[40] : K[48];
assign K14[13] = decrypt_int ? K[17] : K[25];
assign K14[14] = decrypt_int ? K[46] : K[54];
assign K14[15] = decrypt_int ? K[54] : K[5];
assign K14[16] = decrypt_int ? K[55] : K[6];
assign K14[17] = decrypt_int ? K[13] : K[46];
assign K14[18] = decrypt_int ? K[26] : K[34];
assign K14[19] = decrypt_int ? K[25] : K[33];
assign K14[20] = decrypt_int ? K[19] : K[27];
assign K14[21] = decrypt_int ? K[20] : K[53];
assign K14[22] = decrypt_int ? K[53] : K[4];
assign K14[23] = decrypt_int ? K[4] : K[12];
assign K14[24] = decrypt_int ? K[41] : K[17];
assign K14[25] = decrypt_int ? K[2] : K[8];
assign K14[26] = decrypt_int ? K[52] : K[30];
assign K14[27] = decrypt_int ? K[42] : K[52];
assign K14[28] = decrypt_int ? K[29] : K[35];
assign K14[29] = decrypt_int ? K[44] : K[50];
assign K14[30] = decrypt_int ? K[14] : K[51];
assign K14[31] = decrypt_int ? K[35] : K[45];
assign K14[32] = decrypt_int ? K[50] : K[1];
assign K14[33] = decrypt_int ? K[45] : K[23];
assign K14[34] = decrypt_int ? K[30] : K[36];
assign K14[35] = decrypt_int ? K[1] : K[7];
assign K14[36] = decrypt_int ? K[51] : K[2];
assign K14[37] = decrypt_int ? K[23] : K[29];
assign K14[38] = decrypt_int ? K[31] : K[9];
assign K14[39] = decrypt_int ? K[43] : K[49];
assign K14[40] = decrypt_int ? K[21] : K[31];
assign K14[41] = decrypt_int ? K[8] : K[14];
assign K14[42] = decrypt_int ? K[0] : K[37];
assign K14[43] = decrypt_int ? K[37] : K[43];
assign K14[44] = decrypt_int ? K[9] : K[15];
assign K14[45] = decrypt_int ? K[38] : K[16];
assign K14[46] = decrypt_int ? K[22] : K[28];
assign K14[47] = decrypt_int ? K[28] : K[38];
assign K14[48] = decrypt_int ? K[49] : K[0];
assign K13[1] = decrypt_int ? K[25] : K[5];
assign K13[2] = decrypt_int ? K[46] : K[26];
assign K13[3] = decrypt_int ? K[4] : K[41];
assign K13[4] = decrypt_int ? K[13] : K[18];
assign K13[5] = decrypt_int ? K[48] : K[53];
assign K13[6] = decrypt_int ? K[19] : K[24];
assign K13[7] = decrypt_int ? K[5] : K[10];
assign K13[8] = decrypt_int ? K[41] : K[46];
assign K13[9] = decrypt_int ? K[32] : K[12];
assign K13[10] = decrypt_int ? K[26] : K[6];
assign K13[11] = decrypt_int ? K[17] : K[54];
assign K13[12] = decrypt_int ? K[54] : K[34];
assign K13[13] = decrypt_int ? K[6] : K[11];
assign K13[14] = decrypt_int ? K[3] : K[40];
assign K13[15] = decrypt_int ? K[11] : K[48];
assign K13[16] = decrypt_int ? K[12] : K[17];
assign K13[17] = decrypt_int ? K[27] : K[32];
assign K13[18] = decrypt_int ? K[40] : K[20];
assign K13[19] = decrypt_int ? K[39] : K[19];
assign K13[20] = decrypt_int ? K[33] : K[13];
assign K13[21] = decrypt_int ? K[34] : K[39];
assign K13[22] = decrypt_int ? K[10] : K[47];
assign K13[23] = decrypt_int ? K[18] : K[55];
assign K13[24] = decrypt_int ? K[55] : K[3];
assign K13[25] = decrypt_int ? K[16] : K[49];
assign K13[26] = decrypt_int ? K[7] : K[16];
assign K13[27] = decrypt_int ? K[1] : K[38];
assign K13[28] = decrypt_int ? K[43] : K[21];
assign K13[29] = decrypt_int ? K[31] : K[36];
assign K13[30] = decrypt_int ? K[28] : K[37];
assign K13[31] = decrypt_int ? K[49] : K[31];
assign K13[32] = decrypt_int ? K[9] : K[42];
assign K13[33] = decrypt_int ? K[0] : K[9];
assign K13[34] = decrypt_int ? K[44] : K[22];
assign K13[35] = decrypt_int ? K[15] : K[52];
assign K13[36] = decrypt_int ? K[38] : K[43];
assign K13[37] = decrypt_int ? K[37] : K[15];
assign K13[38] = decrypt_int ? K[45] : K[50];
assign K13[39] = decrypt_int ? K[2] : K[35];
assign K13[40] = decrypt_int ? K[35] : K[44];
assign K13[41] = decrypt_int ? K[22] : K[0];
assign K13[42] = decrypt_int ? K[14] : K[23];
assign K13[43] = decrypt_int ? K[51] : K[29];
assign K13[44] = decrypt_int ? K[23] : K[1];
assign K13[45] = decrypt_int ? K[52] : K[2];
assign K13[46] = decrypt_int ? K[36] : K[14];
assign K13[47] = decrypt_int ? K[42] : K[51];
assign K13[48] = decrypt_int ? K[8] : K[45];
assign K12[1] = decrypt_int ? K[39] : K[48];
assign K12[2] = decrypt_int ? K[3] : K[12];
assign K12[3] = decrypt_int ? K[18] : K[27];
assign K12[4] = decrypt_int ? K[27] : K[4];
assign K12[5] = decrypt_int ? K[5] : K[39];
assign K12[6] = decrypt_int ? K[33] : K[10];
assign K12[7] = decrypt_int ? K[19] : K[53];
assign K12[8] = decrypt_int ? K[55] : K[32];
assign K12[9] = decrypt_int ? K[46] : K[55];
assign K12[10] = decrypt_int ? K[40] : K[17];
assign K12[11] = decrypt_int ? K[6] : K[40];
assign K12[12] = decrypt_int ? K[11] : K[20];
assign K12[13] = decrypt_int ? K[20] : K[54];
assign K12[14] = decrypt_int ? K[17] : K[26];
assign K12[15] = decrypt_int ? K[25] : K[34];
assign K12[16] = decrypt_int ? K[26] : K[3];
assign K12[17] = decrypt_int ? K[41] : K[18];
assign K12[18] = decrypt_int ? K[54] : K[6];
assign K12[19] = decrypt_int ? K[53] : K[5];
assign K12[20] = decrypt_int ? K[47] : K[24];
assign K12[21] = decrypt_int ? K[48] : K[25];
assign K12[22] = decrypt_int ? K[24] : K[33];
assign K12[23] = decrypt_int ? K[32] : K[41];
assign K12[24] = decrypt_int ? K[12] : K[46];
assign K12[25] = decrypt_int ? K[30] : K[35];
assign K12[26] = decrypt_int ? K[21] : K[2];
assign K12[27] = decrypt_int ? K[15] : K[51];
assign K12[28] = decrypt_int ? K[2] : K[7];
assign K12[29] = decrypt_int ? K[45] : K[22];
assign K12[30] = decrypt_int ? K[42] : K[23];
assign K12[31] = decrypt_int ? K[8] : K[44];
assign K12[32] = decrypt_int ? K[23] : K[28];
assign K12[33] = decrypt_int ? K[14] : K[50];
assign K12[34] = decrypt_int ? K[31] : K[8];
assign K12[35] = decrypt_int ? K[29] : K[38];
assign K12[36] = decrypt_int ? K[52] : K[29];
assign K12[37] = decrypt_int ? K[51] : K[1];
assign K12[38] = decrypt_int ? K[0] : K[36];
assign K12[39] = decrypt_int ? K[16] : K[21];
assign K12[40] = decrypt_int ? K[49] : K[30];
assign K12[41] = decrypt_int ? K[36] : K[45];
assign K12[42] = decrypt_int ? K[28] : K[9];
assign K12[43] = decrypt_int ? K[38] : K[15];
assign K12[44] = decrypt_int ? K[37] : K[42];
assign K12[45] = decrypt_int ? K[7] : K[43];
assign K12[46] = decrypt_int ? K[50] : K[0];
assign K12[47] = decrypt_int ? K[1] : K[37];
assign K12[48] = decrypt_int ? K[22] : K[31];
assign K11[1] = decrypt_int ? K[53] : K[34];
assign K11[2] = decrypt_int ? K[17] : K[55];
assign K11[3] = decrypt_int ? K[32] : K[13];
assign K11[4] = decrypt_int ? K[41] : K[47];
assign K11[5] = decrypt_int ? K[19] : K[25];
assign K11[6] = decrypt_int ? K[47] : K[53];
assign K11[7] = decrypt_int ? K[33] : K[39];
assign K11[8] = decrypt_int ? K[12] : K[18];
assign K11[9] = decrypt_int ? K[3] : K[41];
assign K11[10] = decrypt_int ? K[54] : K[3];
assign K11[11] = decrypt_int ? K[20] : K[26];
assign K11[12] = decrypt_int ? K[25] : K[6];
assign K11[13] = decrypt_int ? K[34] : K[40];
assign K11[14] = decrypt_int ? K[6] : K[12];
assign K11[15] = decrypt_int ? K[39] : K[20];
assign K11[16] = decrypt_int ? K[40] : K[46];
assign K11[17] = decrypt_int ? K[55] : K[4];
assign K11[18] = decrypt_int ? K[11] : K[17];
assign K11[19] = decrypt_int ? K[10] : K[48];
assign K11[20] = decrypt_int ? K[4] : K[10];
assign K11[21] = decrypt_int ? K[5] : K[11];
assign K11[22] = decrypt_int ? K[13] : K[19];
assign K11[23] = decrypt_int ? K[46] : K[27];
assign K11[24] = decrypt_int ? K[26] : K[32];
assign K11[25] = decrypt_int ? K[44] : K[21];
assign K11[26] = decrypt_int ? K[35] : K[43];
assign K11[27] = decrypt_int ? K[29] : K[37];
assign K11[28] = decrypt_int ? K[16] : K[52];
assign K11[29] = decrypt_int ? K[0] : K[8];
assign K11[30] = decrypt_int ? K[1] : K[9];
assign K11[31] = decrypt_int ? K[22] : K[30];
assign K11[32] = decrypt_int ? K[37] : K[14];
assign K11[33] = decrypt_int ? K[28] : K[36];
assign K11[34] = decrypt_int ? K[45] : K[49];
assign K11[35] = decrypt_int ? K[43] : K[51];
assign K11[36] = decrypt_int ? K[7] : K[15];
assign K11[37] = decrypt_int ? K[38] : K[42];
assign K11[38] = decrypt_int ? K[14] : K[22];
assign K11[39] = decrypt_int ? K[30] : K[7];
assign K11[40] = decrypt_int ? K[8] : K[16];
assign K11[41] = decrypt_int ? K[50] : K[31];
assign K11[42] = decrypt_int ? K[42] : K[50];
assign K11[43] = decrypt_int ? K[52] : K[1];
assign K11[44] = decrypt_int ? K[51] : K[28];
assign K11[45] = decrypt_int ? K[21] : K[29];
assign K11[46] = decrypt_int ? K[9] : K[45];
assign K11[47] = decrypt_int ? K[15] : K[23];
assign K11[48] = decrypt_int ? K[36] : K[44];
assign K10[1] = decrypt_int ? K[10] : K[20];
assign K10[2] = decrypt_int ? K[6] : K[41];
assign K10[3] = decrypt_int ? K[46] : K[24];
assign K10[4] = decrypt_int ? K[55] : K[33];
assign K10[5] = decrypt_int ? K[33] : K[11];
assign K10[6] = decrypt_int ? K[4] : K[39];
assign K10[7] = decrypt_int ? K[47] : K[25];
assign K10[8] = decrypt_int ? K[26] : K[4];
assign K10[9] = decrypt_int ? K[17] : K[27];
assign K10[10] = decrypt_int ? K[11] : K[46];
assign K10[11] = decrypt_int ? K[34] : K[12];
assign K10[12] = decrypt_int ? K[39] : K[17];
assign K10[13] = decrypt_int ? K[48] : K[26];
assign K10[14] = decrypt_int ? K[20] : K[55];
assign K10[15] = decrypt_int ? K[53] : K[6];
assign K10[16] = decrypt_int ? K[54] : K[32];
assign K10[17] = decrypt_int ? K[12] : K[47];
assign K10[18] = decrypt_int ? K[25] : K[3];
assign K10[19] = decrypt_int ? K[24] : K[34];
assign K10[20] = decrypt_int ? K[18] : K[53];
assign K10[21] = decrypt_int ? K[19] : K[54];
assign K10[22] = decrypt_int ? K[27] : K[5];
assign K10[23] = decrypt_int ? K[3] : K[13];
assign K10[24] = decrypt_int ? K[40] : K[18];
assign K10[25] = decrypt_int ? K[31] : K[7];
assign K10[26] = decrypt_int ? K[49] : K[29];
assign K10[27] = decrypt_int ? K[43] : K[23];
assign K10[28] = decrypt_int ? K[30] : K[38];
assign K10[29] = decrypt_int ? K[14] : K[49];
assign K10[30] = decrypt_int ? K[15] : K[50];
assign K10[31] = decrypt_int ? K[36] : K[16];
assign K10[32] = decrypt_int ? K[51] : K[0];
assign K10[33] = decrypt_int ? K[42] : K[22];
assign K10[34] = decrypt_int ? K[0] : K[35];
assign K10[35] = decrypt_int ? K[2] : K[37];
assign K10[36] = decrypt_int ? K[21] : K[1];
assign K10[37] = decrypt_int ? K[52] : K[28];
assign K10[38] = decrypt_int ? K[28] : K[8];
assign K10[39] = decrypt_int ? K[44] : K[52];
assign K10[40] = decrypt_int ? K[22] : K[2];
assign K10[41] = decrypt_int ? K[9] : K[44];
assign K10[42] = decrypt_int ? K[1] : K[36];
assign K10[43] = decrypt_int ? K[7] : K[42];
assign K10[44] = decrypt_int ? K[38] : K[14];
assign K10[45] = decrypt_int ? K[35] : K[15];
assign K10[46] = decrypt_int ? K[23] : K[31];
assign K10[47] = decrypt_int ? K[29] : K[9];
assign K10[48] = decrypt_int ? K[50] : K[30];
assign K9[1] = decrypt_int ? K[24] : K[6];
assign K9[2] = decrypt_int ? K[20] : K[27];
assign K9[3] = decrypt_int ? K[3] : K[10];
assign K9[4] = decrypt_int ? K[12] : K[19];
assign K9[5] = decrypt_int ? K[47] : K[54];
assign K9[6] = decrypt_int ? K[18] : K[25];
assign K9[7] = decrypt_int ? K[4] : K[11];
assign K9[8] = decrypt_int ? K[40] : K[47];
assign K9[9] = decrypt_int ? K[6] : K[13];
assign K9[10] = decrypt_int ? K[25] : K[32];
assign K9[11] = decrypt_int ? K[48] : K[55];
assign K9[12] = decrypt_int ? K[53] : K[3];
assign K9[13] = decrypt_int ? K[5] : K[12];
assign K9[14] = decrypt_int ? K[34] : K[41];
assign K9[15] = decrypt_int ? K[10] : K[17];
assign K9[16] = decrypt_int ? K[11] : K[18];
assign K9[17] = decrypt_int ? K[26] : K[33];
assign K9[18] = decrypt_int ? K[39] : K[46];
assign K9[19] = decrypt_int ? K[13] : K[20];
assign K9[20] = decrypt_int ? K[32] : K[39];
assign K9[21] = decrypt_int ? K[33] : K[40];
assign K9[22] = decrypt_int ? K[41] : K[48];
assign K9[23] = decrypt_int ? K[17] : K[24];
assign K9[24] = decrypt_int ? K[54] : K[4];
assign K9[25] = decrypt_int ? K[45] : K[52];
assign K9[26] = decrypt_int ? K[8] : K[15];
assign K9[27] = decrypt_int ? K[2] : K[9];
assign K9[28] = decrypt_int ? K[44] : K[51];
assign K9[29] = decrypt_int ? K[28] : K[35];
assign K9[30] = decrypt_int ? K[29] : K[36];
assign K9[31] = decrypt_int ? K[50] : K[2];
assign K9[32] = decrypt_int ? K[38] : K[45];
assign K9[33] = decrypt_int ? K[1] : K[8];
assign K9[34] = decrypt_int ? K[14] : K[21];
assign K9[35] = decrypt_int ? K[16] : K[23];
assign K9[36] = decrypt_int ? K[35] : K[42];
assign K9[37] = decrypt_int ? K[7] : K[14];
assign K9[38] = decrypt_int ? K[42] : K[49];
assign K9[39] = decrypt_int ? K[31] : K[38];
assign K9[40] = decrypt_int ? K[36] : K[43];
assign K9[41] = decrypt_int ? K[23] : K[30];
assign K9[42] = decrypt_int ? K[15] : K[22];
assign K9[43] = decrypt_int ? K[21] : K[28];
assign K9[44] = decrypt_int ? K[52] : K[0];
assign K9[45] = decrypt_int ? K[49] : K[1];
assign K9[46] = decrypt_int ? K[37] : K[44];
assign K9[47] = decrypt_int ? K[43] : K[50];
assign K9[48] = decrypt_int ? K[9] : K[16];
assign K8[1] = decrypt_int ? K[6] : K[24];
assign K8[2] = decrypt_int ? K[27] : K[20];
assign K8[3] = decrypt_int ? K[10] : K[3];
assign K8[4] = decrypt_int ? K[19] : K[12];
assign K8[5] = decrypt_int ? K[54] : K[47];
assign K8[6] = decrypt_int ? K[25] : K[18];
assign K8[7] = decrypt_int ? K[11] : K[4];
assign K8[8] = decrypt_int ? K[47] : K[40];
assign K8[9] = decrypt_int ? K[13] : K[6];
assign K8[10] = decrypt_int ? K[32] : K[25];
assign K8[11] = decrypt_int ? K[55] : K[48];
assign K8[12] = decrypt_int ? K[3] : K[53];
assign K8[13] = decrypt_int ? K[12] : K[5];
assign K8[14] = decrypt_int ? K[41] : K[34];
assign K8[15] = decrypt_int ? K[17] : K[10];
assign K8[16] = decrypt_int ? K[18] : K[11];
assign K8[17] = decrypt_int ? K[33] : K[26];
assign K8[18] = decrypt_int ? K[46] : K[39];
assign K8[19] = decrypt_int ? K[20] : K[13];
assign K8[20] = decrypt_int ? K[39] : K[32];
assign K8[21] = decrypt_int ? K[40] : K[33];
assign K8[22] = decrypt_int ? K[48] : K[41];
assign K8[23] = decrypt_int ? K[24] : K[17];
assign K8[24] = decrypt_int ? K[4] : K[54];
assign K8[25] = decrypt_int ? K[52] : K[45];
assign K8[26] = decrypt_int ? K[15] : K[8];
assign K8[27] = decrypt_int ? K[9] : K[2];
assign K8[28] = decrypt_int ? K[51] : K[44];
assign K8[29] = decrypt_int ? K[35] : K[28];
assign K8[30] = decrypt_int ? K[36] : K[29];
assign K8[31] = decrypt_int ? K[2] : K[50];
assign K8[32] = decrypt_int ? K[45] : K[38];
assign K8[33] = decrypt_int ? K[8] : K[1];
assign K8[34] = decrypt_int ? K[21] : K[14];
assign K8[35] = decrypt_int ? K[23] : K[16];
assign K8[36] = decrypt_int ? K[42] : K[35];
assign K8[37] = decrypt_int ? K[14] : K[7];
assign K8[38] = decrypt_int ? K[49] : K[42];
assign K8[39] = decrypt_int ? K[38] : K[31];
assign K8[40] = decrypt_int ? K[43] : K[36];
assign K8[41] = decrypt_int ? K[30] : K[23];
assign K8[42] = decrypt_int ? K[22] : K[15];
assign K8[43] = decrypt_int ? K[28] : K[21];
assign K8[44] = decrypt_int ? K[0] : K[52];
assign K8[45] = decrypt_int ? K[1] : K[49];
assign K8[46] = decrypt_int ? K[44] : K[37];
assign K8[47] = decrypt_int ? K[50] : K[43];
assign K8[48] = decrypt_int ? K[16] : K[9];
assign K7[1] = decrypt_int ? K[20] : K[10];
assign K7[2] = decrypt_int ? K[41] : K[6];
assign K7[3] = decrypt_int ? K[24] : K[46];
assign K7[4] = decrypt_int ? K[33] : K[55];
assign K7[5] = decrypt_int ? K[11] : K[33];
assign K7[6] = decrypt_int ? K[39] : K[4];
assign K7[7] = decrypt_int ? K[25] : K[47];
assign K7[8] = decrypt_int ? K[4] : K[26];
assign K7[9] = decrypt_int ? K[27] : K[17];
assign K7[10] = decrypt_int ? K[46] : K[11];
assign K7[11] = decrypt_int ? K[12] : K[34];
assign K7[12] = decrypt_int ? K[17] : K[39];
assign K7[13] = decrypt_int ? K[26] : K[48];
assign K7[14] = decrypt_int ? K[55] : K[20];
assign K7[15] = decrypt_int ? K[6] : K[53];
assign K7[16] = decrypt_int ? K[32] : K[54];
assign K7[17] = decrypt_int ? K[47] : K[12];
assign K7[18] = decrypt_int ? K[3] : K[25];
assign K7[19] = decrypt_int ? K[34] : K[24];
assign K7[20] = decrypt_int ? K[53] : K[18];
assign K7[21] = decrypt_int ? K[54] : K[19];
assign K7[22] = decrypt_int ? K[5] : K[27];
assign K7[23] = decrypt_int ? K[13] : K[3];
assign K7[24] = decrypt_int ? K[18] : K[40];
assign K7[25] = decrypt_int ? K[7] : K[31];
assign K7[26] = decrypt_int ? K[29] : K[49];
assign K7[27] = decrypt_int ? K[23] : K[43];
assign K7[28] = decrypt_int ? K[38] : K[30];
assign K7[29] = decrypt_int ? K[49] : K[14];
assign K7[30] = decrypt_int ? K[50] : K[15];
assign K7[31] = decrypt_int ? K[16] : K[36];
assign K7[32] = decrypt_int ? K[0] : K[51];
assign K7[33] = decrypt_int ? K[22] : K[42];
assign K7[34] = decrypt_int ? K[35] : K[0];
assign K7[35] = decrypt_int ? K[37] : K[2];
assign K7[36] = decrypt_int ? K[1] : K[21];
assign K7[37] = decrypt_int ? K[28] : K[52];
assign K7[38] = decrypt_int ? K[8] : K[28];
assign K7[39] = decrypt_int ? K[52] : K[44];
assign K7[40] = decrypt_int ? K[2] : K[22];
assign K7[41] = decrypt_int ? K[44] : K[9];
assign K7[42] = decrypt_int ? K[36] : K[1];
assign K7[43] = decrypt_int ? K[42] : K[7];
assign K7[44] = decrypt_int ? K[14] : K[38];
assign K7[45] = decrypt_int ? K[15] : K[35];
assign K7[46] = decrypt_int ? K[31] : K[23];
assign K7[47] = decrypt_int ? K[9] : K[29];
assign K7[48] = decrypt_int ? K[30] : K[50];
assign K6[1] = decrypt_int ? K[34] : K[53];
assign K6[2] = decrypt_int ? K[55] : K[17];
assign K6[3] = decrypt_int ? K[13] : K[32];
assign K6[4] = decrypt_int ? K[47] : K[41];
assign K6[5] = decrypt_int ? K[25] : K[19];
assign K6[6] = decrypt_int ? K[53] : K[47];
assign K6[7] = decrypt_int ? K[39] : K[33];
assign K6[8] = decrypt_int ? K[18] : K[12];
assign K6[9] = decrypt_int ? K[41] : K[3];
assign K6[10] = decrypt_int ? K[3] : K[54];
assign K6[11] = decrypt_int ? K[26] : K[20];
assign K6[12] = decrypt_int ? K[6] : K[25];
assign K6[13] = decrypt_int ? K[40] : K[34];
assign K6[14] = decrypt_int ? K[12] : K[6];
assign K6[15] = decrypt_int ? K[20] : K[39];
assign K6[16] = decrypt_int ? K[46] : K[40];
assign K6[17] = decrypt_int ? K[4] : K[55];
assign K6[18] = decrypt_int ? K[17] : K[11];
assign K6[19] = decrypt_int ? K[48] : K[10];
assign K6[20] = decrypt_int ? K[10] : K[4];
assign K6[21] = decrypt_int ? K[11] : K[5];
assign K6[22] = decrypt_int ? K[19] : K[13];
assign K6[23] = decrypt_int ? K[27] : K[46];
assign K6[24] = decrypt_int ? K[32] : K[26];
assign K6[25] = decrypt_int ? K[21] : K[44];
assign K6[26] = decrypt_int ? K[43] : K[35];
assign K6[27] = decrypt_int ? K[37] : K[29];
assign K6[28] = decrypt_int ? K[52] : K[16];
assign K6[29] = decrypt_int ? K[8] : K[0];
assign K6[30] = decrypt_int ? K[9] : K[1];
assign K6[31] = decrypt_int ? K[30] : K[22];
assign K6[32] = decrypt_int ? K[14] : K[37];
assign K6[33] = decrypt_int ? K[36] : K[28];
assign K6[34] = decrypt_int ? K[49] : K[45];
assign K6[35] = decrypt_int ? K[51] : K[43];
assign K6[36] = decrypt_int ? K[15] : K[7];
assign K6[37] = decrypt_int ? K[42] : K[38];
assign K6[38] = decrypt_int ? K[22] : K[14];
assign K6[39] = decrypt_int ? K[7] : K[30];
assign K6[40] = decrypt_int ? K[16] : K[8];
assign K6[41] = decrypt_int ? K[31] : K[50];
assign K6[42] = decrypt_int ? K[50] : K[42];
assign K6[43] = decrypt_int ? K[1] : K[52];
assign K6[44] = decrypt_int ? K[28] : K[51];
assign K6[45] = decrypt_int ? K[29] : K[21];
assign K6[46] = decrypt_int ? K[45] : K[9];
assign K6[47] = decrypt_int ? K[23] : K[15];
assign K6[48] = decrypt_int ? K[44] : K[36];
assign K5[1] = decrypt_int ? K[48] : K[39];
assign K5[2] = decrypt_int ? K[12] : K[3];
assign K5[3] = decrypt_int ? K[27] : K[18];
assign K5[4] = decrypt_int ? K[4] : K[27];
assign K5[5] = decrypt_int ? K[39] : K[5];
assign K5[6] = decrypt_int ? K[10] : K[33];
assign K5[7] = decrypt_int ? K[53] : K[19];
assign K5[8] = decrypt_int ? K[32] : K[55];
assign K5[9] = decrypt_int ? K[55] : K[46];
assign K5[10] = decrypt_int ? K[17] : K[40];
assign K5[11] = decrypt_int ? K[40] : K[6];
assign K5[12] = decrypt_int ? K[20] : K[11];
assign K5[13] = decrypt_int ? K[54] : K[20];
assign K5[14] = decrypt_int ? K[26] : K[17];
assign K5[15] = decrypt_int ? K[34] : K[25];
assign K5[16] = decrypt_int ? K[3] : K[26];
assign K5[17] = decrypt_int ? K[18] : K[41];
assign K5[18] = decrypt_int ? K[6] : K[54];
assign K5[19] = decrypt_int ? K[5] : K[53];
assign K5[20] = decrypt_int ? K[24] : K[47];
assign K5[21] = decrypt_int ? K[25] : K[48];
assign K5[22] = decrypt_int ? K[33] : K[24];
assign K5[23] = decrypt_int ? K[41] : K[32];
assign K5[24] = decrypt_int ? K[46] : K[12];
assign K5[25] = decrypt_int ? K[35] : K[30];
assign K5[26] = decrypt_int ? K[2] : K[21];
assign K5[27] = decrypt_int ? K[51] : K[15];
assign K5[28] = decrypt_int ? K[7] : K[2];
assign K5[29] = decrypt_int ? K[22] : K[45];
assign K5[30] = decrypt_int ? K[23] : K[42];
assign K5[31] = decrypt_int ? K[44] : K[8];
assign K5[32] = decrypt_int ? K[28] : K[23];
assign K5[33] = decrypt_int ? K[50] : K[14];
assign K5[34] = decrypt_int ? K[8] : K[31];
assign K5[35] = decrypt_int ? K[38] : K[29];
assign K5[36] = decrypt_int ? K[29] : K[52];
assign K5[37] = decrypt_int ? K[1] : K[51];
assign K5[38] = decrypt_int ? K[36] : K[0];
assign K5[39] = decrypt_int ? K[21] : K[16];
assign K5[40] = decrypt_int ? K[30] : K[49];
assign K5[41] = decrypt_int ? K[45] : K[36];
assign K5[42] = decrypt_int ? K[9] : K[28];
assign K5[43] = decrypt_int ? K[15] : K[38];
assign K5[44] = decrypt_int ? K[42] : K[37];
assign K5[45] = decrypt_int ? K[43] : K[7];
assign K5[46] = decrypt_int ? K[0] : K[50];
assign K5[47] = decrypt_int ? K[37] : K[1];
assign K5[48] = decrypt_int ? K[31] : K[22];
assign K4[1] = decrypt_int ? K[5] : K[25];
assign K4[2] = decrypt_int ? K[26] : K[46];
assign K4[3] = decrypt_int ? K[41] : K[4];
assign K4[4] = decrypt_int ? K[18] : K[13];
assign K4[5] = decrypt_int ? K[53] : K[48];
assign K4[6] = decrypt_int ? K[24] : K[19];
assign K4[7] = decrypt_int ? K[10] : K[5];
assign K4[8] = decrypt_int ? K[46] : K[41];
assign K4[9] = decrypt_int ? K[12] : K[32];
assign K4[10] = decrypt_int ? K[6] : K[26];
assign K4[11] = decrypt_int ? K[54] : K[17];
assign K4[12] = decrypt_int ? K[34] : K[54];
assign K4[13] = decrypt_int ? K[11] : K[6];
assign K4[14] = decrypt_int ? K[40] : K[3];
assign K4[15] = decrypt_int ? K[48] : K[11];
assign K4[16] = decrypt_int ? K[17] : K[12];
assign K4[17] = decrypt_int ? K[32] : K[27];
assign K4[18] = decrypt_int ? K[20] : K[40];
assign K4[19] = decrypt_int ? K[19] : K[39];
assign K4[20] = decrypt_int ? K[13] : K[33];
assign K4[21] = decrypt_int ? K[39] : K[34];
assign K4[22] = decrypt_int ? K[47] : K[10];
assign K4[23] = decrypt_int ? K[55] : K[18];
assign K4[24] = decrypt_int ? K[3] : K[55];
assign K4[25] = decrypt_int ? K[49] : K[16];
assign K4[26] = decrypt_int ? K[16] : K[7];
assign K4[27] = decrypt_int ? K[38] : K[1];
assign K4[28] = decrypt_int ? K[21] : K[43];
assign K4[29] = decrypt_int ? K[36] : K[31];
assign K4[30] = decrypt_int ? K[37] : K[28];
assign K4[31] = decrypt_int ? K[31] : K[49];
assign K4[32] = decrypt_int ? K[42] : K[9];
assign K4[33] = decrypt_int ? K[9] : K[0];
assign K4[34] = decrypt_int ? K[22] : K[44];
assign K4[35] = decrypt_int ? K[52] : K[15];
assign K4[36] = decrypt_int ? K[43] : K[38];
assign K4[37] = decrypt_int ? K[15] : K[37];
assign K4[38] = decrypt_int ? K[50] : K[45];
assign K4[39] = decrypt_int ? K[35] : K[2];
assign K4[40] = decrypt_int ? K[44] : K[35];
assign K4[41] = decrypt_int ? K[0] : K[22];
assign K4[42] = decrypt_int ? K[23] : K[14];
assign K4[43] = decrypt_int ? K[29] : K[51];
assign K4[44] = decrypt_int ? K[1] : K[23];
assign K4[45] = decrypt_int ? K[2] : K[52];
assign K4[46] = decrypt_int ? K[14] : K[36];
assign K4[47] = decrypt_int ? K[51] : K[42];
assign K4[48] = decrypt_int ? K[45] : K[8];
assign K3[1] = decrypt_int ? K[19] : K[11];
assign K3[2] = decrypt_int ? K[40] : K[32];
assign K3[3] = decrypt_int ? K[55] : K[47];
assign K3[4] = decrypt_int ? K[32] : K[24];
assign K3[5] = decrypt_int ? K[10] : K[34];
assign K3[6] = decrypt_int ? K[13] : K[5];
assign K3[7] = decrypt_int ? K[24] : K[48];
assign K3[8] = decrypt_int ? K[3] : K[27];
assign K3[9] = decrypt_int ? K[26] : K[18];
assign K3[10] = decrypt_int ? K[20] : K[12];
assign K3[11] = decrypt_int ? K[11] : K[3];
assign K3[12] = decrypt_int ? K[48] : K[40];
assign K3[13] = decrypt_int ? K[25] : K[17];
assign K3[14] = decrypt_int ? K[54] : K[46];
assign K3[15] = decrypt_int ? K[5] : K[54];
assign K3[16] = decrypt_int ? K[6] : K[55];
assign K3[17] = decrypt_int ? K[46] : K[13];
assign K3[18] = decrypt_int ? K[34] : K[26];
assign K3[19] = decrypt_int ? K[33] : K[25];
assign K3[20] = decrypt_int ? K[27] : K[19];
assign K3[21] = decrypt_int ? K[53] : K[20];
assign K3[22] = decrypt_int ? K[4] : K[53];
assign K3[23] = decrypt_int ? K[12] : K[4];
assign K3[24] = decrypt_int ? K[17] : K[41];
assign K3[25] = decrypt_int ? K[8] : K[2];
assign K3[26] = decrypt_int ? K[30] : K[52];
assign K3[27] = decrypt_int ? K[52] : K[42];
assign K3[28] = decrypt_int ? K[35] : K[29];
assign K3[29] = decrypt_int ? K[50] : K[44];
assign K3[30] = decrypt_int ? K[51] : K[14];
assign K3[31] = decrypt_int ? K[45] : K[35];
assign K3[32] = decrypt_int ? K[1] : K[50];
assign K3[33] = decrypt_int ? K[23] : K[45];
assign K3[34] = decrypt_int ? K[36] : K[30];
assign K3[35] = decrypt_int ? K[7] : K[1];
assign K3[36] = decrypt_int ? K[2] : K[51];
assign K3[37] = decrypt_int ? K[29] : K[23];
assign K3[38] = decrypt_int ? K[9] : K[31];
assign K3[39] = decrypt_int ? K[49] : K[43];
assign K3[40] = decrypt_int ? K[31] : K[21];
assign K3[41] = decrypt_int ? K[14] : K[8];
assign K3[42] = decrypt_int ? K[37] : K[0];
assign K3[43] = decrypt_int ? K[43] : K[37];
assign K3[44] = decrypt_int ? K[15] : K[9];
assign K3[45] = decrypt_int ? K[16] : K[38];
assign K3[46] = decrypt_int ? K[28] : K[22];
assign K3[47] = decrypt_int ? K[38] : K[28];
assign K3[48] = decrypt_int ? K[0] : K[49];
assign K2[1] = decrypt_int ? K[33] : K[54];
assign K2[2] = decrypt_int ? K[54] : K[18];
assign K2[3] = decrypt_int ? K[12] : K[33];
assign K2[4] = decrypt_int ? K[46] : K[10];
assign K2[5] = decrypt_int ? K[24] : K[20];
assign K2[6] = decrypt_int ? K[27] : K[48];
assign K2[7] = decrypt_int ? K[13] : K[34];
assign K2[8] = decrypt_int ? K[17] : K[13];
assign K2[9] = decrypt_int ? K[40] : K[4];
assign K2[10] = decrypt_int ? K[34] : K[55];
assign K2[11] = decrypt_int ? K[25] : K[46];
assign K2[12] = decrypt_int ? K[5] : K[26];
assign K2[13] = decrypt_int ? K[39] : K[3];
assign K2[14] = decrypt_int ? K[11] : K[32];
assign K2[15] = decrypt_int ? K[19] : K[40];
assign K2[16] = decrypt_int ? K[20] : K[41];
assign K2[17] = decrypt_int ? K[3] : K[24];
assign K2[18] = decrypt_int ? K[48] : K[12];
assign K2[19] = decrypt_int ? K[47] : K[11];
assign K2[20] = decrypt_int ? K[41] : K[5];
assign K2[21] = decrypt_int ? K[10] : K[6];
assign K2[22] = decrypt_int ? K[18] : K[39];
assign K2[23] = decrypt_int ? K[26] : K[47];
assign K2[24] = decrypt_int ? K[6] : K[27];
assign K2[25] = decrypt_int ? K[22] : K[43];
assign K2[26] = decrypt_int ? K[44] : K[38];
assign K2[27] = decrypt_int ? K[7] : K[28];
assign K2[28] = decrypt_int ? K[49] : K[15];
assign K2[29] = decrypt_int ? K[9] : K[30];
assign K2[30] = decrypt_int ? K[38] : K[0];
assign K2[31] = decrypt_int ? K[0] : K[21];
assign K2[32] = decrypt_int ? K[15] : K[36];
assign K2[33] = decrypt_int ? K[37] : K[31];
assign K2[34] = decrypt_int ? K[50] : K[16];
assign K2[35] = decrypt_int ? K[21] : K[42];
assign K2[36] = decrypt_int ? K[16] : K[37];
assign K2[37] = decrypt_int ? K[43] : K[9];
assign K2[38] = decrypt_int ? K[23] : K[44];
assign K2[39] = decrypt_int ? K[8] : K[29];
assign K2[40] = decrypt_int ? K[45] : K[7];
assign K2[41] = decrypt_int ? K[28] : K[49];
assign K2[42] = decrypt_int ? K[51] : K[45];
assign K2[43] = decrypt_int ? K[2] : K[23];
assign K2[44] = decrypt_int ? K[29] : K[50];
assign K2[45] = decrypt_int ? K[30] : K[51];
assign K2[46] = decrypt_int ? K[42] : K[8];
assign K2[47] = decrypt_int ? K[52] : K[14];
assign K2[48] = decrypt_int ? K[14] : K[35];
assign K1[1] = decrypt_int ? K[40]  : K[47];
assign K1[2] = decrypt_int ? K[4]   : K[11];
assign K1[3] = decrypt_int ? K[19]  : K[26];
assign K1[4] = decrypt_int ? K[53]  : K[3];
assign K1[5] = decrypt_int ? K[6]   : K[13];
assign K1[6] = decrypt_int ? K[34]  : K[41];
assign K1[7] = decrypt_int ? K[20]  : K[27];
assign K1[8] = decrypt_int ? K[24]  : K[6];
assign K1[9] = decrypt_int ? K[47]  : K[54];
assign K1[10] = decrypt_int ? K[41] : K[48];
assign K1[11] = decrypt_int ? K[32] : K[39];
assign K1[12] = decrypt_int ? K[12] : K[19];
assign K1[13] = decrypt_int ? K[46] : K[53];
assign K1[14] = decrypt_int ? K[18] : K[25];
assign K1[15] = decrypt_int ? K[26] : K[33];
assign K1[16] = decrypt_int ? K[27] : K[34];
assign K1[17] = decrypt_int ? K[10] : K[17];
assign K1[18] = decrypt_int ? K[55] : K[5];
assign K1[19] = decrypt_int ? K[54] : K[4];
assign K1[20] = decrypt_int ? K[48] : K[55];
assign K1[21] = decrypt_int ? K[17] : K[24];
assign K1[22] = decrypt_int ? K[25] : K[32];
assign K1[23] = decrypt_int ? K[33] : K[40];
assign K1[24] = decrypt_int ? K[13] : K[20];
assign K1[25] = decrypt_int ? K[29] : K[36];
assign K1[26] = decrypt_int ? K[51] : K[31];
assign K1[27] = decrypt_int ? K[14] : K[21];
assign K1[28] = decrypt_int ? K[1]  : K[8];
assign K1[29] = decrypt_int ? K[16] : K[23];
assign K1[30] = decrypt_int ? K[45] : K[52];
assign K1[31] = decrypt_int ? K[7]  : K[14];
assign K1[32] = decrypt_int ? K[22] : K[29];
assign K1[33] = decrypt_int ? K[44] : K[51];
assign K1[34] = decrypt_int ? K[2]  : K[9];
assign K1[35] = decrypt_int ? K[28] : K[35];
assign K1[36] = decrypt_int ? K[23] : K[30];
assign K1[37] = decrypt_int ? K[50] : K[2];
assign K1[38] = decrypt_int ? K[30] : K[37];
assign K1[39] = decrypt_int ? K[15] : K[22];
assign K1[40] = decrypt_int ? K[52] : K[0];
assign K1[41] = decrypt_int ? K[35] : K[42];
assign K1[42] = decrypt_int ? K[31] : K[38];
assign K1[43] = decrypt_int ? K[9]  : K[16];
assign K1[44] = decrypt_int ? K[36] : K[43];
assign K1[45] = decrypt_int ? K[37] : K[44];
assign K1[46] = decrypt_int ? K[49] : K[1];
assign K1[47] = decrypt_int ? K[0]  : K[7];
assign K1[48] = decrypt_int ? K[21] : K[28];
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  DES CORE                                                   ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
Triple DES Core
===============
Attached is a Triple DES core implementation in verilog. It takes
three standard 56 bit keys and 64 bits of data as input and generates
a 64 bit encrypted/decrypted result. Two implementations are provided:
1) Area Optimized (CBC Mode)
   This is a sequential implementation and needs 48 cycles to complete
   a full encryption/decryption cycle.
2) Performance Optimized (EBC Mode)
   This is a pipelined implementation that has a 48 cycle pipeline
   (plus 1 input and 1 output register). It can perform a complete
   encryption/decryption every cycle.
Performance
===========
1) Area Optimized (CBC Mode)
   0.18u UMC ASIC process: 5.5K gates, > 160 Mhz
   Spartan IIe 100-6 : 1450 LUTs (about 60%), 88MHz
2) Performance Optimized (EBC Mode)
   0.18u UMC ASIC process: 55K Gates, 300MHz (19.2 Gbits/sec)
   Virtex-II-1500-6: 79% utilization, 166Mhz (10.6 Gbits/sec)
DES Core
========
Attached is a DES core implementation in verilog. It takes a standard
56 bit key and 64 bits of data as input and generates a 64 bit 
encrypted/decrypted result. Two implementations are provided:
1) Area Optimized (CBC Mode)
   This is a sequential implementation and needs 16 cycles to complete
   a full encryption/decryption cycle.
2) Performance Optimized (EBC Mode)
   This is a pipelined implementation that has a 16 cycle pipeline
   (plus 1 input and 1 output register). It can perform a complete
   encryption/decryption every cycle.
Performance
===========
1) Area Optimized (CBC Mode)
   0.18u UMC ASIC process: >155Mhz 3K Gates
   Altera APEX 20KE-1: 1106 lcells >27MHz
   Altera FLEX 10K50E-1: 1283 lcells >43MHz
2) Performance Optimized (EBC Mode)
   0.18u UMC ASIC process: >290Mhz 28K Gates
   Altera APEX 20KE-1: 6688 lcells >53MHz
   Altera FLEX 10K130E-1: 6485 lcells >76 Mhz
Status
======
31-Oct-2002	Added Triple DES
05-Oct-2001	Added decrypt input (Thanks to Mark Cynar for
                providing the code)
		Reorganized directory structure
		Added Makefile
		Cleaned up test benches
03-Feb-2001	Initial Release
 
Directory Structure
===================
[core_root]
 |
 +-doc                        Documentation
 |
 +-bench--+                   Test Bench
 |        +- verilog          Verilog Sources
 |        +-vhdl              VHDL Sources
 |
 +-rtl----+                   Core RTL Sources
 |        +-verilog           Verilog Sources
 |        +-vhdl              VHDL Sources
 |
 +-sim----+
 |        +-rtl_sim---+       Functional verification Directory
 |        |           +-bin   Makefiles/Run Scripts
 |        |           +-run   Working Directory
 |        |
 |        +-gate_sim--+       Functional & Timing Gate Level
 |                    |       Verification Directory
 |                    +-bin   Makefiles/Run Scripts
 |                    +-run   Working Directory
 |
 +-lint--+                    Lint Directory Tree
 |       +-bin                Makefiles/Run Scripts
 |       +-run                Working Directory
 |       +-log                Linter log & result files
 |
 +-syn---+                    Synthesis Directory Tree
 |       +-bin                Synthesis Scripts
 |       +-run                Working Directory
 |       +-log                Synthesis log files
 |       +-out                Synthesis Output
About the Author
================
To find out more about me (Rudolf Usselmann), please visit:
http://www.asics.ws
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox1(addr, dout, reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
always @(*)
    begin
        case ({ addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout =  14;
            1:
                dout =   4;
            2:
                dout =  13;
            3:
                dout =   1;
            4:
                dout =   2;
            5:
                dout =  15;
            6:
                dout =  11;
            7:
                dout =   8;
            8:
                dout =   3;
            9:
                dout =  10;
            10:
                dout =   6;
            11:
                dout =  12;
            12:
                dout =   5;
            13:
                dout =   9;
            14:
                dout =   0;
            15:
                dout =   7;
            16:
                dout =   0;
            17:
                dout =  15;
            18:
                dout =   7;
            19:
                dout =   4;
            20:
                dout =  14;
            21:
                dout =   2;
            22:
                dout =  13;
            23:
                dout =   1;
            24:
                dout =  10;
            25:
                dout =   6;
            26:
                dout =  12;
            27:
                dout =  11;
            28:
                dout =   9;
            29:
                dout =   5;
            30:
                dout =   3;
            31:
                dout =   8;
            32:
                dout =   4;
            33:
                dout =   1;
            34:
                dout =  14;
            35:
                dout =   8;
            36:
                dout =  13;
            37:
                dout =   6;
            38:
                dout =   2;
            39:
                dout =  11;
            40:
                dout =  15;
            41:
                dout =  12;
            42:
                dout =   9;
            43:
                dout =   7;
            44:
                dout =   3;
            45:
                dout =  10;
            46:
                dout =   5;
            47:
                dout =   0;
            48:
                dout =  15;
            49:
                dout =  12;
            50:
                dout =   8;
            51:
                dout =   2;
            52:
                dout =   4;
            53:
                dout =   9;
            54:
                dout =   1;
            55:
                dout =   7;
            56:
                dout =   5;
            57:
                dout =  11;
            58:
                dout =   3;
            59:
                dout =  14;
            60:
                dout =  10;
            61:
                dout =   0;
            62:
                dout =   6;
            63:
                dout =  13;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox2(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout = 15;
            1:
                dout =  1;
            2:
                dout =  8;
            3:
                dout = 14;
            4:
                dout =  6;
            5:
                dout = 11;
            6:
                dout =  3;
            7:
                dout =  4;
            8:
                dout =  9;
            9:
                dout =  7;
            10:
                dout =  2;
            11:
                dout = 13;
            12:
                dout = 12;
            13:
                dout =  0;
            14:
                dout =  5;
            15:
                dout = 10;
            16:
                dout =  3;
            17:
                dout = 13;
            18:
                dout =  4;
            19:
                dout =  7;
            20:
                dout = 15;
            21:
                dout =  2;
            22:
                dout =  8;
            23:
                dout = 14;
            24:
                dout = 12;
            25:
                dout =  0;
            26:
                dout =  1;
            27:
                dout = 10;
            28:
                dout =  6;
            29:
                dout =  9;
            30:
                dout = 11;
            31:
                dout =  5;
            32:
                dout =  0;
            33:
                dout = 14;
            34:
                dout =  7;
            35:
                dout = 11;
            36:
                dout = 10;
            37:
                dout =  4;
            38:
                dout = 13;
            39:
                dout =  1;
            40:
                dout =  5;
            41:
                dout =  8;
            42:
                dout = 12;
            43:
                dout =  6;
            44:
                dout =  9;
            45:
                dout =  3;
            46:
                dout =  2;
            47:
                dout = 15;
            48:
                dout = 13;
            49:
                dout =  8;
            50:
                dout = 10;
            51:
                dout =  1;
            52:
                dout =  3;
            53:
                dout = 15;
            54:
                dout =  4;
            55:
                dout =  2;
            56:
                dout = 11;
            57:
                dout =  6;
            58:
                dout =  7;
            59:
                dout = 12;
            60:
                dout =  0;
            61:
                dout =  5;
            62:
                dout = 14;
            63:
                dout =  9;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox3(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout = 10;
            1:
                dout =  0;
            2:
                dout =  9;
            3:
                dout = 14;
            4:
                dout =  6;
            5:
                dout =  3;
            6:
                dout = 15;
            7:
                dout =  5;
            8:
                dout =  1;
            9:
                dout = 13;
            10:
                dout = 12;
            11:
                dout =  7;
            12:
                dout = 11;
            13:
                dout =  4;
            14:
                dout =  2;
            15:
                dout =  8;
            16:
                dout = 13;
            17:
                dout =  7;
            18:
                dout =  0;
            19:
                dout =  9;
            20:
                dout =  3;
            21:
                dout =  4;
            22:
                dout =  6;
            23:
                dout = 10;
            24:
                dout =  2;
            25:
                dout =  8;
            26:
                dout =  5;
            27:
                dout = 14;
            28:
                dout = 12;
            29:
                dout = 11;
            30:
                dout = 15;
            31:
                dout =  1;
            32:
                dout = 13;
            33:
                dout =  6;
            34:
                dout =  4;
            35:
                dout =  9;
            36:
                dout =  8;
            37:
                dout = 15;
            38:
                dout =  3;
            39:
                dout =  0;
            40:
                dout = 11;
            41:
                dout =  1;
            42:
                dout =  2;
            43:
                dout = 12;
            44:
                dout =  5;
            45:
                dout = 10;
            46:
                dout = 14;
            47:
                dout =  7;
            48:
                dout =  1;
            49:
                dout = 10;
            50:
                dout = 13;
            51:
                dout =  0;
            52:
                dout =  6;
            53:
                dout =  9;
            54:
                dout =  8;
            55:
                dout =  7;
            56:
                dout =  4;
            57:
                dout = 15;
            58:
                dout = 14;
            59:
                dout =  3;
            60:
                dout = 11;
            61:
                dout =  5;
            62:
                dout =  2;
            63:
                dout = 12;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox4(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout =  7;
            1:
                dout = 13;
            2:
                dout = 14;
            3:
                dout =  3;
            4:
                dout =  0;
            5:
                dout =  6;
            6:
                dout =  9;
            7:
                dout = 10;
            8:
                dout =  1;
            9:
                dout =  2;
            10:
                dout =  8;
            11:
                dout =  5;
            12:
                dout = 11;
            13:
                dout = 12;
            14:
                dout =  4;
            15:
                dout = 15;
            16:
                dout = 13;
            17:
                dout =  8;
            18:
                dout = 11;
            19:
                dout =  5;
            20:
                dout =  6;
            21:
                dout = 15;
            22:
                dout =  0;
            23:
                dout =  3;
            24:
                dout =  4;
            25:
                dout =  7;
            26:
                dout =  2;
            27:
                dout = 12;
            28:
                dout =  1;
            29:
                dout = 10;
            30:
                dout = 14;
            31:
                dout =  9;
            32:
                dout = 10;
            33:
                dout =  6;
            34:
                dout =  9;
            35:
                dout =  0;
            36:
                dout = 12;
            37:
                dout = 11;
            38:
                dout =  7;
            39:
                dout = 13;
            40:
                dout = 15;
            41:
                dout =  1;
            42:
                dout =  3;
            43:
                dout = 14;
            44:
                dout =  5;
            45:
                dout =  2;
            46:
                dout =  8;
            47:
                dout =  4;
            48:
                dout =  3;
            49:
                dout = 15;
            50:
                dout =  0;
            51:
                dout =  6;
            52:
                dout = 10;
            53:
                dout =  1;
            54:
                dout = 13;
            55:
                dout =  8;
            56:
                dout =  9;
            57:
                dout =  4;
            58:
                dout =  5;
            59:
                dout = 11;
            60:
                dout = 12;
            61:
                dout =  7;
            62:
                dout =  2;
            63:
                dout = 14;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox5(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout =  2;
            1:
                dout = 12;
            2:
                dout =  4;
            3:
                dout =  1;
            4:
                dout =  7;
            5:
                dout = 10;
            6:
                dout = 11;
            7:
                dout =  6;
            8:
                dout =  8;
            9:
                dout =  5;
            10:
                dout =  3;
            11:
                dout = 15;
            12:
                dout = 13;
            13:
                dout =  0;
            14:
                dout = 14;
            15:
                dout =  9;
            16:
                dout = 14;
            17:
                dout = 11;
            18:
                dout =  2;
            19:
                dout = 12;
            20:
                dout =  4;
            21:
                dout =  7;
            22:
                dout = 13;
            23:
                dout =  1;
            24:
                dout =  5;
            25:
                dout =  0;
            26:
                dout = 15;
            27:
                dout = 10;
            28:
                dout =  3;
            29:
                dout =  9;
            30:
                dout =  8;
            31:
                dout =  6;
            32:
                dout =  4;
            33:
                dout =  2;
            34:
                dout =  1;
            35:
                dout = 11;
            36:
                dout = 10;
            37:
                dout = 13;
            38:
                dout =  7;
            39:
                dout =  8;
            40:
                dout = 15;
            41:
                dout =  9;
            42:
                dout = 12;
            43:
                dout =  5;
            44:
                dout =  6;
            45:
                dout =  3;
            46:
                dout =  0;
            47:
                dout = 14;
            48:
                dout = 11;
            49:
                dout =  8;
            50:
                dout = 12;
            51:
                dout =  7;
            52:
                dout =  1;
            53:
                dout = 14;
            54:
                dout =  2;
            55:
                dout = 13;
            56:
                dout =  6;
            57:
                dout = 15;
            58:
                dout =  0;
            59:
                dout =  9;
            60:
                dout = 10;
            61:
                dout =  4;
            62:
                dout =  5;
            63:
                dout =  3;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox6(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout = 12;
            1:
                dout =  1;
            2:
                dout = 10;
            3:
                dout = 15;
            4:
                dout =  9;
            5:
                dout =  2;
            6:
                dout =  6;
            7:
                dout =  8;
            8:
                dout =  0;
            9:
                dout = 13;
            10:
                dout =  3;
            11:
                dout =  4;
            12:
                dout = 14;
            13:
                dout =  7;
            14:
                dout =  5;
            15:
                dout = 11;
            16:
                dout = 10;
            17:
                dout = 15;
            18:
                dout =  4;
            19:
                dout =  2;
            20:
                dout =  7;
            21:
                dout = 12;
            22:
                dout =  9;
            23:
                dout =  5;
            24:
                dout =  6;
            25:
                dout =  1;
            26:
                dout = 13;
            27:
                dout = 14;
            28:
                dout =  0;
            29:
                dout = 11;
            30:
                dout =  3;
            31:
                dout =  8;
            32:
                dout =  9;
            33:
                dout = 14;
            34:
                dout = 15;
            35:
                dout =  5;
            36:
                dout =  2;
            37:
                dout =  8;
            38:
                dout = 12;
            39:
                dout =  3;
            40:
                dout =  7;
            41:
                dout =  0;
            42:
                dout =  4;
            43:
                dout = 10;
            44:
                dout =  1;
            45:
                dout = 13;
            46:
                dout = 11;
            47:
                dout =  6;
            48:
                dout =  4;
            49:
                dout =  3;
            50:
                dout =  2;
            51:
                dout = 12;
            52:
                dout =  9;
            53:
                dout =  5;
            54:
                dout = 15;
            55:
                dout = 10;
            56:
                dout = 11;
            57:
                dout = 14;
            58:
                dout =  1;
            59:
                dout =  7;
            60:
                dout =  6;
            61:
                dout =  0;
            62:
                dout =  8;
            63:
                dout = 13;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox7(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout =  4;
            1:
                dout = 11;
            2:
                dout =  2;
            3:
                dout = 14;
            4:
                dout = 15;
            5:
                dout =  0;
            6:
                dout =  8;
            7:
                dout = 13;
            8:
                dout =  3;
            9:
                dout = 12;
            10:
                dout =  9;
            11:
                dout =  7;
            12:
                dout =  5;
            13:
                dout = 10;
            14:
                dout =  6;
            15:
                dout =  1;
            16:
                dout = 13;
            17:
                dout =  0;
            18:
                dout = 11;
            19:
                dout =  7;
            20:
                dout =  4;
            21:
                dout =  9;
            22:
                dout =  1;
            23:
                dout = 10;
            24:
                dout = 14;
            25:
                dout =  3;
            26:
                dout =  5;
            27:
                dout = 12;
            28:
                dout =  2;
            29:
                dout = 15;
            30:
                dout =  8;
            31:
                dout =  6;
            32:
                dout =  1;
            33:
                dout =  4;
            34:
                dout = 11;
            35:
                dout = 13;
            36:
                dout = 12;
            37:
                dout =  3;
            38:
                dout =  7;
            39:
                dout = 14;
            40:
                dout = 10;
            41:
                dout = 15;
            42:
                dout =  6;
            43:
                dout =  8;
            44:
                dout =  0;
            45:
                dout =  5;
            46:
                dout =  9;
            47:
                dout =  2;
            48:
                dout =  6;
            49:
                dout = 11;
            50:
                dout = 13;
            51:
                dout =  8;
            52:
                dout =  1;
            53:
                dout =  4;
            54:
                dout = 10;
            55:
                dout =  7;
            56:
                dout =  9;
            57:
                dout =  5;
            58:
                dout =  0;
            59:
                dout = 15;
            60:
                dout = 14;
            61:
                dout =  2;
            62:
                dout =  3;
            63:
                dout = 12;
        endcase
    end
endmodule
 | 
| 
	/////////////////////////////////////////////////////////////////////
////                                                             ////
////  SBOX                                                       ////
////  The SBOX is essentially a 64x4 ROM                         ////
////                                                             ////
////  Author: Rudolf Usselmann                                   ////
////          [email protected]                                      ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
////                                                             ////
//// Copyright (C) 2001 Rudolf Usselmann                         ////
////                    [email protected]                            ////
////                                                             ////
//// This source file may be used and distributed without        ////
//// restriction provided that this copyright statement is not   ////
//// removed from the file and that any derivative work contains ////
//// the original copyright notice and the associated disclaimer.////
////                                                             ////
////     THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY     ////
//// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   ////
//// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS   ////
//// FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR      ////
//// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,         ////
//// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    ////
//// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE   ////
//// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR        ////
//// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  ////
//// LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT  ////
//// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT  ////
//// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         ////
//// POSSIBILITY OF SUCH DAMAGE.                                 ////
////                                                             ////
/////////////////////////////////////////////////////////////////////
module  sbox8(addr, dout,reset, clk);
/* verilator lint_off LITENDIAN */
input [1:6] addr;
output [1:4] dout;
reg [1:4] dout;
input reset;
input clk;
/* verilator lint_on LITENDIAN */
always @(*)
    begin
        case ({addr[1], addr[6], addr[2:5]}) //synopsys full_case parallel_case
            0:
                dout = 13;
            1:
                dout =  2;
            2:
                dout =  8;
            3:
                dout =  4;
            4:
                dout =  6;
            5:
                dout = 15;
            6:
                dout = 11;
            7:
                dout =  1;
            8:
                dout = 10;
            9:
                dout =  9;
            10:
                dout =  3;
            11:
                dout = 14;
            12:
                dout =  5;
            13:
                dout =  0;
            14:
                dout = 12;
            15:
                dout =  7;
            16:
                dout =  1;
            17:
                dout = 15;
            18:
                dout = 13;
            19:
                dout =  8;
            20:
                dout = 10;
            21:
                dout =  3;
            22:
                dout =  7;
            23:
                dout =  4;
            24:
                dout = 12;
            25:
                dout =  5;
            26:
                dout =  6;
            27:
                dout = 11;
            28:
                dout =  0;
            29:
                dout = 14;
            30:
                dout =  9;
            31:
                dout =  2;
            32:
                dout =  7;
            33:
                dout = 11;
            34:
                dout =  4;
            35:
                dout =  1;
            36:
                dout =  9;
            37:
                dout = 12;
            38:
                dout = 14;
            39:
                dout =  2;
            40:
                dout =  0;
            41:
                dout =  6;
            42:
                dout = 10;
            43:
                dout = 13;
            44:
                dout = 15;
            45:
                dout =  3;
            46:
                dout =  5;
            47:
                dout =  8;
            48:
                dout =  2;
            49:
                dout =  1;
            50:
                dout = 14;
            51:
                dout =  7;
            52:
                dout =  4;
            53:
                dout = 10;
            54:
                dout =  8;
            55:
                dout = 13;
            56:
                dout = 15;
            57:
                dout = 12;
            58:
                dout =  9;
            59:
                dout =  0;
            60:
                dout =  3;
            61:
                dout =  5;
            62:
                dout =  6;
            63:
                dout = 11;
        endcase
    end
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       dft_top_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module dft_top_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    
    // Core I/O
    input wire            next,
    output wire           next_out,
    input wire [15 : 0]   X0,
    input wire [15 : 0]   X1,
    input wire [15 : 0]   X2,
    input wire [15 : 0]   X3,
    output wire [15 : 0]  Y0,
    output wire [15 : 0]  Y1,
    output wire [15 : 0]  Y2,
    output wire [15 : 0]  Y3,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = DFT_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [15:0]                   mock_tss_X0;
  wire [15:0]                   mock_tss_X1;
  wire [15:0]                   mock_tss_X2;
  wire [15:0]                   mock_tss_X3;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign mock_tss_X0          = DFT_MOCK_TSS_KEY_WORDS[0][15:0] ^
                                llkid_key_register[15:0] ^
                                X0;
  assign mock_tss_X1          = DFT_MOCK_TSS_KEY_WORDS[0][31:16] ^
                                llkid_key_register[31:16] ^
                                X1;
  assign mock_tss_X2          = DFT_MOCK_TSS_KEY_WORDS[0][47:32] ^
                                llkid_key_register[47:32] ^
                                X2;
  assign mock_tss_X3          = DFT_MOCK_TSS_KEY_WORDS[0][63:48] ^
                                llkid_key_register[63:48] ^
                                X3;
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  dft_top dft_top_inst (
    .clk            (clk),
    .reset          (rst),
    .next           (next),
    .next_out       (next_out),
    .X0             (mock_tss_X0),
    .X1             (mock_tss_X1),
    .X2             (mock_tss_X2),
    .X3             (mock_tss_X3),
    .Y0             (Y0),
    .Y1             (Y1),
    .Y2             (Y2),
    .Y3             (Y3)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	/*------------------------------------------------------------------------------
 * This code was generated by Spiral IIR Filter Generator, www.spiral.net
 * Copyright (c) 2006, Carnegie Mellon University
 * All rights reserved.
 * The code is distributed under a BSD style license
 * (see http://www.opensource.org/licenses/bsd-license.php)
 *------------------------------------------------------------------------------ */
/* ./iirGen.pl -A 256 256 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -B 0 4 22 68 136 191 191 136 68 22 4 0 -moduleName FIR_filter -fractionalBits 8 -bitWidth 32 -inData inData -inReg -outReg -outData outData -clk clk -reset reset -reset_edge negedge -filterForm 1 -outFile ../outputs/filter_1542230812.v */
/* Warning: zero-valued filter taps have been optimized away. */
module FIR_filter_firBlock_left_MultiplyBlock (
    X,
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8,
    Y9,
    Y10,
    Y11
);
  // Port mode declarations:
  input signed   [31:0] X;
  output signed  [31:0]
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8,
    Y9,
    Y10,
    Y11;
  wire [31:0] Y [0:10];
  assign Y1 = Y[0];
  assign Y2 = Y[1];
  assign Y3 = Y[2];
  assign Y4 = Y[3];
  assign Y5 = Y[4];
  assign Y6 = Y[5];
  assign Y7 = Y[6];
  assign Y8 = Y[7];
  assign Y9 = Y[8];
  assign Y10 = Y[9];
  assign Y11 = Y[10];
  //Multipliers:
  wire signed [39:0]
    w1,
    w0,
    w16,
    w17,
    w4,
    w3,
    w8,
    w11,
    w192,
    w191,
    w22,
    w68,
    w136;
  assign w1 = X;
  assign w0 = 0;
  assign w11 = w3 + w8;
  assign w136 = w17 << 3;
  assign w16 = w1 << 4;
  assign w17 = w1 + w16;
  assign w191 = w192 - w1;
  assign w192 = w3 << 6;
  assign w22 = w11 << 1;
  assign w3 = w4 - w1;
  assign w4 = w1 << 2;
  assign w68 = w17 << 2;
  assign w8 = w1 << 3;
  assign Y[0] = w4[39:8];
  assign Y[1] = w22[39:8];
  assign Y[2] = w68[39:8];
  assign Y[3] = w136[39:8];
  assign Y[4] = w191[39:8];
  assign Y[5] = w191[39:8];
  assign Y[6] = w136[39:8];
  assign Y[7] = w68[39:8];
  assign Y[8] = w22[39:8];
  assign Y[9] = w4[39:8];
  assign Y[10] = w0[39:8];
  //FIR_filter_firBlock_left_MultiplyBlock area estimate = 9360.48955432647;
endmodule //FIR_filter_firBlock_left_MultiplyBlock
module FIR_filter_firBlock_left (
    X,
    clk,
    Y,
    reset
);
  // Port mode declarations:
  input   [31:0] X;
  input    clk;
  output  [31:0] Y;
  input    reset;
  //registerOut
  reg [31:0] Y;
  wire [31:0] Y_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      Y <= 32'h00000000;
    end  else begin
      Y <= Y_in;
    end
  end
  wire [31:0] multProducts [0:10];
  FIR_filter_firBlock_left_MultiplyBlock my_FIR_filter_firBlock_left_MultiplyBlock(
    .X(X),
    .Y1(multProducts[0]),
    .Y2(multProducts[1]),
    .Y3(multProducts[2]),
    .Y4(multProducts[3]),
    .Y5(multProducts[4]),
    .Y6(multProducts[5]),
    .Y7(multProducts[6]),
    .Y8(multProducts[7]),
    .Y9(multProducts[8]),
    .Y10(multProducts[9]),
    .Y11(multProducts[10])
  );
  reg [31:0] firStep[0:9];
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      firStep[0] <= 32'h00000000;
      firStep[1] <= 32'h00000000;
      firStep[2] <= 32'h00000000;
      firStep[3] <= 32'h00000000;
      firStep[4] <= 32'h00000000;
      firStep[5] <= 32'h00000000;
      firStep[6] <= 32'h00000000;
      firStep[7] <= 32'h00000000;
      firStep[8] <= 32'h00000000;
      firStep[9] <= 32'h00000000;
    end
    else begin
      firStep[0] <=  multProducts[0];
      firStep[1] <=  firStep[0] + multProducts[1];
      firStep[2] <=  firStep[1] + multProducts[2];
      firStep[3] <=  firStep[2] + multProducts[3];
      firStep[4] <=  firStep[3] + multProducts[4];
      firStep[5] <=  firStep[4] + multProducts[5];
      firStep[6] <=  firStep[5] + multProducts[6];
      firStep[7] <=  firStep[6] + multProducts[7];
      firStep[8] <=  firStep[7] + multProducts[8];
      firStep[9] <=  firStep[8] + multProducts[9];
    end
  end
  assign Y_in = firStep[9]+ multProducts[10];
  //FIR_filter_firBlock_left area estimate = 56049.8412354117;
endmodule //FIR_filter_firBlock_left
/* Warning: zero-valued filter taps have been optimized away. */
module FIR_filter_firBlock_right_MultiplyBlock (
    X,
    Y
);
  // Port mode declarations:
  input signed   [31:0] X;
  output signed  [31:0] Y;
  //Multipliers:
  wire signed [39:0]
    w1,
    w256,
    w256_;
  assign w1 = X;
  assign w256 = w1 << 8;
  assign w256_ = -1 * w256;
  assign Y = w256_[39:8];
  //FIR_filter_firBlock_right_MultiplyBlock area estimate = 1437.00483871323;
endmodule //FIR_filter_firBlock_right_MultiplyBlock
module FIR_filter_firBlock_right (
    X,
    clk,
    Y,
    reset
);
  // Port mode declarations:
  input   [31:0] X;
  input    clk;
  output  [31:0] Y;
  input    reset;
  //registerOut
  reg [31:0] Y;
  wire [31:0] Y_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      Y <= 32'h00000000;
    end  else begin
      Y <= Y_in;
    end
  end
  wire [31:0] multProducts;
  FIR_filter_firBlock_right_MultiplyBlock my_FIR_filter_firBlock_right_MultiplyBlock(
    .X(X),
    .Y(multProducts)
  );
  assign Y_in = multProducts;
  //FIR_filter_firBlock_right area estimate = 3885.23530779558;
endmodule //FIR_filter_firBlock_right
module FIR_filter (
    inData,
    clk,
    outData,
    reset
);
  // Port mode declarations:
  input   [31:0] inData;
  input    clk;
  output  [31:0] outData;
  input    reset;
  //registerIn
  reg [31:0] inData_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      inData_in <= 32'h00000000;
    end  else begin
      inData_in <= inData;
    end
  end
  //registerOut
  reg [31:0] outData;
  wire [31:0] outData_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      outData <= 32'h00000000;
    end  else begin
      outData <= outData_in;
    end
  end
  wire [31:0] leftOut, rightOut;
  FIR_filter_firBlock_left my_FIR_filter_firBlock_left(
    .X(inData_in),
    .Y(leftOut),
    .clk(clk),
    .reset(reset)
);
  FIR_filter_firBlock_right my_FIR_filter_firBlock_right(
    .X(outData_in),
    .Y(rightOut),
    .clk(clk),
    .reset(reset)
);
  assign outData_in = leftOut + rightOut;
  //FIR_filter area estimate = 67026.9615392808;
endmodule //FIR_filter
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       FIR_filter_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module FIR_filter_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    input wire            rst_dut,
    // Core I/O
    input wire [31 : 0]   inData,
    output wire [31 : 0]  outData,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = FIR_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [31:0]                   mock_tss_inData;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign mock_tss_inData      = FIR_MOCK_TSS_KEY_WORDS[0][31:0] ^
                                llkid_key_register[31:0] ^
                                inData;
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  FIR_filter FIR_filter_inst (
    .clk            (clk),
    .reset          (~(rst || rst_dut)),
    .inData         (mock_tss_inData),
    .outData        (outData)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       idft_top_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module idft_top_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    
    // Core I/O
    input wire            next,
    output wire           next_out,
    input wire [15 : 0]   X0,
    input wire [15 : 0]   X1,
    input wire [15 : 0]   X2,
    input wire [15 : 0]   X3,
    output wire [15 : 0]  Y0,
    output wire [15 : 0]  Y1,
    output wire [15 : 0]  Y2,
    output wire [15 : 0]  Y3,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = IDFT_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [15:0]                   mock_tss_X0;
  wire [15:0]                   mock_tss_X1;
  wire [15:0]                   mock_tss_X2;
  wire [15:0]                   mock_tss_X3;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign mock_tss_X0          = IDFT_MOCK_TSS_KEY_WORDS[0][15:0] ^
                                llkid_key_register[15:0] ^
                                X0;
  assign mock_tss_X1          = IDFT_MOCK_TSS_KEY_WORDS[0][31:16] ^
                                llkid_key_register[31:16] ^
                                X1;
  assign mock_tss_X2          = IDFT_MOCK_TSS_KEY_WORDS[0][47:32] ^
                                llkid_key_register[47:32] ^
                                X2;
  assign mock_tss_X3          = IDFT_MOCK_TSS_KEY_WORDS[0][63:48] ^
                                llkid_key_register[63:48] ^
                                X3;
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  idft_top idft_top_inst (
    .clk            (clk),
    .reset          (rst),
    .next           (next),
    .next_out       (next_out),
    .X0             (mock_tss_X0),
    .X1             (mock_tss_X1),
    .X2             (mock_tss_X2),
    .X3             (mock_tss_X3),
    .Y0             (Y0),
    .Y1             (Y1),
    .Y2             (Y2),
    .Y3             (Y3)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	/*------------------------------------------------------------------------------
 * This code was generated by Spiral IIR Filter Generator, www.spiral.net
 * Copyright (c) 2006, Carnegie Mellon University
 * All rights reserved.
 * The code is distributed under a BSD style license
 * (see http://www.opensource.org/licenses/bsd-license.php)
 *------------------------------------------------------------------------------ */
/* ./iirGen.pl -A 256 0 378 0 179 0 32 0 2 0 0 0 -B 0 4 22 68 136 191 191 136 68 22 4 0 -moduleName IIR_filter -fractionalBits 8 -bitWidth 32 -inData inData -inReg -outReg -outData outData -clk clk -reset reset -reset_edge negedge -filterForm 1 -outFile ../outputs/filter_1542230730.v */
/* Warning: zero-valued filter taps have been optimized away. */
module IIR_filter_firBlock_left_MultiplyBlock (
    X,
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8,
    Y9,
    Y10,
    Y11
);
  // Port mode declarations:
  input signed   [31:0] X;
  output signed  [31:0]
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8,
    Y9,
    Y10,
    Y11;
  wire [31:0] Y [0:10];
  assign Y1 = Y[0];
  assign Y2 = Y[1];
  assign Y3 = Y[2];
  assign Y4 = Y[3];
  assign Y5 = Y[4];
  assign Y6 = Y[5];
  assign Y7 = Y[6];
  assign Y8 = Y[7];
  assign Y9 = Y[8];
  assign Y10 = Y[9];
  assign Y11 = Y[10];
  //Multipliers:
  wire signed [39:0]
    w1,
    w0,
    w16,
    w17,
    w4,
    w3,
    w8,
    w11,
    w192,
    w191,
    w22,
    w68,
    w136;
  assign w1 = X;
  assign w0 = 0;
  assign w11 = w3 + w8;
  assign w136 = w17 << 3;
  assign w16 = w1 << 4;
  assign w17 = w1 + w16;
  assign w191 = w192 - w1;
  assign w192 = w3 << 6;
  assign w22 = w11 << 1;
  assign w3 = w4 - w1;
  assign w4 = w1 << 2;
  assign w68 = w17 << 2;
  assign w8 = w1 << 3;
  assign Y[0] = w4[39:8];
  assign Y[1] = w22[39:8];
  assign Y[2] = w68[39:8];
  assign Y[3] = w136[39:8];
  assign Y[4] = w191[39:8];
  assign Y[5] = w191[39:8];
  assign Y[6] = w136[39:8];
  assign Y[7] = w68[39:8];
  assign Y[8] = w22[39:8];
  assign Y[9] = w4[39:8];
  assign Y[10] = w0[39:8];
  //IIR_filter_firBlock_left_MultiplyBlock area estimate = 9360.48955432647;
endmodule //IIR_filter_firBlock_left_MultiplyBlock
module IIR_filter_firBlock_left (
    X,
    clk,
    Y,
    reset
);
  // Port mode declarations:
  input   [31:0] X;
  input    clk;
  output  [31:0] Y;
  input    reset;
  //registerOut
  reg [31:0] Y;
  wire [31:0] Y_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      Y <= 32'h00000000;
    end  else begin
      Y <= Y_in;
    end
  end
  wire [31:0] multProducts [0:10];
  IIR_filter_firBlock_left_MultiplyBlock my_IIR_filter_firBlock_left_MultiplyBlock(
    .X(X),
    .Y1(multProducts[0]),
    .Y2(multProducts[1]),
    .Y3(multProducts[2]),
    .Y4(multProducts[3]),
    .Y5(multProducts[4]),
    .Y6(multProducts[5]),
    .Y7(multProducts[6]),
    .Y8(multProducts[7]),
    .Y9(multProducts[8]),
    .Y10(multProducts[9]),
    .Y11(multProducts[10])
  );
  reg [31:0] firStep[0:9];
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      firStep[0] <= 32'h00000000;
      firStep[1] <= 32'h00000000;
      firStep[2] <= 32'h00000000;
      firStep[3] <= 32'h00000000;
      firStep[4] <= 32'h00000000;
      firStep[5] <= 32'h00000000;
      firStep[6] <= 32'h00000000;
      firStep[7] <= 32'h00000000;
      firStep[8] <= 32'h00000000;
      firStep[9] <= 32'h00000000;
    end
    else begin
      firStep[0] <=  multProducts[0];
      firStep[1] <=  firStep[0] + multProducts[1];
      firStep[2] <=  firStep[1] + multProducts[2];
      firStep[3] <=  firStep[2] + multProducts[3];
      firStep[4] <=  firStep[3] + multProducts[4];
      firStep[5] <=  firStep[4] + multProducts[5];
      firStep[6] <=  firStep[5] + multProducts[6];
      firStep[7] <=  firStep[6] + multProducts[7];
      firStep[8] <=  firStep[7] + multProducts[8];
      firStep[9] <=  firStep[8] + multProducts[9];
    end
  end
  assign Y_in = firStep[9]+ multProducts[10];
  //IIR_filter_firBlock_left area estimate = 56049.8412354117;
endmodule //IIR_filter_firBlock_left
/* Warning: zero-valued filter taps have been optimized away. */
module IIR_filter_firBlock_right_MultiplyBlock (
    X,
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8
);
  // Port mode declarations:
  input signed   [31:0] X;
  output signed  [31:0]
    Y1,
    Y2,
    Y3,
    Y4,
    Y5,
    Y6,
    Y7,
    Y8;
  wire [31:0] Y [0:7];
  assign Y1 = Y[0];
  assign Y2 = Y[1];
  assign Y3 = Y[2];
  assign Y4 = Y[3];
  assign Y5 = Y[4];
  assign Y6 = Y[5];
  assign Y7 = Y[6];
  assign Y8 = Y[7];
  //Multipliers:
  wire signed [39:0]
    w1,
    w0,
    w4,
    w3,
    w192,
    w189,
    w5,
    w10,
    w179,
    w2,
    w2_,
    w32,
    w32_,
    w179_,
    w378,
    w378_;
  assign w1 = X;
  assign w0 = 0;
  assign w10 = w5 << 1;
  assign w179 = w189 - w10;
  assign w179_ = -1 * w179;
  assign w189 = w192 - w3;
  assign w192 = w3 << 6;
  assign w2 = w1 << 1;
  assign w2_ = -1 * w2;
  assign w3 = w4 - w1;
  assign w32 = w1 << 5;
  assign w32_ = -1 * w32;
  assign w378 = w189 << 1;
  assign w378_ = -1 * w378;
  assign w4 = w1 << 2;
  assign w5 = w1 + w4;
  assign Y[0] = w2_[39:8];
  assign Y[1] = w0[39:8];
  assign Y[2] = w32_[39:8];
  assign Y[3] = w0[39:8];
  assign Y[4] = w179_[39:8];
  assign Y[5] = w0[39:8];
  assign Y[6] = w378_[39:8];
  assign Y[7] = w0[39:8];
  //IIR_filter_firBlock_right_MultiplyBlock area estimate = 16402.4783787809;
endmodule //IIR_filter_firBlock_right_MultiplyBlock
module IIR_filter_firBlock_right (
    X,
    clk,
    Y,
    reset
);
  // Port mode declarations:
  input   [31:0] X;
  input    clk;
  output  [31:0] Y;
  input    reset;
  //registerOut
  reg [31:0] Y;
  wire [31:0] Y_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      Y <= 32'h00000000;
    end  else begin
      Y <= Y_in;
    end
  end
  wire [31:0] multProducts [0:7];
  IIR_filter_firBlock_right_MultiplyBlock my_IIR_filter_firBlock_right_MultiplyBlock(
    .X(X),
    .Y1(multProducts[0]),
    .Y2(multProducts[1]),
    .Y3(multProducts[2]),
    .Y4(multProducts[3]),
    .Y5(multProducts[4]),
    .Y6(multProducts[5]),
    .Y7(multProducts[6]),
    .Y8(multProducts[7])
  );
  reg [31:0] firStep[0:6];
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      firStep[0] <= 32'h00000000;
      firStep[1] <= 32'h00000000;
      firStep[2] <= 32'h00000000;
      firStep[3] <= 32'h00000000;
      firStep[4] <= 32'h00000000;
      firStep[5] <= 32'h00000000;
      firStep[6] <= 32'h00000000;
    end
    else begin
      firStep[0] <=  multProducts[0];
      firStep[1] <=  firStep[0] + multProducts[1];
      firStep[2] <=  firStep[1] + multProducts[2];
      firStep[3] <=  firStep[2] + multProducts[3];
      firStep[4] <=  firStep[3] + multProducts[4];
      firStep[5] <=  firStep[4] + multProducts[5];
      firStep[6] <=  firStep[5] + multProducts[6];
    end
  end
  assign Y_in = firStep[6]+ multProducts[7];
  //IIR_filter_firBlock_right area estimate = 42574.5943051662;
endmodule //IIR_filter_firBlock_right
module IIR_filter (
    inData,
    clk,
    outData,
    reset
);
  // Port mode declarations:
  input   [31:0] inData;
  input    clk;
  output  [31:0] outData;
  input    reset;
  //registerIn
  reg [31:0] inData_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      inData_in <= 32'h00000000;
    end  else begin
      inData_in <= inData;
    end
  end
  //registerOut
  reg [31:0] outData;
  wire [31:0] outData_in;
  always@(posedge clk or negedge reset) begin
    if(~reset) begin
      outData <= 32'h00000000;
    end  else begin
      outData <= outData_in;
    end
  end
  wire [31:0] leftOut, rightOut;
  IIR_filter_firBlock_left my_IIR_filter_firBlock_left(
    .X(inData_in),
    .Y(leftOut),
    .clk(clk),
    .reset(reset)
);
  IIR_filter_firBlock_right my_IIR_filter_firBlock_right(
    .X(outData_in),
    .Y(rightOut),
    .clk(clk),
    .reset(reset)
);
  assign outData_in = leftOut + rightOut;
  //IIR_filter area estimate = 105716.320536651;
endmodule //IIR_filter
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       IIR_filter_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module IIR_filter_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    input wire            rst_dut,
    // Core I/O
    input wire [31 : 0]   inData,
    output wire [31 : 0]  outData,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = IIR_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [31:0]                   mock_tss_inData;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign mock_tss_inData      = IIR_MOCK_TSS_KEY_WORDS[0][31:0] ^
                                llkid_key_register[31:0] ^
                                inData;
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  IIR_filter IIR_filter_inst (
    .clk            (clk),
    .reset          (~(rst || rst_dut)),
    .inData         (mock_tss_inData),
    .outData        (outData)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	[//]: # (Copyright 2022 Massachusets Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   Copyright 2022 Massachusets Institute of Technology
</p>
# CEP-DSP: Core blocks
The core DSP blocks (DFT/IDFT/IIR/FIR) were generated using the free online hardware generators provided by the [Spiral Project](http://www.spiral.net/). 
Due to licensing restrictions, the generated DFT and IDFT cores cannot be directly included within the CEP repository.  
## Generator Websites
* DFT/iDFT: [Spiral Project DFT Gen](http://www.spiral.net/hardware/dftgen.html)
* IIR/FIR: [Spiral Project Filter Gen](http://www.spiral.net/hardware/filter.html)
## Generator Settings
* Note: We indicate deviations from the default generator setting as **`modified`**
* DFT/iDFT:
Core(s)  |DFT |IDFT
---------|---:|----:
**Problem Specification**||
Transform Size|64|64
Direction|Forward|**`Inverse`**
Data type|Fixed Point|Fixed Point
||16 bits|16 bits
||unscaled|unscaled
**Parameters Controlling Implementation**||
Architecture|fully streaming|fully streaming
radix|2|2
streaming width|2|2
data ordering|Natural in / natural out|Natural in / natural out
BRAM budget|1000|1000
Permutation Method|**`DATE'09 [4] (patent Free)`**|**`DATE'09 [4] (patent Free)`**
* IIR/FIR
Core(s)  |IIR |FIR
---------|---:|---:
Example Filter| Custom Filter| Custom Filter
Filter Taps a_k|1.000000e+000|**`1`**
||8.274631e-016|**`1`**
||1.479294e+000|**`0`**
||1.089388e-015|**`0`**
||7.013122e-001|**`0`**
||4.861197e-016|**`0`**
||1.262132e-001|**`0`**
||9.512539e-017|**`0`**
||7.898376e-003|**`0`**
||-4.496047e-018|**`0`**
||1.152699e-004|**`0`**
||-6.398766e-021|**`0`**
Filter Taps b_k|1.618571e-003|1.618571e-003
||1.780428e-002|1.780428e-002
||8.902138e-002|8.902138e-002
||2.670642e-001|2.670642e-001
||5.341283e-001|5.341283e-001
||7.477796e-001|7.477796e-001
||7.477796e-001|7.477796e-001
||5.341283e-001|5.341283e-001
||2.670642e-001|2.670642e-001
||8.902138e-002|8.902138e-002
||1.780428e-002|1.780428e-002
||1.618571e-003|1.618571e-003
Fractional bits|8|8
Bitwidth|32|32
Module Name|**`IIR_filter`**|**`FIR_filter`**
Input Data|inData|inData
Register Input|Yes|Yes
Output Data|outData|outData
Register Output|Yes|Yes
Clock Name|clk|clk
reset|negedge|negedge
Filter Form|I|I
Debug Output|**`Off`**|**`Off`**
## Incorporating the Generated Source Files
Generated source for the DFT and IDFT cores should be placed in `<CEP ROOT>/generators/mitll-blocks/src/main/resources/vsrc/generated_dsp_code`.
* DFT 
  * Save the generated Verilog file to `dft_top.v`
  * Remove the testbench module from the generated Verilog file.
* iDFT
  * Save the generated Verilog file to `idft_top.v`
  * Edit `idft_top.v`.  Rename the **dft_top** module to **idft_top**
  * Remove the testbench module from the generated Verilog file.
* IIR (already included in repo)
  * Save the generated Verilog file to `IIR_filter.v`
* FIR (already included in repo)
  * Save the generated Verilog file to `FIR_filter.v`
#### Return to the root CEP [README](../../../../../../../README.md) | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      	cacode.v
// Program:        	Common Evaluation Platform (CEP)
// Description:    	CA code generator
// Note: 			Generate 1023 chip sequence for SV PRN number prn_num.
//                  First chip on chip_out after reset.
//                  Asserting enb will advance to next chip.
//
//************************************************************************
module cacode
  (
   input       clk,
   input       rst,
   input [5:0] prn_num,
   input       prn_changed,
   input       enb,
   output reg  chip_out
   );
reg [10:1] g1, g2;
reg chip;
always @ (posedge clk) begin
    if (rst)
        begin
            g1 <= 10'b1111111111;
            g2 <= 10'b1111111111;
        end else begin
            if (prn_changed) begin
               g1 <= 10'b1111111111;
               g2 <= 10'b1111111111;
            end else if (enb) begin
                g1[10:1] <= {g1[9:1], g1[3] ^ g1[10]};
                g2[10:1] <= {g2[9:1], g2[2] ^ g2[3] ^ g2[6] ^ g2[8] ^ g2[9] ^ g2[10]};
            end
        end // else: !if(rst)
    end // always @ (posedge clk)
always @(*)
    begin
        if(rst)
           chip <= 1'b0; 
        else
    begin
        case (prn_num)
            6'd1 :
                chip <= g1[10] ^ g2[2] ^ g2[6];
            6'd2 :
                chip <= g1[10] ^ g2[3] ^ g2[7];
            6'd3 :
                chip <= g1[10] ^ g2[4] ^ g2[8];
            6'd4 :
                chip <= g1[10] ^ g2[5] ^ g2[9];
            6'd5 :
                chip <= g1[10] ^ g2[1] ^ g2[9];
            6'd6 :
                chip <= g1[10] ^ g2[2] ^ g2[10];
            6'd7 :
                chip <= g1[10] ^ g2[1] ^ g2[8];
            6'd8 :
                chip <= g1[10] ^ g2[2] ^ g2[9];
            6'd9 :
                chip <= g1[10] ^ g2[3] ^ g2[10];
            6'd10:
                chip <= g1[10] ^ g2[2] ^ g2[3];
            6'd11:
                chip <= g1[10] ^ g2[3] ^ g2[4];
            6'd12:
                chip <= g1[10] ^ g2[5] ^ g2[6];
            6'd13:
                chip <= g1[10] ^ g2[6] ^ g2[7];
            6'd14:
                chip <= g1[10] ^ g2[7] ^ g2[8];
            6'd15:
                chip <= g1[10] ^ g2[8] ^ g2[9];
            6'd16:
                chip <= g1[10] ^ g2[9] ^ g2[10];
            6'd17:
                chip <= g1[10] ^ g2[1] ^ g2[4];
            6'd18:
                chip <= g1[10] ^ g2[2] ^ g2[5];
            6'd19:
                chip <= g1[10] ^ g2[3] ^ g2[6];
            6'd20:
                chip <= g1[10] ^ g2[4] ^ g2[7];
            6'd21:
                chip <= g1[10] ^ g2[5] ^ g2[8];
            6'd22:
                chip <= g1[10] ^ g2[6] ^ g2[9];
            6'd23:
                chip <= g1[10] ^ g2[1] ^ g2[3];
            6'd24:
                chip <= g1[10] ^ g2[4] ^ g2[6];
            6'd25:
                chip <= g1[10] ^ g2[5] ^ g2[7];
            6'd26:
                chip <= g1[10] ^ g2[6] ^ g2[8];
            6'd27:
                chip <= g1[10] ^ g2[7] ^ g2[9];
            6'd28:
                chip <= g1[10] ^ g2[8] ^ g2[10];
            6'd29:
                chip <= g1[10] ^ g2[1] ^ g2[6];
            6'd30:
                chip <= g1[10] ^ g2[2] ^ g2[7];
            6'd31:
                chip <= g1[10] ^ g2[3] ^ g2[8];
            6'd32:
                chip <= g1[10] ^ g2[4] ^ g2[9];
            6'd33:
                chip <= g1[10] ^ g2[5] ^ g2[10];
            6'd34:
                chip <= g1[10] ^ g2[4] ^ g2[10];
            6'd35:
                chip <= g1[10] ^ g2[1] ^ g2[7];
            6'd36:
                chip <= g1[10] ^ g2[2] ^ g2[8];
            6'd37:
                chip <= g1[10] ^ g2[4] ^ g2[10];
            default:
                chip <= 1'b0;  //invalid prn_num
        endcase
    end
end
// reclock for timing
always @ (posedge clk)
    begin
        if(rst)
            chip_out<= 1'b0;
        else
            chip_out <= chip;
    end
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      	gps.v
// Program:        	Common Evaluation Platform (CEP)
// Description:    	GPS top-level module
// Note: 			From the GPS transmitter's perspective
//
//************************************************************************
module gps(
           sys_clk,
           sync_rst_in,
           sv_num,
           startRound,
           aes_key,
           pcode_speeds,
           pcode_initializers,
           ca_code,
           p_code,
           l_code,
           l_code_valid
       );
input  sys_clk;
input  sync_rst_in;
input [5:0] sv_num;
input startRound;
input [191:0] aes_key;
input [30:0] pcode_speeds;
input [47:0] pcode_initializers;
output reg [12:0] ca_code;
output [127:0] p_code;
output [127:0] l_code;
output l_code_valid;
wire gps_clk_fast;
// Start of round edge detection
reg startRound_r;
always @(posedge gps_clk_fast)
    begin
        if(sync_rst_in) begin
            startRound_r <= 0;
        end else begin
            startRound_r <= startRound;
        end
    end
wire startRoundPosEdge = ~startRound_r & startRound;
//
// Tony Duong: Added logic to detect a change in *sv_num* number and ca-code and p-code calculation automatically
// to recompute CA-Code
//
reg [5:0] last_sv_num;
wire      sv_changed = last_sv_num != sv_num;
always @(posedge gps_clk_fast)
    begin
        if (sync_rst_in)
            last_sv_num <= 0;
        else
            last_sv_num <= sv_num;
    end
//
// Control code generators
//
reg p_gen_en;
reg ca_gen_en;
reg [7:0] p_bit_count;
reg [3:0] ca_bit_count;
//Get 128 P-Code bits and 13 CA-Code bits. (Real GPS is exactly a 10:1 ratio, this is close enough for here)
always @(posedge gps_clk_fast)
    begin
        if (sync_rst_in)
            p_gen_en <= 1'b0;
        else if(startRoundPosEdge) begin
            p_gen_en <= startRoundPosEdge;
        end else if(p_bit_count == 8'd127) begin //Stop 1 cycle early due to generator latency.
            p_gen_en <= 1'b0;
        end
    end
always @(posedge gps_clk_fast)
    begin
        if (sync_rst_in)
            ca_gen_en <= 1'b0;
        else if(startRoundPosEdge) begin
            ca_gen_en <= startRoundPosEdge;
        end else if(ca_bit_count == 4'd12) begin //Stop 1 cycle early due to generator latency.
            ca_gen_en <= 1'b0;
        end
    end
// Generate C/A code
wire ca_code_bit;
cacode ca(
          .clk         (gps_clk_slow ),
          .rst         (sync_rst_in  ),
          .prn_num     (sv_num       ),
          .prn_changed (sv_changed   ),
          .enb         (ca_gen_en    ),
          .chip_out    (ca_code_bit  )
         );
// Save 13 ca-code bits
always @(posedge gps_clk_slow)
    begin
        if(sync_rst_in) begin
            ca_bit_count <= 4'b0;
            ca_code  <= 13'b0;
        end else if (startRoundPosEdge) begin
            ca_bit_count <= 4'b0;
            ca_code  <= 13'b0;
        end else if(ca_bit_count < 4'd14) begin //Due to latency of CA generator, record 1 extra bit as first bit received is junk.
            ca_bit_count <= ca_bit_count + 1;
            ca_code <= {ca_code[11:0], ca_code_bit};
        end
    end
// Generate P-code
wire p_code_bit;
//verification connections:
wire [11:0] pcode_xn_cnt_speed; //default must be 1.
wire [18:0] pcode_z_cnt_speed; //default must be 1.
wire [11:0] pcode_ini_x1a;     //default must be 12'b001001001000;
wire [11:0] pcode_ini_x1b;     //default must be 12'b010101010100;
wire [11:0] pcode_ini_x2a;     //default must be 12'b100100100101;
wire [11:0] pcode_ini_x2b;     //default must be 12'b010101010100;
assign pcode_xn_cnt_speed = pcode_speeds[11:0];
assign pcode_z_cnt_speed  = pcode_speeds[30:12];
assign pcode_ini_x1a = pcode_initializers[11:0];
assign pcode_ini_x1b = pcode_initializers[23:12];
assign pcode_ini_x2a = pcode_initializers[35:24];
assign pcode_ini_x2b = pcode_initializers[47:36];
pcode p(
        .clk            (gps_clk_fast  ),
        .reset          (sync_rst_in   ),
        .prn_changed    (sv_changed    ),
        .en             (p_gen_en      ),
        .sat            (sv_num        ),
        .preg           (p_code_bit    ),
        .xn_cnt_speed   (pcode_xn_cnt_speed),
        .z_cnt_speed    (pcode_z_cnt_speed),
        .ini_x1a        (pcode_ini_x1a ),
        .ini_x1b        (pcode_ini_x1b ),
        .ini_x2a        (pcode_ini_x2a ),
        .ini_x2b        (pcode_ini_x2b )
      );
// Save 128 p-code bits, encrypt and send as l_code
reg [127:0] p_pt;
always @(posedge gps_clk_fast)
    begin
        if (sync_rst_in) begin
            p_bit_count <= 0;
            p_pt <= 0; 
        end else if(startRoundPosEdge) begin
            p_bit_count <= 0;
            p_pt <= 0;
        end else if ( p_gen_en) begin
            if(p_bit_count < 8'd128) begin
                p_bit_count <= p_bit_count + 1;
                p_pt <= {p_pt [126:0], p_code_bit};
            end
        end
    end
assign p_code = p_pt;
reg encrypt;
always @(posedge gps_clk_fast)
    begin
        if (sync_rst_in) 
            encrypt <= 0;
        else begin
            encrypt <= (p_bit_count == 8'd127); //Run encryption every 128th bit
        end
    end
//
// Todo : finish removing
assign gps_clk_fast = sys_clk;
assign gps_clk_slow = sys_clk;
//
// in order to remove the reset dependency, we need create a mask to mask out the out_valid from aes_192 module
// while computing CA-code and P-code, the valid is only applied when encryt=1
reg l_valid_mask;
wire l_code_valid_i;
assign l_code_valid = l_code_valid_i & l_valid_mask;
//
always @(posedge gps_clk_fast) begin
    if (sync_rst_in)            l_valid_mask <= 0;
    else if (startRoundPosEdge) l_valid_mask <= 0; // clear the mask
    else if (encrypt)           l_valid_mask <= 1; // this happens             
end
aes_192 aes_192_inst (
    .clk        (gps_clk_fast),
    .rst        (sync_rst_in),
    .start      (encrypt),
    .state      (p_pt),
    .key        (aes_key),
    .out        (l_code),
    .out_valid  (l_code_valid_i)
  );
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       gps_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module gps_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            sys_clk,
    input wire            sync_rst_in,
    input wire            sync_rst_in_dut, // tony duong: from registers
    
    // Core I/O
    input wire [5 : 0]    sv_num,
    input wire [191 : 0]  aes_key,
    input wire [30 : 0]   pcode_speeds,
    input wire [47 : 0]   pcode_initializers,
    input wire            startRound,
    output wire [12 : 0]  ca_code,
    output wire [127 : 0] p_code,
    output wire [127 : 0] l_code,
    output wire           l_code_valid,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = GPS_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [12:0]                   mock_tss_ca_code;
  wire [127:0]                  mock_tss_p_code;
  wire [127:0]                  mock_tss_l_code;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (sys_clk),
    .rst                  (sync_rst_in),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign ca_code              = GPS_MOCK_TSS_KEY_WORDS[4][12:0] ^
                                llkid_key_register[268:256] ^
                                mock_tss_ca_code;
  assign p_code[63:0]         = GPS_MOCK_TSS_KEY_WORDS[0] ^
                                llkid_key_register[63:0] ^
                                mock_tss_p_code[63:0];
  assign p_code[127:64]       = GPS_MOCK_TSS_KEY_WORDS[1] ^
                                llkid_key_register[127:64] ^
                                mock_tss_p_code[127:64];
  assign l_code[63:0]         = GPS_MOCK_TSS_KEY_WORDS[2] ^
                                llkid_key_register[191:128] ^
                                mock_tss_l_code[63:0];
  assign l_code[127:64]       = GPS_MOCK_TSS_KEY_WORDS[3] ^
                                llkid_key_register[255:192] ^
                                mock_tss_l_code[127:64];
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  gps gps_inst (
    .sys_clk            (sys_clk),
    .sync_rst_in        (sync_rst_in || sync_rst_in_dut),
    .sv_num             (sv_num),
    .aes_key            (aes_key),
    .pcode_speeds       (pcode_speeds),
    .pcode_initializers (pcode_initializers),
    .startRound         (startRound),
    .ca_code            (mock_tss_ca_code),
    .p_code             (mock_tss_p_code),
    .l_code             (mock_tss_l_code),
    .l_code_valid       (l_code_valid)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      pcode.v
// Program:        Common Evaluation Platform (CEP)
// Description:    P-code generator
//
//************************************************************************
module pcode(
           clk, reset, prn_changed, en, sat,
           preg, xn_cnt_speed, z_cnt_speed,
           ini_x1a, ini_x1b, ini_x2a, ini_x2b
       );
parameter SAT_WIDTH = 6;
parameter SREG_WIDTH = 37;
parameter XREG_WIDTH = 12;
input clk;
input reset;
input prn_changed;
input en;
input [ SAT_WIDTH-1:0] sat;
output wire preg; //Combinational output
//Verification-focused inputs
input [11:0] xn_cnt_speed; //default must be 1.
input [18:0] z_cnt_speed; //default must be 1.
input [11:0] ini_x1a;     //default must be 12'b001001001000;
input [11:0] ini_x1b;     //default must be 12'b010101010100;
input [11:0] ini_x2a;     //default must be 12'b100100100101;
input [11:0] ini_x2b;     //default must be 12'b010101010100;
wire rst = reset | prn_changed;
   
reg[XREG_WIDTH-1:0] x1a;
reg[XREG_WIDTH-1:0] x1b;
reg[XREG_WIDTH-1:0] x2a;
reg[XREG_WIDTH-1:0] x2b;
reg [SREG_WIDTH:0] sreg; //Note that sat is 1-based!
wire x1a_rst, x1b_rst, x2a_rst, x2b_rst;
wire x1a_cnt_d, x1b_cnt_d, x2a_cnt_d, x2b_cnt_d, x_cnt_d, z_cnt_last, z_cnt_eow, x1a_cnt_last;
reg[XREG_WIDTH-1:0] x1a_cnt, x1b_cnt, x2a_cnt, x2b_cnt;
reg[SAT_WIDTH-1:0] x_cnt;
reg[18:0] z_cnt;
wire x1b_en, x2a_en, x2b_en;
reg x1b_en_r, x2a_en_r, x2b_en_r;
wire x1b_res, x2a_res, x2b_res;
wire x1b_halt, x2a_halt, x2b_halt;
//////////////////////////////////////////
//Control Signals
//////////////////////////////////////////
assign x1b_res = x1a_cnt_d & x1a_rst;
assign x1b_halt= (x1b_cnt_d|x1a_cnt_last) & x1b_rst;
assign x2a_res = /*!x1a_cnt_d  &*/ (z_cnt_eow|x_cnt_d); //If on last cycle of X1A, do not continue
assign x2a_halt= (z_cnt_eow|x2a_cnt_d|x1a_cnt_last) & x2a_rst;
assign x2b_res = x2a_res;
assign x2b_halt= (z_cnt_eow|x2b_cnt_d|x1a_cnt_last) & x2b_rst;
assign z_cnt_last = (z_cnt >= 19'd403200-z_cnt_speed);
assign z_cnt_eow = (z_cnt_last & x1b_res);
assign x1a_cnt_last = x1a_cnt_d & z_cnt_last;
//////////////////////////////////////////
//Clock Control Signals
//////////////////////////////////////////
assign x1b_en = x1b_en_r & !x1b_halt;
assign x2a_en = x2a_en_r & !x2a_halt;
assign x2b_en = x2b_en_r & !x2b_halt;
always @(posedge clk)
    begin
        if(rst)
            x1b_en_r<=1;
        else if(en) begin
            if(x1b_res)
                x1b_en_r<=1;
            else if(x1b_halt)
                x1b_en_r<=0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x2a_en_r<=1;
        else if(en) begin
            if(x2a_res)
                x2a_en_r<=1;
            else if(x2a_halt)
                x2a_en_r<=0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x2b_en_r<=1;
        else if(en) begin
            if(x2b_res)
                x2b_en_r<=1;
            else if(x2b_halt)
                x2b_en_r<=0;
        end
    end
//////////////////////////////////////////
//Decoders
//////////////////////////////////////////
assign x1a_rst = (x1a==12'b000100100100); //4092nd state
assign x1b_rst = (x1b==12'b001010101010); //4093rd state
assign x2a_rst = (x2a==12'b110010010010); //4092nd state
assign x2b_rst = (x2b==12'b001010101010); //4093rd state
//////////////////////////////////////////
//Counters
//////////////////////////////////////////
assign x1a_cnt_d = (x1a_cnt>=12'd3750-xn_cnt_speed); //Comparison instead of equality due to configurable counter increment
assign x1b_cnt_d = (x1b_cnt>=12'd3749-xn_cnt_speed);
assign x2a_cnt_d = (x2a_cnt>=12'd3750-xn_cnt_speed);
assign x2b_cnt_d = (x2b_cnt>=12'd3749-xn_cnt_speed);
assign x_cnt_d   = (x_cnt  ==6'd37);
always @(posedge clk)
    begin
        if(rst)
            x1a_cnt  <=0;
        else if(en & x1a_rst) begin
            if (!x1a_cnt_d)
                x1a_cnt <= x1a_cnt+xn_cnt_speed;
            else
                x1a_cnt <= 12'd0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x1b_cnt <=0;
        else if(en & x1b_rst & x1b_en_r) begin //TODO: x1b_en_r?
            if (!x1b_cnt_d & !x1a_cnt_last)
                x1b_cnt <= x1b_cnt+xn_cnt_speed;
            else
                x1b_cnt <= 12'd0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x2a_cnt<=0;
        else if(en & x2a_rst & x2a_en_r) begin
            if (!x2a_cnt_d & !x1a_cnt_last)
                x2a_cnt <= x2a_cnt+xn_cnt_speed;
            else
                x2a_cnt <=12'd0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x2b_cnt  <=0;
        else if(en & x2b_rst & x2b_en_r) begin
            if (!x2b_cnt_d & !x1a_cnt_last)
                x2b_cnt <= x2b_cnt+xn_cnt_speed;
            else
                x2b_cnt <=12'd0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            x_cnt<=0;
        else if(en & ((x2a_rst & x2a_cnt_d) | (x_cnt!=0))) begin
            if(x_cnt < 6'd37)
                x_cnt <= x_cnt+1;
            else
                x_cnt <= 6'd0;
        end
    end
always @(posedge clk)
    begin
        if(rst)
            z_cnt<=0;
        else if(en & x1b_res) begin
            if (!z_cnt_last)
                z_cnt <= z_cnt+z_cnt_speed;
            else
                z_cnt <=19'd0;
        end
    end
//////////////////////////////////////////
//4 shift registers
//////////////////////////////////////////
always @(posedge clk)
    begin
        if(rst|x1a_rst)
            x1a<=ini_x1a;
        else if(en)
            x1a<={x1a[XREG_WIDTH-2:0],x1a[5]^x1a[7]^x1a[10]^x1a[11]};
    end
always @(posedge clk)
    begin
        //If enabled, handle resume/reset immediately.
        //Keep in mind that *_en update is delayed 1 cycle from *_halt, but need to halt immediately.
        if(rst | (en & (x1b_res | (x1b_rst & x1b_en))))
            x1b<=ini_x1b;
        else if (en & x1b_en)
            x1b<={x1b[XREG_WIDTH-2:0],x1b[0]^x1b[1]^x1b[4]^x1b[7]^x1b[8]^x1b[9]^x1b[10]^x1b[11]};
    end
always @(posedge clk)
    begin
        if(rst | (en & (x2a_res | (x2a_rst & x2a_en))))
            x2a<=ini_x2a;
        else if (en & x2a_en)
            x2a<={x2a[XREG_WIDTH-2:0],x2a[0]^x2a[2]^x2a[3]^x2a[4]^x2a[6]^x2a[7]^x2a[8]^x2a[9]^x2a[10]^x2a[11]};
    end
always @(posedge clk)
    begin
        if (rst | (en & (x2b_res | (x2b_rst & x2b_en))))
            x2b<=ini_x2b;
        else if (en & x2b_en)
            x2b<={x2b[XREG_WIDTH-2:0],x2b[1]^x2b[2]^x2b[3]^x2b[7]^x2b[8]^x2b[11]};
    end
//x2 shift register
always @(posedge clk)
    begin
        if(rst)
            sreg<={SREG_WIDTH{1'b1}};
        else if(en)
            sreg<={sreg[SREG_WIDTH-1:0], (x2a[XREG_WIDTH-1]^x2b[XREG_WIDTH-1])};
    end
//Output
assign preg = (rst | (sat==0)) ? 1'b0 : (x1a[XREG_WIDTH-1]^x1b[XREG_WIDTH-1]) ^ sreg[sat-1]; 
endmodule
 | 
| 
	[//]: # (Copyright 2022 Massachusets Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   Copyright 2022 Massachusets Institute of Technology
</p>
# GPS code generator
Generates three codes used for GPS signal correlation (from the perspective of a space vehicle): C/A-code, P-code, and a secure form of P-code that we call L-code.  The combination of the P-code generator and the L-code is meant to serve as a surrogate for the M-code generator found in modern secure GPS systems.  The goal of this core is to provide reference implementations for items that a GPS designer would like to protect from an untrusted manufacturer; it is not a fully-functional GPS unit.
## Functionality:
While this block generates accurate P-code and C/A-code sequences, it does not implement the GPS spec exactly. Notable differences:
* "L-code" is a proxy for the M-code, and in this implementation just encrypts with AES in 128 bit blocks.
  * Note that the default AES key is currently 0x00000... This can be customized as needed in gps.scala
* Generates batches of 128 bits of the P-code and 13 bits of C/A-code, which roughly approximates the 10:1 ratio of a real GPS device. Likewise real GPS systems have precise timing specifications which are not followed here.
## References
* https://www.gps.gov/technical/icwg/IS-GPS-200K.pdf
* https://www.mitre.org/publications/technical-papers/overview-of-the-gps-m-code-signal
* https://natronics.github.io/blag/2014/gps-prn/
* https://github.com/kristianpaul/gnsssdr/blob/master/ARM_FPGA_PROJECTS/Xilinx_ISE_14.1_namuru_project_for_async_memory_bus/code_gen.v
* http://www.ohio.edu/people/starzykj/network/research/Papers/Recent%20conferences/Pcode_Generator_FPGA_FPLA2002.pdf
* https://etd.ohiolink.edu/!etd.send_file?accession=ohiou1177700503&disposition=inline
* https://www.navcen.uscg.gov/pubs/gps/icd200/ICD200Cw1234.pdf
* https://patents.google.com/patent/US5068872
* https://patents.google.com/patent/US5202694
* https://patents.google.com/patent/US6567042
#### Return to the root CEP [README](../../README.md) | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:       llki_pkg.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     LLKI related parameters and such.
// Notes:           Addresses MUST reside "within" the corresponding
//                  range as specified in cep_addresses.scala.
//              
//                  The address and bitmappings here should match
//                  those in CEP.h (to allow for SW access)
//
//************************************************************************
// The following is a "dummy" module that facilitates addResources in the
// cep_registers.scala file (which has no real blackbox)
module import_resources (); endmodule
package llki_pkg;
    // SROT Control / Status Register
    localparam SROT_CTRLSTS_ADDR                = 32'h7020_0000;
    localparam SROT_CTRLSTS_MODEBIT_0           = 0;    // If either mode bit is set, TileLink access to the Key and Key Index RAMs are disabled
    localparam SROT_CTRLSTS_MODEBIT_1           = 1;    // These bits are SET ONLY    
    localparam SROT_CTRLSTS_RESP_WAITING        = 2;    // Indicates that a message/response is available in the SROT_RESPONSE_ADDR register
    localparam SROT_LLKIC2_SENDRECV_ADDR        = 32'h7020_0008;
    localparam SROT_LLKIC2_SCRATCHPAD0_ADDR     = 32'h7020_0010;
    localparam SROT_LLKIC2_SCRATCHPAD1_ADDR     = 32'h7020_0018;
    // See KeyIndexRAM explanation below
    localparam SROT_KEYINDEXRAM_ADDR            = 32'h7020_0100;
    localparam SROT_KEYINDEXRAM_SIZE            = 32'h0000_0020;	// 32 64-bit words
    // Holds the LLKI keys as referenced by the those words in the KeyIndex RAM
    // Note: This cannot be less than SROT_KEYINDEXRAM_ADDR + (SROT_KEYINDEXRAM_SIZE * 8)!!!
    localparam SROT_KEYRAM_ADDR                 = 32'h7020_0200;
    localparam SROT_KEYRAM_SIZE                 = 32'h0000_0800;	// 2048 64-bit words
    // All LLKI Protocol Processing blocks will use the same SystemVerilog code, and thus
    // will have their decode addresses uniquified through module parameters.  These will be
    // passed down from the Chisel level of the design (and ths the addresses are contained
    // in cep_addresses.scala).  Common parameters (such as the LLKI_CTRLSTS_RESP_WAITING
    // bit mapped will be contained here)
    localparam  LLKIKL_CTRLSTS_RESP_WAITING     = 0;    // Indicates that a message/response is available 
                                                        // in the LLKI PP control/status register
    localparam  LLKIKL_CTRLSTS_READY_FOR_KEY    = 1;    // The LLKI-PP provides minimal buffering for
                                                        // messages (and key words) received from
                                                        // Thus,  the SRoT can poll the ready for key
                                                        // bit in the LLKI-PP Control/Status register
                                                        // to determine that the LLKI-PP (and TSS) is
                                                        // ready to receive the next key word
    // The Key Index RAM holds single word identifiers that contain
    // metadata for all the keys stored in the Key RAM
    //
    // 63 62                 40 39       32 31            16 15             0
    // +-+---------------------+-----------+----------------+----------------+ 
    // |V|      Reserved       | Core Indx |  High Pointer  |  Low Pointer   |
    // +-+---------------------+-----------+----------------+----------------+ 
    //
    // Field descriptions:
    //  - Valid             : Indicates a valid key index and valid key material in the
    //                        range identified to by the high and low pointers
    //  - Core Indx         : Pointer to an entry in LLKI_CORE_INDEX_ARRAY that determines
    //                        which LLKI-enabled core is the target of the current operation
    //                        Constant definitions are located in DevKitsConfig.scala under
    //                        the U500DevKitPeripherals class (SROTKey)
    //  - High Pointer      : Upper Key RAM addr
    //  - Low Pointer       : Lower Key RAM addr
    //
    // For a valid key index, the key data words should be located in the
    // Key RAM as described here:  Higher Pointer >= Key#N >= Low Pointer
    //
    // This error condition as well as other are checked i n the ST_RETRIEVE_KEY_INDEX state 
    // of the SRoT state machine (in srot_wrapper.sv)
    //
    localparam LLKI_CTRLSTS_OFFSET        = 32'h0;
    localparam LLKI_SENDRECV_OFFSET       = 32'h8;
    //
    // The LLKI is comprised of the following three interface types:
    //      LLKI-C2         : Using Tilelink, it supports the following message types:
    //                          C2LoadKeyReq        : Load a key into the specified Core
    //                          C2ClearKeyReq       : Clear the key from the specified Core
    //                          C2KeyStatusReq      : Request key status from the specified Core
    //                          C2LoadKeyAck        : Load key acknowledgement
    //                          C2ClearKeyAck       : Clear key acknowledgement
    //                          C2KeyStatusResp     : Response to the Key Status Requests
    //      LLKI-KL         : Using Tilelink, it supports the following message types:
    //                          KLLoadKeyReq        : Load a key into the specified Core
    //                          KLClearKeyReq       : Clear the key from the specified Core
    //                          KLKeyStatusReq      : Request key status from the specified Core
    //                          KLLoadKeyAck        : Load key acknowledgement
    //                          KLClearKeyAck       : Clear key acknowledgement
    //                          KLKeyStatusResp     : Response to the Key Status Requests    
    //      LLKI-Discrete   : Discrete signals for connecting the LLKI to Technique Specific Shims
    //                          llkid_key_data      : Key Data Bits, greater key widths loaded over multiple clock cycles
    //                          llkid_key_valid     : Indicates that the key data is valid
    //                          llkid_key_ready     : Indicates that the TSS is ready to receive key data
    //                          llkid_key_complete  : Indicates that the TSS has received all the required key bits
    //                          llkid_clear_key     : Assert to instruct the TSS to clear its internal key-state, thus "locking" the core
    //                          llkid_clear_key_ack : When asserted by the TSS, it indicates that the key has been cleared
    //
    //
    // LLKI C2 RISCV -> SRoT Message Format
    //
    //                                                                         Word#
    // 63                       40 39   32 31             16 15     8 7      0  
    // +----------------------------------+-----------------+--------+--------+ 
    // |             Reserved     |Key Idx|     MSG LEN     | STATUS | MSG ID |  1
    // +----------------------------------+-----------------+--------+--------+ 
    //
    // MSG ID : Only the following message IDs are valid on the LLKIC2 request interface:
    //  - LLKI_MID_C2LOADKEYREQ
    //  - LLKI_MID_C2CLEARKEYREQ
    //  - LLKI_MID_C2KEYSTATUSREQ
    //
    // STATUS :
    //  - Unused for C2 RISCV -> SRoT Messages
    //
    // MSG LEN :
    //  - Should be 1 for all C2 RISCV -> SRoT Messages
    //
    // Key Idx : Specifies the index of the key to be referenced by the request.  This
    //  becomes a direct index into the Key Index RAM, which contains all the key
    //  specific metadata.  See Key Index RAM format above for more information.
    // LLKI Message ID constants
    localparam  LLKI_MID_C2LOADKEYREQ           = 8'h00;
    localparam  LLKI_MID_C2CLEARKEYREQ          = 8'h01;
    localparam  LLKI_MID_C2KEYSTATUSREQ         = 8'h02;
    localparam  LLKI_MID_C2LOADKEYACK           = 8'h03;
    localparam  LLKI_MID_C2CLEARKEYACK          = 8'h04;
    localparam  LLKI_MID_C2KEYSTATUSRESP        = 8'h05;
    localparam  LLKI_MID_C2ERRORRESP            = 8'h06;
    // LLKI KL SRoT -> LLKI PP Message Format
    // NOTE: Each word transferred is a SEPERATE Tilelink transaction
    //
    //                                                                         Word#
    // 63                       40 39   32 31             16 15     8 7      0  
    // +----------------------------------+-----------------+--------+--------+ 
    // |             Reserved     |Key Idx|     MSG LEN     | STATUS | MSG ID |  1
    // +----------------------------------+-----------------+--------+--------+ 
    //                                      ...
    // +----------------------------------------------------------------------+
    // |             Key Word #1 (LLKI_MID_KLLOADKEYREQ message only)         |  2
    // +----------------------------------------------------------------------+
    //                                      ...
    // +----------------------------------------------------------------------+
    // |             Key Word #N (LLKI_MID_KLLOADKEYREQ message only)         |  N + 1
    // +----------------------------------------------------------------------+
    //
    //
    // MSG ID : Only the following message IDs are valid on the LLKIC2 request interface:
    //  - LLKI_MID_C2LOADKEYREQ
    //  - LLKI_MID_C2CLEARKEYREQ
    //  - LLKI_MID_C2KEYSTATUSREQ
    localparam  LLKI_MID_KLLOADKEYREQ           = 8'h07;
    localparam  LLKI_MID_KLCLEARKEYREQ          = 8'h08;
    localparam  LLKI_MID_KLKEYSTATUSREQ         = 8'h09;
    localparam  LLKI_MID_KLLOADKEYACK           = 8'h0A;
    localparam  LLKI_MID_KLCLEARKEYACK          = 8'h0B;
    localparam  LLKI_MID_KLKEYSTATUSRESP        = 8'h0C;
    localparam  LLKI_MID_KLERRORRESP            = 8'h06;
    // LLKI Status Constants
    localparam  LLKI_STATUS_GOOD                = 8'h00;    // Indication by the LLKI PP that a request has been successfully
                                                            // processed
    localparam  LLKI_STATUS_KEY_PRESENT         = 8'h01;    // In response to a LLKI_MID_KL/C2KEYSTATUSREQ, indicates that the
                                                            // target core has a key present
    localparam  LLKI_STATUS_KEY_NOT_PRESENT     = 9'h02;    // In response to a LLKI_MID_KL/C2KEYSTATUSREQ, indicates that the
                                                            // target core does not have a key present
    localparam  LLKI_STATUS_BAD_MSG_ID          = 8'h20;    // A message ID received via the LLKI-C2 interface is not valid
    localparam  LLKI_STATUS_BAD_MSG_LEN         = 8'h21;    // All messages received via the LLKI-C2 interface have an expected
                                                            // message length of 1
    localparam  LLKI_STATUS_KEY_INDEX_EXCEED    = 8'h22;    // Specified key index in the LLKI-KL message exceeds the size of the Key Index
                                                            // RAM and thus cannot be valid
    localparam  LLKI_STATUS_KEY_INDEX_INVALID   = 8'h23;    // The key index referenced by the LLKI-KL message does not have a valid bit set and
                                                            // thus is invalid
    localparam  LLKI_STATUS_BAD_POINTER_PAIR    = 8'h24;    // A Key Index entry that was previously loaded in which either of the pointers were in 
                                                            // excess of the Key RAM size OR the low pointer > high pointer
    localparam  LLKI_STATUS_BAD_CORE_INDEX      = 8'h25;    // The Core Index, which is used as a pointer to of the available cores, exceeeds the
                                                            // the highest entry in LLKI_CORE_INDEX_ARRAY
    localparam  LLKI_STATUS_KL_REQ_BAD_MSG_ID   = 8'h26;    // The LLKI PP received a bad message ID from the SRoT
    localparam  LLKI_STATUS_KL_REQ_BAD_MSG_LEN  = 8'h27;    // The LLKI PP received a message with a bad length from the SRoT
    localparam  LLKI_STATUS_KL_RESP_BAD_MSG_ID  = 8'h28;    // The SRoT has received a response from the selected LLKI PP with a bad message ID
    localparam  LLKI_STATUS_KL_TILELINK_ERROR   = 8'h29;    // A tilelink error was detected on the SRoT -> LLKI PP (LLKI-KL) interface
    localparam  LLKI_STATUS_KL_LOSS_OF_SYNC     = 8'h30;    // There has been a synchronization error between the selected LLKI PP and TSS
    localparam  LLKI_STATUS_KL_BAD_KEY_LEN      = 8'h31;    // A key has been loaded into the specificed LLKI-PP whose length does not match
                                                            // the expected length
    localparam  LLKI_STATUS_KL_KEY_OVERWRITE    = 8'h32;    // A key load has been attempted on a core that already has one
    localparam  LLKI_STATUS_UNKNOWN_ERROR       = 8'hFF;    // An unknown LLKI error has been detected
    // Value is used to initalize the SRoT STM wait state
    // counter.  This mitigates spamming the SRoT host
    // interface while waiting for a response from the
    // selected LLKI-KP
    localparam  SROT_WAIT_STATE_COUNTER_INIT    = 8'h0A;
    // Enumerated type for Surrogate Root of Trust state machine.  State
    // decscriptions can be found in srot_wrapper.sv
    typedef enum {
        ST_SROT_IDLE,
        ST_SROT_MESSAGE_CHECK,
        ST_SROT_RETRIEVE_KEY_INDEX_WAIT_STATE,
        ST_SROT_RETRIEVE_KEY_INDEX,
        
        ST_SROT_KL_REQ_HEADER,
        ST_SROT_KL_REQ_ISSUE,
        ST_SROT_KL_REQ_WAIT_FOR_ACK,
        ST_SROT_KL_READ_READY_STATUS,
        ST_SROT_KL_CHECK_READY_STATUS,
        ST_SROT_KL_READY_WAIT_STATE,
        ST_SROT_KL_LOAD_KEY_WORD,
        ST_SROT_KL_LOAD_KEY_WORD_WAIT_FOR_ACK,
        ST_SROT_KL_READ_RESP_STATUS,
        ST_SROT_KL_CHECK_RESP_STATUS,
        ST_SROT_KL_RESP_WAIT_STATE,
        ST_SROT_KL_RESP_READ,
        ST_SROT_C2_RESPONSE
    } SROT_STATE_TYPE;  
    // Enumerate type for the LLKI Protocol Processing block state machine
    typedef enum {
        ST_LLKIPP_IDLE,
        ST_LLKIPP_MESSAGE_CHECK,
        ST_LLKIPP_LOAD_KEY_WORDS,
        ST_SROT_KL_WAIT_FOR_COMPLETE,
        ST_LLKIPP_CLEAR_KEY,
        ST_LLKIPP_RESPONSE
    } LLKIPP_STATE_TYPE;
    // The Mock TSS introduces artificial wait states to demonstrate
    // a delay when loading or clearing keys
    typedef enum {
        ST_MOCKTSS_IDLE,
        ST_MOCKTSS_WAIT_STATE0,
        ST_MOCKTSS_WAIT_FOR_NEXT_KEY_WORD,
        ST_MOCKTSS_CLEAR_KEY,
        ST_MOCKTSS_WAIT_STATE1,
        ST_MOCKTSS_WAIT_STATE2
    } MOCKTSS_STATE_TYPE;
    localparam  MOCKTSS_WAIT_STATE_COUNTER_INIT     = 8'h0A;
    // The following parameters are used by the AES instance of the Mock Technique Specific Shim (TSS)
    localparam AES_MOCK_TSS_NUM_KEY_WORDS       = 2;
    localparam [63:0] AES_MOCK_TSS_KEY_WORDS [0:AES_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'hAE53456789ABCDEF,
        64'hFEDCBA9876543210
    };
    // The following parameters are used by the DES3 instance of the Mock Technique Specific Shim (TSS)
    localparam DES3_MOCK_TSS_NUM_KEY_WORDS      = 1;
    localparam [63:0] DES3_MOCK_TSS_KEY_WORDS [0:DES3_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'hDE53456789ABCDEF
    };
    // The following parameters are used by the SHA256 instance of the Mock Technique Specific Shim (TSS)
    localparam SHA256_MOCK_TSS_NUM_KEY_WORDS    = 8;
    localparam [63:0] SHA256_MOCK_TSS_KEY_WORDS [0:SHA256_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h54A3456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210
    };
    // The following parameters are used by the MD5 instance of the Mock Technique Specific Shim (TSS)
    localparam MD5_MOCK_TSS_NUM_KEY_WORDS    = 8;
    localparam [63:0] MD5_MOCK_TSS_KEY_WORDS [0:MD5_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h3D53456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210
    };
    // The following parameters are used by the RSA (modexp_core) instance of the Mock Technique Specific Shim (TSS)
    localparam RSA_MOCK_TSS_NUM_KEY_WORDS    = 1;
    localparam [63:0] RSA_MOCK_TSS_KEY_WORDS [0:RSA_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h45A3456789ABCDEF
    };
    // The following parameters are used by the IIR instance of the Mock Technique Specific Shim (TSS)
    localparam IIR_MOCK_TSS_NUM_KEY_WORDS    = 1;
    localparam [63:0] IIR_MOCK_TSS_KEY_WORDS [0:IIR_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h1143456789ABCDEF
    };
    // The following parameters are used by the FIR instance of the Mock Technique Specific Shim (TSS)
    localparam FIR_MOCK_TSS_NUM_KEY_WORDS    = 1;
    localparam [63:0] FIR_MOCK_TSS_KEY_WORDS [0:FIR_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'hF143456789ABCDEF
    };
    // The following parameters are used by the DFT instance of the Mock Technique Specific Shim (TSS)
    localparam DFT_MOCK_TSS_NUM_KEY_WORDS    = 1;
    localparam [63:0] DFT_MOCK_TSS_KEY_WORDS [0:DFT_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'hDF73456789ABCDEF
    };
    // The following parameters are used by the IDFT instance of the Mock Technique Specific Shim (TSS)
    localparam IDFT_MOCK_TSS_NUM_KEY_WORDS   = 1;
    localparam [63:0] IDFT_MOCK_TSS_KEY_WORDS [0:IDFT_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h1DF7456789ABCDEF
    };
    // The following parameters are used by the GPS instance of the Mock Technique Specific Shim (TSS)
    localparam GPS_MOCK_TSS_NUM_KEY_WORDS    = 5;
    localparam [63:0] GPS_MOCK_TSS_KEY_WORDS [0:GPS_MOCK_TSS_NUM_KEY_WORDS - 1] = '{
        64'h6953456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF,
        64'hFEDCBA9876543210,
        64'h0123456789ABCDEF
    };
endpackage
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       llki_pp_wrapper.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     This file provides a Verilog <-> SystemVerilog adapter
//                  allowing connection of TL-UL interface to the Chisel
//                  blackbox.  
//
//                  It also implements the LLKI Protocol Processing
//                  block's State Machine.
// Notes:           The underlying TL-UL package is from the OpenTitan
//                  project.
//
//                  Send / Recv FIFOs have specifically NOT been
//                  implemented here in an effort to minimize the number
//                  of memory blocks that ever touch key material.
//
//                  The LLKI Protocol Procesing block is intended to be
//                  common across ALL LLKI enabled cores.  Unique address
//                  decoding will be facilitated through the use of the
//                  CTRLSTS_ADDR and SENDRECV_ADDR parameters (which are
//                  passed down from Chisel)
//
//************************************************************************
`timescale 1ns/1ns
`include "prim_assert.sv"
module llki_pp_wrapper import tlul_pkg::*; import llki_pkg::*; #(
  parameter int CTRLSTS_ADDR    = 32'h00000000,   // These default values MUST be overwritten
  parameter int SENDRECV_ADDR   = 32'h00000008,   // These default values MUST be overwritten
  parameter SLAVE_TL_SZW        = top_pkg::TL_SZW,
  parameter SLAVE_TL_AIW        = top_pkg::TL_AIW,
  parameter SLAVE_TL_AW         = top_pkg::TL_AW,
  parameter SLAVE_TL_DBW        = top_pkg::TL_DBW,
  parameter SLAVE_TL_DW         = top_pkg::TL_DW,
  parameter SLAVE_TL_DIW        = top_pkg::TL_DIW
 ) (
  // Clock and reset
  input                         clk,
  input                         rst,
  // Slave interface A channel
  input [2:0]                     slave_a_opcode,
  input [2:0]                     slave_a_param,
  input [SLAVE_TL_SZW-1:0]        slave_a_size,
  input [SLAVE_TL_AIW-1:0]        slave_a_source,
  input [SLAVE_TL_AW-1:00]        slave_a_address,
  input [SLAVE_TL_DBW-1:0]        slave_a_mask,
  input [SLAVE_TL_DW-1:0]         slave_a_data,
  input                           slave_a_corrupt,
  input                           slave_a_valid,
  output                          slave_a_ready,
  // Slave interface D channel
  output [2:0]                    slave_d_opcode,
  output [2:0]                    slave_d_param,
  output reg [SLAVE_TL_SZW-1:0]   slave_d_size,
  output reg [SLAVE_TL_AIW-1:0]   slave_d_source,
  output reg [SLAVE_TL_DIW-1:0]   slave_d_sink,
  output                          slave_d_denied,
  output [SLAVE_TL_DW-1:0]        slave_d_data,
  output                          slave_d_corrupt,
  output                          slave_d_valid,
  input                           slave_d_ready,
  // LLKI discrete I/O
  output reg [63:0]               llkid_key_data,
  output reg                      llkid_key_valid,
  input                           llkid_key_ready,
  input                           llkid_key_complete,
  output reg                      llkid_clear_key,
  input                           llkid_clear_key_ack
);
  // Create the structures for communicating with OpenTitan-based Tilelink
  tl_h2d_t                      slave_tl_h2d;
  tl_d2h_t                      slave_tl_d2h;
  // In the OpenTitan world, TL buses are encapsulated with the structures instantitated above
  // and as defined in top_pkg.sv.  This includes field widths.
  //
  // In the RocketChip world, some field widths will vary based on the other system components
  // (e.g., source and sink widths).  In order to provide maximum flexibility, without breaking
  // OpenTitan, top_pkg.sv is going to be defined with field maximum expected widths within
  // the CEP ecosystem.
  //
  // The following assignments, coupled with the parameters passed to this component will 
  // provide for a flexible assignment, when necessary.  Assertions will be used to capture
  // a mismatch when the widths in the OpenTitan world are not large enough to encapsulate
  // what is being passed from RocketChip.
  //
  // DW/DBW (Data bus width) must be equal in both worlds
  
  `ASSERT_INIT(srot_slaveTlSzw, top_pkg::TL_SZW >= SLAVE_TL_SZW)
  `ASSERT_INIT(srot_slaveTlAiw, top_pkg::TL_AIW >= SLAVE_TL_AIW)
  `ASSERT_INIT(srot_slaveTlAw, top_pkg::TL_AW >= SLAVE_TL_AW)
  `ASSERT_INIT(srot_slaveTlDbw, top_pkg::TL_DBW == SLAVE_TL_DBW)
  `ASSERT_INIT(srot_slaveTlDw, top_pkg::TL_DW == SLAVE_TL_DW)
  
  always @*
  begin
    slave_tl_h2d.a_size                         <= '0;
    slave_tl_h2d.a_size[SLAVE_TL_SZW-1:0]       <= slave_a_size;
    slave_tl_h2d.a_source                       <= '0;
    slave_tl_h2d.a_source[SLAVE_TL_AIW-1:0]     <= slave_a_source;
    slave_tl_h2d.a_address                      <= '0;
    slave_tl_h2d.a_address[SLAVE_TL_AW-1:0]     <= slave_a_address;
    
    slave_d_size                                <= slave_tl_d2h.d_size[SLAVE_TL_SZW-1:0];
    slave_d_source                              <= slave_tl_d2h.d_source[SLAVE_TL_AIW-1:0];
    slave_d_sink                                <= slave_tl_d2h.d_sink[SLAVE_TL_DIW-1:0];
  end
  // Make Slave A channel connections
  assign slave_tl_h2d.a_valid     = slave_a_valid;
  assign slave_tl_h2d.a_opcode    = ( slave_a_opcode == 3'h0) ? PutFullData : 
                                    ((slave_a_opcode == 3'h1) ? PutPartialData : 
                                    ((slave_a_opcode == 3'h4) ? Get : 
                                      Get));                                   
  assign slave_tl_h2d.a_param     = slave_a_param;
  assign slave_tl_h2d.a_mask      = slave_a_mask;
  assign slave_tl_h2d.a_data      = slave_a_data;
  assign slave_tl_h2d.a_user      = tl_a_user_t'('0);  // User field is unused by Rocket Chip
  assign slave_tl_h2d.d_ready     = slave_d_ready;
  
  // Make Slave D channel connections
  // Converting from the OpenTitan enumerated type to specific bit mappings
  assign slave_d_opcode         = ( slave_tl_d2h.d_opcode == AccessAck)     ? 3'h0 :
                                  ((slave_tl_d2h.d_opcode == AccessAckData) ? 3'h1 :
                                    3'h0);
  assign slave_d_param          = slave_tl_d2h.d_param;
  assign slave_d_denied         = slave_tl_d2h.d_error;
  assign slave_d_data           = slave_tl_d2h.d_data;
  assign slave_d_corrupt        = slave_tl_d2h.d_error;
  assign slave_d_valid          = slave_tl_d2h.d_valid;
  assign slave_a_ready          = slave_tl_d2h.a_ready;
  // Define some of the wires and registers associated with the tlul_adapter_reg
  wire                          reg_we_o;
  wire                          reg_re_o;
  reg                           reg_we_o_d1;
  wire [top_pkg::TL_AW-1:0]     reg_addr_o;
  wire [top_pkg::TL_DW-1:0]     reg_wdata_o;
  reg [top_pkg::TL_DW-1:0]      reg_rdata_i;
  wire                          ack_i;
  reg                           reg_error_i;
  // Misc. signals
  reg [1:0]                     llkipp_ctrlstatus_register;   // Bit definition can be found in llki_pkg.sv
                                                              // Register width explicitly minimized to only
                                                              // the required bits (to increaase coverage)
  reg                           write_error;
  reg                           read_error;
  //------------------------------------------------------------------------
  // Instantitate a tlul_adapter_reg to adapt the TL Slave Interface
  //------------------------------------------------------------------------
  tlul_adapter_reg #(
    .RegAw          (top_pkg::TL_AW   ),
    .RegDw          (top_pkg::TL_DW   )
  ) u_tlul_adapter_reg_inst (
    .clk_i          (clk              ),
    .rst_ni         (~rst             ),
    .tl_i           (slave_tl_h2d     ),
    .tl_o           (slave_tl_d2h     ),
    .we_o           (reg_we_o         ),
    .re_o           (reg_re_o         ),
    .addr_o         (reg_addr_o       ),
    .wdata_o        (reg_wdata_o      ),
    .be_o           (                 ),  // Accesses are assumed to be word-wide
    .rdata_i        (reg_rdata_i      ),
    .ack_i          (ack_i            ),    // External acknowledgement of the
                                            // transaction
    .error_i        (reg_error_i      )
  );
  // The reg_error_i will be asserted if either a read or write error occurs
  assign reg_error_i    = read_error || write_error;
  // The acknowledgement signal allows for latching of the read data when
  // available (if it is a read) and/or proper processing of the
  // external error
  assign ack_i          = reg_re_o ||  reg_we_o_d1;
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Write Decode Process (writing to the state machine sendrecv address
  // be handled in the LLKI PP state machine)
  //------------------------------------------------------------------------
  reg                         llkipp_response_waiting;
  reg [top_pkg::TL_DW-1:0]    llkipp_response_word;
  always @(posedge clk or posedge rst)
  begin
    if (rst) begin
      llkipp_ctrlstatus_register    <= '0;
      write_error                   <= 1'b0;
      reg_we_o_d1                   <= 1'b0;
    end else begin
      // Registered version of the write enable
      reg_we_o_d1                   <= reg_we_o;
      // Default signal assignments
      write_error                   <= 1'b0;
      // Capture the message available state (setting and clearing
      // of the source bit will occur within the state machine always block)
      llkipp_ctrlstatus_register[LLKIKL_CTRLSTS_RESP_WAITING]   <= llkipp_response_waiting;
      // The LLKI-PP provides minimal buffering for messages (and key words) received from
      // Thus,  the SRoT can poll the ready for key bit in the LLKI-PP Control/Status register
      // to determine that the LLKI-PP (and TSS) is ready to receive the next key word
      llkipp_ctrlstatus_register[LLKIKL_CTRLSTS_READY_FOR_KEY]  <= llkid_key_ready;
      
      if (reg_we_o) begin
        case (reg_addr_o)
          // Currently, no Ctrl/Status bits are writeable via TileLink
          CTRLSTS_ADDR    : begin
            ;
          end
          // Write to Send/Recv Address - Data "capture" occurs within the
          // LLKI PP State Machine block, thus we have a null action here
          SENDRECV_ADDR  : begin
            ;
          end
          // Trap State - Currently, the control/status register has no
          // LLKI-PP writable bits and thus c
          default             : begin
            write_error               <= 1'b1;
          end
        endcase
      end // end if (reg_we_o)
    end // end if (rst)
  end // end always
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Read decode process
  //------------------------------------------------------------------------
  always @*
  begin
    // Default signal assignments
    reg_rdata_i             = '0;
    read_error              = 1'b0;
    if (reg_re_o) begin
      case (reg_addr_o)
        // Currently, no Ctrl/Status bits are writeable via TileLink
        // CTRLSTS_ADDR explicitly mapped (see llkipp_ctrlstatus_register decleration above)
        CTRLSTS_ADDR    : begin
          reg_rdata_i[1:0]  = llkipp_ctrlstatus_register;
        end
        // Write to Send/Recv Address - Data "capture" occurs within the
        // LLKI PP State Machine block, thus we have a null action here
        SENDRECV_ADDR  : begin
          reg_rdata_i       = llkipp_response_word;
        end
        // Trap State - Invalid addresses
        default             : begin
          read_error        = 1'b1;
        end
      endcase
    end // end if (reg_re_o)
  end // end always
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // LLKI PP State Machine
  //------------------------------------------------------------------------
  LLKIPP_STATE_TYPE           llkipp_current_state;
  reg [7:0]                   msg_id;
  reg [7:0]                   status;
  reg [15:0]                  msg_len;
  always @(posedge clk or posedge rst)
  begin
    if (rst) begin
      llkid_key_data                <= '0;
      llkid_key_valid               <= '0;
      llkid_clear_key               <= '0;
      llkipp_response_waiting       <= '0;
      llkipp_response_word          <= '0;
      msg_id                        <= '0;
      status                        <= '0;
      msg_len                       <= '0;
      llkipp_current_state          <= ST_LLKIPP_IDLE;
    end else begin
      case (llkipp_current_state)
        //------------------------------------------------------------------
        // IDLE State
        //------------------------------------------------------------------
        ST_LLKIPP_IDLE                  : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          msg_id                        <= '0;
          status                        <= '0;
          msg_len                       <= '0;
          llkipp_current_state          <= ST_LLKIPP_IDLE;
          // If a write occurs AND it's to the SENDRECV_ADDR
          if (reg_we_o && reg_addr_o == SENDRECV_ADDR) begin
            msg_id                      <= reg_wdata_o[7:0];
            status                      <= reg_wdata_o[15:8];
            msg_len                     <= reg_wdata_o[31:16];
            // Now that we have captured the message, time to process
            llkipp_current_state        <= ST_LLKIPP_MESSAGE_CHECK;
          end // end if (reg_we_o && reg_addr_o == SENDRECV_ADDR)
        end   // ST_LLKIPP_IDLE
        //------------------------------------------------------------------
        // Message Check State
        //------------------------------------------------------------------
        ST_LLKIPP_MESSAGE_CHECK         : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          llkipp_current_state          <= ST_LLKIPP_MESSAGE_CHECK;
          // Make some checks and decision based on the Message ID
          case (msg_id) 
            LLKI_MID_KLLOADKEYREQ       : begin
              // A message length of 1 (or zero) for a load key request
              // is invalid
              if (msg_len <= 1) begin
                msg_id                  <= LLKI_MID_KLERRORRESP;
                status                  <= LLKI_STATUS_KL_REQ_BAD_MSG_LEN;
                llkipp_current_state    <= ST_LLKIPP_RESPONSE;
              // If a key load attempt occurs when there is already a key, then
              // generate an error
              end else if (llkid_key_complete) begin
                msg_id                  <= LLKI_MID_KLERRORRESP;
                status                  <= LLKI_STATUS_KL_KEY_OVERWRITE;
                llkipp_current_state    <= ST_LLKIPP_RESPONSE;
              // A load key request has been issued, jump to the
              // load key words and wait for the next word (which
              // will be treated as a key word)
              end else
                llkipp_current_state    <= ST_LLKIPP_LOAD_KEY_WORDS;
            end
            LLKI_MID_KLCLEARKEYREQ      : begin
              // The only valid message length is 1
              if (msg_len != 1) begin
                msg_id                  <= LLKI_MID_KLERRORRESP;
                status                  <= LLKI_STATUS_KL_REQ_BAD_MSG_LEN;
                llkipp_current_state    <= ST_LLKIPP_RESPONSE;
              end else 
                llkipp_current_state    <= ST_LLKIPP_CLEAR_KEY;
            end
            LLKI_MID_KLKEYSTATUSREQ     : begin
              // The only valid message length is 1
              if (msg_len != 1) begin
                msg_id                  <= LLKI_MID_KLERRORRESP;
                status                  <= LLKI_STATUS_KL_REQ_BAD_MSG_LEN;
                llkipp_current_state    <= ST_LLKIPP_RESPONSE;
              end else begin
                msg_id                  <= LLKI_MID_KLKEYSTATUSRESP;
                // Set the status based on what state the LLKI-Discrete
                // interface indicates
                if (llkid_key_complete)
                  status                 <= LLKI_STATUS_KEY_PRESENT;
                else
                  status                 <= LLKI_STATUS_KEY_NOT_PRESENT;
                llkipp_current_state    <= ST_LLKIPP_RESPONSE;
              end
            end
            // All other message ID (error condition)
            default                     : begin
              msg_id                    <= LLKI_MID_KLERRORRESP;
              status                    <= LLKI_STATUS_KL_REQ_BAD_MSG_ID;
              llkipp_current_state      <= ST_LLKIPP_RESPONSE;
            end
          endcase   // msg id
        end   // ST_LLKIPP_MESSAGE_CHECK
        //------------------------------------------------------------------
        // Load Key Words State - This state will "pass" the key words
        // received over the LLKI-PP TileLink interface to the
        // LLKI-Discrete interface.
        //
        // It is the responsibility of the SRoT to read the status of the
        // key ready bit between EACH KEY WORD before sending the next one
        //------------------------------------------------------------------
        ST_LLKIPP_LOAD_KEY_WORDS        : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          llkipp_current_state          <= ST_LLKIPP_LOAD_KEY_WORDS;
          // Another key word has been received, time to do some checks
          if (reg_we_o && reg_addr_o == SENDRECV_ADDR) begin
            // If for some reason, the LLKI-Discrete is not ready, we'll
            // ignore the key word, and send an error response (which the
            // SRoT will need to check for)
            if (~llkid_key_ready) begin
              msg_id                    <= LLKI_MID_KLERRORRESP;
              status                    <= LLKI_STATUS_KL_LOSS_OF_SYNC;
              llkipp_current_state      <= ST_LLKIPP_RESPONSE;
            // We have attempted to load a key whose length does not match the expected
            // key length for this core.  Clear the core, and send an error response
            end else if (llkid_key_complete) begin
              msg_id                    <= LLKI_MID_KLERRORRESP;
              status                    <= LLKI_STATUS_KL_BAD_KEY_LEN;
              llkipp_current_state      <= ST_LLKIPP_CLEAR_KEY;
            // If a key word has been received and msg_len == 2, then this
            // is the LAST word of the load key request (understanding the
            // msg_len also includes the header and we are using it for
            // a counter.
            end else if (msg_len == 2) begin
              llkid_key_data            <= reg_wdata_o;
              llkid_key_valid           <= 1;
              msg_id                    <= LLKI_MID_KLLOADKEYACK;
              status                    <= LLKI_STATUS_GOOD;
              llkipp_current_state      <= ST_SROT_KL_WAIT_FOR_COMPLETE;
            // This is not the last word of the key load, load the key word
            // via the LLKI-Discrete and just wait for the next word
            end else begin
              llkid_key_data            <= reg_wdata_o;
              llkid_key_valid           <= 1;
              // Decrement the message length (be used to count the remaining
              // number of key words to load)
              msg_len                   <= msg_len - 1;
            end // end if (~llkid_key_ready)
          end // end if (reg_we_o && reg_addr_o == SENDRECV_ADDR)
        end   // ST_LLKIPP_LOAD_KEY_WORDS
        //------------------------------------------------------------------
        // After all key words have been loaded into the selected TSS,
        // wait for llkid_key_complete to be asserted before sending
        // the response 
        //------------------------------------------------------------------
        ST_SROT_KL_WAIT_FOR_COMPLETE  : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          llkipp_current_state          <= ST_SROT_KL_WAIT_FOR_COMPLETE;
          // When llkid_key_complete is asserted, then jump to sending the response
          if (llkid_key_complete) begin
            llkipp_current_state      <= ST_LLKIPP_RESPONSE;
          end // end if (llkid_key_complete)
        end // ST_SROT_KL_WAIT_FOR_COMPLETE
        //------------------------------------------------------------------
        // Clear Key State
        //------------------------------------------------------------------
        ST_LLKIPP_CLEAR_KEY             : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '1;  // Instruct TSS to clear the key
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          llkipp_current_state          <= ST_LLKIPP_CLEAR_KEY;
          // Clear Key has been acknowledged, time to send the response
          if (llkid_clear_key_ack) begin
            // If we got here due to a normal clear key request, then
            // we need to assign the msg_id and status, otherwise
            // just jump to the response state
            if (msg_id != LLKI_MID_KLERRORRESP) begin
              msg_id                    <= LLKI_MID_KLCLEARKEYACK;
              status                    <= LLKI_STATUS_GOOD;
            end
            // Jump to the response state
            llkipp_current_state        <= ST_LLKIPP_RESPONSE;
          end
        end // ST_LLKIPP_CLEAR_KEY
        //------------------------------------------------------------------
        // Response Message state
        //
        // As there is no FIFO in the LLKI-PP, the State Machine more
        // closurely tracks the message exchange.  Here, when we are
        // sending a response, the STM will advance when the response
        // is read.
        //
        //------------------------------------------------------------------
        ST_LLKIPP_RESPONSE              : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          llkipp_current_state          <= ST_LLKIPP_RESPONSE;
          // Build the response word and indicate that a response is waiting (remember, no FIFOs)
          llkipp_response_word[7:0]     <= msg_id;
          llkipp_response_word[15:8]    <= status;
          llkipp_response_word[31:16]   <= 1;       // All responses have a message len of 1
          llkipp_response_waiting       <= '1;
          // When the SEND/RECV address is read via the register interface, we can return to idle
          if (reg_re_o && reg_addr_o == SENDRECV_ADDR) begin
            llkipp_current_state        <= ST_LLKIPP_IDLE;
          end   // end if (reg_re_o && reg_addr_o == SENDRECV_ADDR)
        end
        //------------------------------------------------------------------
        // Trap State
        //------------------------------------------------------------------
        default                       : begin
          // Default signal assignments
          llkid_key_data                <= '0;
          llkid_key_valid               <= '0;
          llkid_clear_key               <= '0;
          llkipp_response_waiting       <= '0;
          llkipp_response_word          <= '0;
          msg_id                        <= '0;
          status                        <= '0;
          msg_len                       <= '0;
          llkipp_current_state          <= ST_LLKIPP_IDLE;
        end
      endcase // llkipp_current_state
    end // end if (rst)
  end   // end always
  //------------------------------------------------------------------------
endmodule   // endmodule llki_pp_wrapper
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       mock_tss_fsm.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     This file is intended as a common finite state machine
//                  for all instances of the Mock Technique Specific Shim.
//                  How the llkid_key_regis ter is used is up to the higher
//                  level module
// Notes:           The KEY_WORDS parameters is used to define the number
//                  "words" (64-bits) you need for the current instance.
//
//                  Additionally, the worrd load order is from High --> Low
//************************************************************************
`timescale 1ns/1ns
module mock_tss_fsm import llki_pkg::*; #(
  parameter int KEY_WORDS       = 2
) (
  // Clock and reset
  input                             clk,
  input                             rst,
  // LLKI Discrete I/O
  input [63:0]                      llkid_key_data,
  input                             llkid_key_valid,
  output reg                        llkid_key_ready,
  output reg                        llkid_key_complete,
  input                             llkid_clear_key,
  output reg                        llkid_clear_key_ack,
  // Key Register Output
  output reg [(64*KEY_WORDS) - 1:0] llkid_key_register
);
  // Internal signals
  reg [7:0]                         llkid_key_word_counter;
  reg [7:0]                         wait_state_counter;
  MOCKTSS_STATE_TYPE                current_state;
  //------------------------------------------------------------------
  // Mock TSS State Machine
  //
  // The Mock TSS introduces artificial wait states to demonstrate
  // a delay when loading or clearing keys
  //------------------------------------------------------------------
  always @(posedge clk or posedge rst)
  begin
    if (rst) begin
      llkid_key_ready         <= '1;
      llkid_key_complete      <= '0;
      llkid_clear_key_ack     <= '0;
      llkid_key_register      <= '0;
      llkid_key_word_counter  <= 0; 
      wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
      current_state           <= ST_MOCKTSS_IDLE;
    end else begin
      case (current_state)
        //------------------------------------------------------------------
        // Mock TSS - Idle State
        //------------------------------------------------------------------
        ST_MOCKTSS_IDLE         : begin
          // Default signal assignments
          llkid_key_ready         <= '1;
          llkid_clear_key_ack     <= '0;
          llkid_key_word_counter  <= 0;
          wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
          current_state           <= ST_MOCKTSS_IDLE;
          // If a clear key is requested while in the IDLE state, the STM
          // will immediately acknowledge the clearing AND clear the key
          if (llkid_clear_key) begin
            llkid_clear_key_ack     <= '1;
            llkid_key_complete      <= '0;
            llkid_key_register      <= '0;
          // Load the first key word into the appropriate register based on the current
          // state of the llkid_key_word_counter
          // Words coming from the SRoT are Little Endian
          end else if (llkid_key_valid) begin
            llkid_key_ready                                       <= '0;
            llkid_key_register[(64*llkid_key_word_counter) +: 64] <= llkid_key_data;
            // Jump to the next state
            current_state                                         <= ST_MOCKTSS_WAIT_STATE0;
          end // end if (llkid_clear_key)
        end
        //------------------------------------------------------------------
        // Mock TSS - Wait State 0
        //------------------------------------------------------------------
        ST_MOCKTSS_WAIT_STATE0    : begin
          // Default signal assignments
          llkid_key_ready         <= '0;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          current_state           <= ST_MOCKTSS_WAIT_STATE0;
          // Decrement the wait state counter
          wait_state_counter      <= wait_state_counter - 1;
          // When the wait has reached zero, jump to the next state deepending
          // on the value of the word counter (do we have any more words left
          // for the key)
          if (wait_state_counter == 0) begin
            // No more words exist, now jump to another wait state
            if (llkid_key_word_counter == KEY_WORDS - 1) begin 
              wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
              current_state           <= ST_MOCKTSS_WAIT_STATE2;
            end else begin
              // Increment the word counter
              llkid_key_word_counter  <= llkid_key_word_counter + 1;
              // Jump to the next state
              current_state           <= ST_MOCKTSS_WAIT_FOR_NEXT_KEY_WORD;
            end // end if (llkid_key_word_counter == 0)
          // A clear key request has been received
          end else if (llkid_clear_key) begin
            current_state             <= ST_MOCKTSS_CLEAR_KEY;
          end // end if (wait_state_counter == 0)
        end // ST_MOCKTSS_WAIT_STATE0
        //------------------------------------------------------------------
        // Mock TSS - Wait for another key word
        //------------------------------------------------------------------
        ST_MOCKTSS_WAIT_FOR_NEXT_KEY_WORD   : begin
          // Default signal assignments
          llkid_key_ready         <= '1;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
          current_state           <= ST_MOCKTSS_WAIT_FOR_NEXT_KEY_WORD;
          // If a clear key, jump to the clear key state
          if (llkid_clear_key) begin
            current_state                                         <= ST_MOCKTSS_CLEAR_KEY;
          // Load the next key word
          end else if (llkid_key_valid) begin
            llkid_key_ready                                       <= '0;
            llkid_key_register[(64*llkid_key_word_counter) +: 64] <= llkid_key_data;
            // Jump to the next state
            current_state                                         <= ST_MOCKTSS_WAIT_STATE0;
          end // end if (llkid_clear_key)
        end // ST_MOCKTSS_WAIT_FOR_NEXT_KEY_WORD
        //------------------------------------------------------------------
        // Mock TSS - Clear Key State
        //------------------------------------------------------------------
        ST_MOCKTSS_CLEAR_KEY      : begin
          // Default signal assignments
          llkid_key_ready         <= '0;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          llkid_key_register      <= '0;
          wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
          current_state           <= ST_MOCKTSS_WAIT_STATE1;
        end
        //------------------------------------------------------------------
        // Mock TSS - Wait State 1
        //------------------------------------------------------------------
        ST_MOCKTSS_WAIT_STATE1    : begin
          // Default signal assignments
          llkid_key_ready         <= '0;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          current_state           <= ST_MOCKTSS_WAIT_STATE1;
          // Decrement the wait state counter
          wait_state_counter      <= wait_state_counter - 1;
          // Jump when the wait state counter has reached zero
          if (wait_state_counter == 0) begin
            llkid_clear_key_ack     <= '1;
            current_state           <= ST_MOCKTSS_IDLE;
          end // end if (wait_state_counter == 0)
        end // ST_MOCKTSS_WAIT_STATE1
        //------------------------------------------------------------------
        // Mock TSS - Wait State 2 - Wait for some cycles after the
        //   final key word is loaded before assert llkid_key_complete
        //------------------------------------------------------------------
        ST_MOCKTSS_WAIT_STATE2    : begin
          // Default signal assignments
          llkid_key_ready         <= '0;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          current_state           <= ST_MOCKTSS_WAIT_STATE2;
          // Decrement the wait state counter
          wait_state_counter      <= wait_state_counter - 1;
          // Jump when the wait state counter has reached zero
          if (wait_state_counter == 0) begin
            llkid_key_complete      <= '1;
            current_state           <= ST_MOCKTSS_IDLE;
          end // end if (wait_state_counter == 0)
        end // ST_MOCKTSS_WAIT_STATE2
        //------------------------------------------------------------------
        // Mock TSS - Trap State
        //------------------------------------------------------------------
        default                   : begin
          // Default signal assignments
          llkid_key_ready         <= '1;
          llkid_key_complete      <= '0;
          llkid_clear_key_ack     <= '0;
          llkid_key_register      <= '0;
          llkid_key_word_counter  <= 0;
          wait_state_counter      <= MOCKTSS_WAIT_STATE_COUNTER_INIT;
          current_state           <= ST_MOCKTSS_IDLE;
        end
      endcase
    end // end if (rst)
  end // end always
  //------------------------------------------------------------------
endmodule // end mock_tss_fsm
 | 
| 
	// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//
// Synchronous single-port SRAM model
`include "prim_assert.sv"
module prim_generic_ram_1p #(
  parameter  int Width           = 32,  // bit
  parameter  int Depth           = 128,
  parameter  int DataBitsPerMask = 1,   // Number of data bits per bit of write mask
  parameter  int InitToZero      = 0,   // Initialize to Zero
  parameter      MemInitFile     = "",  // VMEM file to initialize the memory with
  localparam int Aw              = $clog2(Depth)  // derived parameter
) (
  input  logic             clk_i,
  input  logic             req_i,
  input  logic             write_i,
  input  logic [Aw-1:0]    addr_i,
  input  logic [Width-1:0] wdata_i,
  input  logic [Width-1:0] wmask_i,
  output logic [Width-1:0] rdata_o // Read data. Data is returned one cycle after req_i is high.
);
  // Width of internal write mask. Note wmask_i input into the module is always assumed
  // to be the full bit mask
  localparam int MaskWidth = Width / DataBitsPerMask;
  logic [Width-1:0]     mem [Depth];
  logic [MaskWidth-1:0] wmask;
  for (genvar k = 0; k < MaskWidth; k++) begin : gen_wmask
    assign wmask[k] = &wmask_i[k*DataBitsPerMask +: DataBitsPerMask];
    // Ensure that all mask bits within a group have the same value for a write
    `ASSERT(MaskCheck_A, req_i && write_i |->
        wmask_i[k*DataBitsPerMask +: DataBitsPerMask] inside {{DataBitsPerMask{1'b1}}, '0},
        clk_i, '0)
  end
  // Memory initialization to make simulation possible...
  `ifndef SYNTHESIS
    initial begin
      if (InitToZero == 1)
        for (int i = 0; i < Depth; i = i + 1)
          mem[i]  <= '0;
    end //end initial
  `endif
  // using always instead of always_ff to avoid 'ICPD  - illegal combination of drivers' error
  // thrown when using $readmemh system task to backdoor load an image
  always @(posedge clk_i) begin
    if (req_i) begin
      if (write_i) begin
        for (int i=0; i < MaskWidth; i = i + 1) begin
          if (wmask[i]) begin
            mem[addr_i][i*DataBitsPerMask +: DataBitsPerMask] <=
              wdata_i[i*DataBitsPerMask +: DataBitsPerMask];
          end
        end
      end else begin
        rdata_o <= mem[addr_i];
      end
    end
  end
  `include "prim_util_memload.svh"
endmodule
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:       scratchpad_wrapper.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     This file provides a Verilog <-> SystemVerilog adapter
//                  allowing connection of TL-UL interface to the Chisel
//                  blackbox.  
// Notes:           The underlying TL-UL package is from the OpenTitan
//                  project.
//
//
//************************************************************************
`timescale 1ns/1ns
`include "prim_assert.sv"
module scratchpad_wrapper import tlul_pkg::*; import llki_pkg::*; #(
  parameter int ADDRESS     = 32'h00000000,  // In terms of bytes
  parameter int DEPTH       = 32'h00000100,  // In terms of bytes
  parameter SLAVE_TL_SZW    = top_pkg::TL_SZW,
  parameter SLAVE_TL_AIW    = top_pkg::TL_AIW,
  parameter SLAVE_TL_AW     = top_pkg::TL_AW,
  parameter SLAVE_TL_DBW    = top_pkg::TL_DBW,
  parameter SLAVE_TL_DW     = top_pkg::TL_DW,
  parameter SLAVE_TL_DIW    = top_pkg::TL_DIW
) (
  // Clock and reset
  input                           clk,
  input                           rst,
  // Slave interface A channel
  input [2:0]                     slave_a_opcode,
  input [2:0]                     slave_a_param,
  input [SLAVE_TL_SZW-1:0]        slave_a_size,
  input [SLAVE_TL_AIW-1:0]        slave_a_source,
  input [SLAVE_TL_AW-1:00]        slave_a_address,
  input [SLAVE_TL_DBW-1:0]        slave_a_mask,
  input [SLAVE_TL_DW-1:0]         slave_a_data,
  input                           slave_a_corrupt,
  input                           slave_a_valid,
  output                          slave_a_ready,
  // Slave interface D channel
  output [2:0]                    slave_d_opcode,
  output [2:0]                    slave_d_param,
  output reg [SLAVE_TL_SZW-1:0]   slave_d_size,
  output reg [SLAVE_TL_AIW-1:0]   slave_d_source,
  output reg [SLAVE_TL_DIW-1:0]   slave_d_sink,
  output                          slave_d_denied,
  output [SLAVE_TL_DW-1:0]        slave_d_data,
  output                          slave_d_corrupt,
  output                          slave_d_valid,
  input                           slave_d_ready
);
  
  localparam int RegBw          = top_pkg::TL_DW/8;
  // Create the structures for communicating with OpenTitan-based Tilelink
  tl_h2d_t                      slave_tl_h2d_i;
  tl_h2d_t                      slave_tl_h2d_o;
  tl_d2h_t                      slave_tl_d2h_i;
  tl_d2h_t                      slave_tl_d2h_o;
  logic                         tl_err;
  logic                         addr_err;
  // In the OpenTitan world, TL buses are encapsulated with the structures instantitated above
  // and as defined in top_pkg.sv.  This includes field widths.
  //
  // In the RocketChip world, some field widths will vary based on the other system components
  // (e.g., source and sink widths).  In order to provide maximum flexibility, without breaking
  // OpenTitan, top_pkg.sv is going to be defined with field maximum expected widths within
  // the CEP ecosystem.
  //
  // The following assignments, coupled with the parameters passed to this component will 
  // provide for a flexible assignment, when necessary.  Assertions will be used to capture
  // a mismatch when the widths in the OpenTitan world are not large enough to encapsulate
  // what is being passed from RocketChip.
  //
  // DW/DBW (Data bus width) must be equal in both worlds
  `ASSERT_INIT(scratchpad_slaveTlSzw, top_pkg::TL_SZW >= SLAVE_TL_SZW)
  `ASSERT_INIT(scratchpad_slaveTlAiw, top_pkg::TL_AIW >= SLAVE_TL_AIW)
  `ASSERT_INIT(scratchpad_slaveTlAw, top_pkg::TL_AW >= SLAVE_TL_AW)
  `ASSERT_INIT(scratchpad_slaveTlDbw, top_pkg::TL_DBW == SLAVE_TL_DBW)
  `ASSERT_INIT(scratchpad_slaveTlDw, top_pkg::TL_DW == SLAVE_TL_DW)
  
  always @*
  begin
    slave_tl_h2d_i.a_size                       <= '0;
    slave_tl_h2d_i.a_size[SLAVE_TL_SZW-1:0]     <= slave_a_size;
    slave_tl_h2d_i.a_source                     <= '0;
    slave_tl_h2d_i.a_source[SLAVE_TL_AIW-1:0]   <= slave_a_source;
    slave_tl_h2d_i.a_address                    <= '0;
    slave_tl_h2d_i.a_address[SLAVE_TL_AW-1:0]   <= slave_a_address;
    
    slave_d_size                                <= slave_tl_d2h_o.d_size[SLAVE_TL_SZW-1:0];
    slave_d_source                              <= slave_tl_d2h_o.d_source[SLAVE_TL_AIW-1:0];
    slave_d_sink                                <= slave_tl_d2h_o.d_sink[SLAVE_TL_DIW-1:0];
  end
  // Make Slave A channel connections
  assign slave_tl_h2d_i.a_valid     = slave_a_valid;
  assign slave_tl_h2d_i.a_opcode    = ( slave_a_opcode == 3'h0) ? PutFullData : 
                                    ((slave_a_opcode == 3'h1) ? PutPartialData : 
                                    ((slave_a_opcode == 3'h4) ? Get : 
                                      Get));                                   
  assign slave_tl_h2d_i.a_param     = slave_a_param;
  assign slave_tl_h2d_i.a_mask      = slave_a_mask;
  assign slave_tl_h2d_i.a_data      = slave_a_data;
  assign slave_tl_h2d_i.a_user      = tl_a_user_t'('0);  // User field is unused by Rocket Chip
  assign slave_tl_h2d_i.d_ready     = slave_d_ready;
  
  // Make Slave D channel connections
  // Converting from the OpenTitan enumerated type to specific bit mappings
  assign slave_d_opcode         = ( slave_tl_d2h_o.d_opcode == AccessAck)     ? 3'h0 :
                                  ((slave_tl_d2h_o.d_opcode == AccessAckData) ? 3'h1 :
                                    3'h0);
  assign slave_d_param          = slave_tl_d2h_o.d_param;
  assign slave_d_denied         = slave_tl_d2h_o.d_error;
  assign slave_d_data           = slave_tl_d2h_o.d_data;
  assign slave_d_corrupt        = slave_tl_d2h_o.d_error;
  assign slave_d_valid          = slave_tl_d2h_o.d_valid;
  assign slave_a_ready          = slave_tl_d2h_o.a_ready;
  //------------------------------------------------------------------------
  // The TL-UL FIFO is used to queue burst transfers
  //
  // The almost_full description can be found in the slave_tl_d2h_i.a_ready
  // assignment below
  //------------------------------------------------------------------------
  localparam        RSP_FIFO_DEPTH        = 10;
  localparam        RSP_FIFO_ALMOST_FULL  = RSP_FIFO_DEPTH - 2;
  localparam int    DepthW                = prim_util_pkg::vbits(RSP_FIFO_DEPTH + 1);
  wire [DepthW-1:0] rsp_depth_o;
  wire              rsp_almost_full;
  assign            rsp_almost_full       = (rsp_depth_o >= RSP_FIFO_ALMOST_FULL) ? 1'b1 : 1'b0;
  tlul_fifo_sync #(
    .ReqPass      (1),                // The request FIFO will be a fall-through
    .RspPass      (1),                // The response FIFO will be also be fall-through
    .ReqDepth     (0),                // Complete passthrough mode
    .RspDepth     (RSP_FIFO_DEPTH),   // The maximum number of words we can expect
    .SpareReqW    (1),                // Unused (A value of zero results in an incorrect FIFO width)
    .SpareRspW    (1)                 // Unused
  ) tlul_fifo_sync_inst (
    .clk_i        (clk),
    .rst_ni       (~rst),
    .tl_h_i       (slave_tl_h2d_i),
    .tl_h_o       (slave_tl_d2h_o),
    .tl_d_i       (slave_tl_d2h_i),
    .tl_d_o       (slave_tl_h2d_o),
    .spare_req_i  ('0),
    .spare_req_o  (),
    .spare_rsp_i  ('0),
    .spare_rsp_o  (),
    .req_depth_o  (),
    .rsp_depth_o  (rsp_depth_o)
  );
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // TL-UL Error Checker Component (Channel A)
  //------------------------------------------------------------------------
  // tl_err : separate checker
  tlul_err tlul_err_inst (
    .clk_i  (clk),
    .rst_ni (~rst),
    .tl_i   (slave_tl_h2d_o),
    .err_o  (tl_err)
  );
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Scratchpad RAM instantiated as individual bytes to allow for byte
  // addressing (effectively masking)
  //------------------------------------------------------------------------
  reg                       scratchpad_write_i;
  reg [top_pkg::TL_AW-1:0]  scratchpad_addr_i;
  reg [top_pkg::TL_DW-1:0]  scratchpad_wdata_i;
  reg [top_pkg::TL_DW-1:0]  scratchpad_mask_i;
  wire [top_pkg::TL_DW-1:0] scratchpad_rdata_o;
  // Generate the mask (in bits) based on the A Channel mask field
  always @*
  begin
    for (int i = 0; i < RegBw; i = i + 1)
      for (int j = 0; j < 8; j = j + 1)
        scratchpad_mask_i[i*8 + j] <= slave_tl_h2d_o.a_mask[i];
  end // end always
  // Generate the scratchpad address (which needs to be in terms of 64-bit words)
  assign scratchpad_addr_i        = (slave_tl_h2d_o.a_address - ADDRESS) >> 3;
  // Writes will occur for only PutFullData and PutPartialData opcodes (we cannot process the request if not ready)
  assign scratchpad_write_i       = slave_tl_h2d_o.a_valid & slave_tl_d2h_i.a_ready & ((slave_tl_h2d_o.a_opcode == PutFullData) | (slave_tl_h2d_o.a_opcode == PutPartialData));
  assign scratchpad_wdata_i       = slave_tl_h2d_o.a_data;
  // D Channel read data is immediately mapped to the FIFO given theat registered RAM reads.  All other d_channel 
  // signals will need be registered to ensure it is aligned with the data
  assign slave_tl_d2h_i.d_data    = scratchpad_rdata_o;
  // The issue with directly connecting d_ready to a_ready, is that it does NOT allow for proper absorption of a request that was just read from
  // the request FIFO (Channel A).  Given the registered RAM output (and associated registering of other signals destined for the D Channel), 
  // there could be a reequest in-flight when d_channel becomes NOT ready, thus the need for using almost full.
  assign slave_tl_d2h_i.a_ready   = !rsp_almost_full;
  // See if an out of bound address was provided 
  always @(scratchpad_addr_i or slave_tl_h2d_o.a_valid) begin
    addr_err                    <= 1'b0;
    
    if (slave_tl_h2d_o.a_valid == 1 && scratchpad_addr_i >= (DEPTH / 8))
      addr_err                  <= 1'b1;
  end
  // Perform the remaining tilelink connections
  always_ff @(posedge clk or posedge rst) begin
    if (rst) begin
      slave_tl_d2h_i.d_opcode   <= AccessAck;
      slave_tl_d2h_i.d_param    <= '0;
      slave_tl_d2h_i.d_size     <= '0;
      slave_tl_d2h_i.d_source   <= '0;
      slave_tl_d2h_i.d_sink     <= '0;
      slave_tl_d2h_i.d_user     <= '0;
      slave_tl_d2h_i.d_error    <= '0;
      slave_tl_d2h_i.d_valid    <= '0;
    end else begin
      //  The following assingment methodology is borrowed from the tlul_adapter_reg component
      if ((slave_tl_h2d_o.a_opcode == PutFullData) | (slave_tl_h2d_o.a_opcode == PutPartialData))
        slave_tl_d2h_i.d_opcode   <= AccessAck;
      else
        slave_tl_d2h_i.d_opcode   <= AccessAckData;
      slave_tl_d2h_i.d_param    <= '0;
      slave_tl_d2h_i.d_size     <= slave_tl_h2d_o.a_size;
      slave_tl_d2h_i.d_source   <= slave_tl_h2d_o.a_source;
      slave_tl_d2h_i.d_sink     <= '0;
      slave_tl_d2h_i.d_user     <= '0;
      slave_tl_d2h_i.d_error    <= tl_err || addr_err;
      // We cannot process the response if not ready
      slave_tl_d2h_i.d_valid    <= slave_tl_h2d_o.a_valid & slave_tl_d2h_i.a_ready;
    end // end if (!rst_ni)
  end // always_ff @(posedge clk_i or negedge rst_ni)
  //------------------------------------------------------------------------
  // Instantiate a generic single port RAM
  //------------------------------------------------------------------------
  prim_generic_ram_1p #(
    .Width              (top_pkg::TL_DW),
    .Depth              (DEPTH / 8),
    .InitToZero         (1)               // Only applicable to simulation
  ) scratchpad_ram_inst (
    .clk_i              (clk),
    .req_i              (1'b1),           // Always selected
    .write_i            (scratchpad_write_i),
    .addr_i             (scratchpad_addr_i[$clog2(DEPTH/8) - 1:0]),
    .wdata_i            (scratchpad_wdata_i),
    .wmask_i            (scratchpad_mask_i),
    .rdata_o            (scratchpad_rdata_o)
  );
  //------------------------------------------------------------------------
endmodule   // endmodule scratchpad_wrapper
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:       srot_wrapper.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     This file provides a Verilog <-> SystemVerilog adapter
//                  allowing connection of TL-UL interface to the Chisel
//                  blackbox.  
// Notes:           The underlying TL-UL package is from the OpenTitan
//                  project
//
//                  The "tl" parameters have been taken from the
//                  OpenTitan ecosystem
//
//                  The SRoT is a SINGLE THREADED DEVICE.
//
//                  As such, care should be taken when using the
//                  SRoT in a multi-core environment.  Care should ssewaa
//                  take that multiple cores are NOT accessing the
//                  SRoT at the same time.
//
//************************************************************************
`timescale 1ns/1ns
`include "prim_assert.sv"
module srot_wrapper import tlul_pkg::*; import llki_pkg::*; #(
  parameter SLAVE_TL_SZW    = top_pkg::TL_SZW,
  parameter SLAVE_TL_AIW    = top_pkg::TL_AIW,
  parameter SLAVE_TL_AW     = top_pkg::TL_AW,
  parameter SLAVE_TL_DBW    = top_pkg::TL_DBW,
  parameter SLAVE_TL_DW     = top_pkg::TL_DW,
  parameter SLAVE_TL_DIW    = top_pkg::TL_DIW,
  parameter MASTER_TL_SZW   = top_pkg::TL_SZW,
  parameter MASTER_TL_AIW   = top_pkg::TL_AIW,
  parameter MASTER_TL_AW    = top_pkg::TL_AW,
  parameter MASTER_TL_DBW   = top_pkg::TL_DBW,
  parameter MASTER_TL_DW    = top_pkg::TL_DW,
  parameter MASTER_TL_DIW   = top_pkg::TL_DIW,
  parameter LLKI_CORE_INDEX_ARRAY_PACKED,     // LLKI interface addresses
  parameter LLKI_NUM_CORES,
  parameter int FIFO_DEPTH  = 8              // Define the depth of the LLKI FIFOs
 ) (
  // Clock and reset
  input                           clk,
  input                           rst,
  // Slave interface A channel
  input [2:0]                     slave_a_opcode,
  input [2:0]                     slave_a_param,
  input [SLAVE_TL_SZW-1:0]        slave_a_size,
  input [SLAVE_TL_AIW-1:0]        slave_a_source,
  input [SLAVE_TL_AW-1:00]        slave_a_address,
  input [SLAVE_TL_DBW-1:0]        slave_a_mask,
  input [SLAVE_TL_DW-1:0]         slave_a_data,
  input                           slave_a_corrupt,
  input                           slave_a_valid,
  output                          slave_a_ready,
  // Slave interface D channel
  output [2:0]                    slave_d_opcode,
  output [2:0]                    slave_d_param,
  output reg [SLAVE_TL_SZW-1:0]   slave_d_size,
  output reg [SLAVE_TL_AIW-1:0]   slave_d_source,
  output reg [SLAVE_TL_DIW-1:0]   slave_d_sink,
  output                          slave_d_denied,
  output [SLAVE_TL_DW-1:0]        slave_d_data,
  output                          slave_d_corrupt,
  output                          slave_d_valid,
  input                           slave_d_ready,
  // Master interface A channel
  output [2:0]                    master_a_opcode,
  output [2:0]                    master_a_param,
  output reg [MASTER_TL_SZW-1:0]  master_a_size,
  output reg [MASTER_TL_AIW-1:0]  master_a_source,
  output reg [MASTER_TL_AW-1:0]   master_a_address,
  output [MASTER_TL_DBW-1:0]      master_a_mask,
  output [MASTER_TL_DW-1:0]       master_a_data,
  output                          master_a_corrupt,
  output                          master_a_valid,
  input                           master_a_ready,
  // Master interface D channel
  input [2:0]                     master_d_opcode,
  input [2:0]                     master_d_param,
  input [MASTER_TL_SZW-1:0]       master_d_size,
  input [MASTER_TL_AIW-1:0]       master_d_source,
  input [MASTER_TL_DIW-1:0]       master_d_sink,
  input                           master_d_denied,
  input [MASTER_TL_DW-1:0]        master_d_data,
  input                           master_d_corrupt,
  input                           master_d_valid,
  output                          master_d_ready
);
  
  // Derived parameters
  localparam int DepthW     = prim_util_pkg::vbits(FIFO_DEPTH + 1);
  //We get this parameter from a verilog file, which does not support unpacked parameter arrays.
  //So, keep as a 2d packed array. 
  localparam [0:LLKI_NUM_CORES-1][31:0] LLKI_CORE_INDEX_ARRAY = LLKI_CORE_INDEX_ARRAY_PACKED;
  // Create the structures for communicating with OpenTitan-based Tilelink
  tl_h2d_t                      slave_tl_h2d;
  tl_d2h_t                      slave_tl_d2h;
  tl_h2d_t                      master_tl_h2d;
  tl_d2h_t                      master_tl_d2h;
  // In the OpenTitan world, TL buses are encapsulated with the structures instantitated above
  // and as defined in top_pkg.sv.  This includes field widths.
  //
  // In the RocketChip world, some field widths will vary based on the other system components
  // (e.g., source and sink widths).  In order to provide maximum flexibility, without breaking
  // OpenTitan, top_pkg.sv is going to be defined with field maximum expected widths within
  // the CEP ecosystem.
  //
  // The following assignments, coupled with the parameters passed to this component will 
  // provide for a flexible assignment, when necessary.  Assertions will be used to capture
  // a mismatch when the widths in the OpenTitan world are not large enough to encapsulate
  // what is being passed from RocketChip.
  //
  // DW/DBW (Data bus width) must be equal in both worlds
  
  `ASSERT_INIT(srot_slaveTlSzw, top_pkg::TL_SZW >= SLAVE_TL_SZW)
  `ASSERT_INIT(srot_slaveTlAiw, top_pkg::TL_AIW >= SLAVE_TL_AIW)
  `ASSERT_INIT(srot_slaveTlAw, top_pkg::TL_AW >= SLAVE_TL_AW)
  `ASSERT_INIT(srot_slaveTlDbw, top_pkg::TL_DBW == SLAVE_TL_DBW)
  `ASSERT_INIT(srot_slaveTlDw, top_pkg::TL_DW == SLAVE_TL_DW)
  
  always @*
  begin
    slave_tl_h2d.a_size                         <= '0;
    slave_tl_h2d.a_size[SLAVE_TL_SZW-1:0]       <= slave_a_size;
    slave_tl_h2d.a_source                       <= '0;
    slave_tl_h2d.a_source[SLAVE_TL_AIW-1:0]     <= slave_a_source;
    slave_tl_h2d.a_address                      <= '0;
    slave_tl_h2d.a_address[SLAVE_TL_AW-1:0]     <= slave_a_address;
    
    slave_d_size                                <= slave_tl_d2h.d_size[SLAVE_TL_SZW-1:0];
    slave_d_source                              <= slave_tl_d2h.d_source[SLAVE_TL_AIW-1:0];
    slave_d_sink                                <= slave_tl_d2h.d_sink[SLAVE_TL_DIW-1:0];
  end
  // Make Slave A channel connections
  assign slave_tl_h2d.a_valid     = slave_a_valid;
  assign slave_tl_h2d.a_opcode    = ( slave_a_opcode == 3'h0) ? PutFullData : 
                                    ((slave_a_opcode == 3'h1) ? PutPartialData : 
                                    ((slave_a_opcode == 3'h4) ? Get : 
                                      Get));                                   
  assign slave_tl_h2d.a_param     = slave_a_param;
  assign slave_tl_h2d.a_mask      = slave_a_mask;
  assign slave_tl_h2d.a_data      = slave_a_data;
  assign slave_tl_h2d.a_user      = tl_a_user_t'('0);  // User field is unused by Rocket Chip
  assign slave_tl_h2d.d_ready     = slave_d_ready;
  
  // Make Slave D channel connections
  // Converting from the OpenTitan enumerated type to specific bit mappings
  assign slave_d_opcode         = ( slave_tl_d2h.d_opcode == AccessAck)     ? 3'h0 :
                                  ((slave_tl_d2h.d_opcode == AccessAckData) ? 3'h1 :
                                    3'h0);
  assign slave_d_param          = slave_tl_d2h.d_param;
  assign slave_d_denied         = slave_tl_d2h.d_error;
  assign slave_d_data           = slave_tl_d2h.d_data;
  assign slave_d_corrupt        = slave_tl_d2h.d_error;
  assign slave_d_valid          = slave_tl_d2h.d_valid;
  assign slave_a_ready          = slave_tl_d2h.a_ready;
  `ASSERT_INIT(srot_masterTlSzw, top_pkg::TL_SZW >= MASTER_TL_SZW)
  `ASSERT_INIT(srot_masterTlAiw, top_pkg::TL_AIW >= MASTER_TL_AIW)
  `ASSERT_INIT(srot_masterTlAw, top_pkg::TL_AW >= MASTER_TL_AW)
  `ASSERT_INIT(srot_masterTlDbw, top_pkg::TL_DBW == MASTER_TL_DBW)
  `ASSERT_INIT(srot_masterTlDw, top_pkg::TL_DW == MASTER_TL_DW)
  always @*
  begin
    master_a_size                             <= master_tl_h2d.a_size[MASTER_TL_SZW-1:0];
    master_a_source                           <= master_tl_h2d.a_source[MASTER_TL_AIW-1:0];
    master_a_address                          <= master_tl_h2d.a_address[MASTER_TL_AW-1:0];
    master_tl_d2h.d_size                      <= '0;
    master_tl_d2h.d_size[MASTER_TL_SZW-1:0]   <= master_d_size;
    master_tl_d2h.d_source                    <= '0;
    master_tl_d2h.d_source[MASTER_TL_AIW-1:0] <= master_d_source;
    master_tl_d2h.d_sink                      <= '0;
    master_tl_d2h.d_sink[MASTER_TL_DIW-1:0]   <= master_d_sink;
  end
  // Make Master A channel connections
  assign master_a_mask          = master_tl_h2d.a_mask;
  assign master_a_data          = master_tl_h2d.a_data;
  assign master_a_opcode        = ( master_tl_h2d.a_opcode == PutFullData)    ? 3'h0 :
                                  ((master_tl_h2d.a_opcode == PutPartialData) ? 3'h1 :
                                  ((master_tl_h2d.a_opcode == Get)            ? 3'h4 :
                                    3'h4));
  assign master_a_param         = master_tl_h2d.a_param;
  assign master_a_corrupt       = 0;
  assign master_a_valid         = master_tl_h2d.a_valid;
  assign master_d_ready         = master_tl_h2d.d_ready;
  // Make Master D channel connections
  assign master_tl_d2h.d_data   = master_d_data;
  assign master_tl_d2h.d_opcode = ( master_d_opcode == 3'h0) ? AccessAck : 
                                  ((master_d_opcode == 3'h1) ? AccessAckData : 
                                    AccessAck); 
  assign master_tl_d2h.d_param  = master_d_param;
  assign master_tl_d2h.d_user   = tl_a_user_t'('0);
  assign master_tl_d2h.d_error  = master_d_corrupt || master_d_denied;
  assign master_tl_d2h.d_valid  = master_d_valid;
  assign master_tl_d2h.a_ready  = master_a_ready;
  // Define some of the wires and registers associated with the tlul_adapter_reg
  wire                          reg_we_o;
  reg                           reg_we_o_d1;
  wire                          reg_re_o;
  reg                           reg_re_o_d1;
  wire [top_pkg::TL_AW-1:0]     reg_addr_o;
  reg  [top_pkg::TL_AW-1:0]     reg_addr_o_d1;
  wire [top_pkg::TL_DW-1:0]     reg_wdata_o;
  reg [top_pkg::TL_DW-1:0]      reg_rdata_i;
  wire                          ack_i;
  reg                           reg_error_i;
  // Define some of the wires and registers associated with the tlul_adapter_host
  reg                           host_req_i;
  wire                          host_gnt_o;
  reg                           host_we_i;
  reg [top_pkg::TL_AW-1:0]      host_addr_i;
  reg [top_pkg::TL_DW-1:0]      host_wdata_i;
  wire                          host_valid_o;
  wire [top_pkg::TL_DW-1:0]     host_rdata_o;
  wire                          host_err_o;
  // Misc. signals
  reg [top_pkg::TL_DW-1:0]      srot_ctrlstatus_register; // Bit definition can be found in llki_pkg.sv
  reg [top_pkg::TL_DW-1:0]      srot_scratchpad0_register;
  reg [top_pkg::TL_DW-1:0]      srot_scratchpad1_register;
  reg                           write_error;
  reg                           read_error;
 
  // Defined earlier in the file so it can be used as a selector input for
  // the KeyIndexRAM and KeyRAM address inputs
  SROT_STATE_TYPE               srot_current_state;
  //------------------------------------------------------------------------
  // Instantitate a tlul_adapter_reg to adapt the TL Slave Interface
  //------------------------------------------------------------------------
  tlul_adapter_reg #(
    .RegAw          (top_pkg::TL_AW   ),
    .RegDw          (top_pkg::TL_DW   )
  ) u_tlul_adapter_reg_inst (
    .clk_i          (clk              ),
    .rst_ni         (~rst             ),
    .tl_i           (slave_tl_h2d     ),
    .tl_o           (slave_tl_d2h     ),
    .we_o           (reg_we_o         ),
    .re_o           (reg_re_o         ),
    .addr_o         (reg_addr_o       ),
    .wdata_o        (reg_wdata_o      ),
    .be_o           (                 ),    // Accesses are assumed to be word-wide
    .rdata_i        (reg_rdata_i      ),
    .ack_i          (ack_i            ),    // External acknowledgement of the
                                            // transaction
    .error_i        (reg_error_i      )
  );
  // The reg_error_i will be asserted if either a read or write error occurs
  assign reg_error_i    = read_error || write_error;
  // The acknowledgement signal allows for latching of the read data when
  // available (if it is a read) and/or proper processing of the
  // external error
  assign ack_i          = reg_re_o_d1 ||  reg_we_o_d1;
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Instantiate a tlul_adapter_host fo connecting to the master interface
  //
  // Per the notes in tlul_adapter_host.sv, setting MAX_REQS = 1 results
  // in a purely combinatorial component.
  //------------------------------------------------------------------------
  tlul_adapter_host #(
    .MAX_REQS(1)
  ) u_tlul_adapter_host_inst (
    .clk_i    (clk                ),
    .rst_ni   (~rst               ),
    .req_i    (host_req_i         ),
    .gnt_o    (host_gnt_o         ),
    .addr_i   (host_addr_i        ),
    .we_i     (host_we_i          ),
    .wdata_i  (host_wdata_i       ),
    .be_i     ('1                 ), // All bytes always enabled
    .valid_o  (host_valid_o       ),
    .rdata_o  (host_rdata_o       ),
    .err_o    (host_err_o         ),
    .tl_o     (master_tl_h2d      ),
    .tl_i     (master_tl_d2h      )
  );
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Instantiate the LLKI C2 Send Message FIFO
  //------------------------------------------------------------------------
  // Define signals associated with the LLKI C2 Send Message FIFO
  reg                               llkic2_reqfifo_clr_i;
  reg                               llkic2_reqfifo_wvalid_i;
  wire                              llkic2_reqfifo_wready_o;
  reg [top_pkg::TL_DW - 1:0]        llkic2_reqfifo_wdata_i;
  wire                              llkic2_reqfifo_rvalid_o;
  reg                               llkic2_reqfifo_rready_i;
  wire [top_pkg::TL_DW - 1:0]       llkic2_reqfifo_rdata_o;
  wire [DepthW - 1 :0]              llkic2_reqfifo_depth_o;
  wire                              llkic2_reqfifo_empty;
  wire                              llkic2_reqfifo_full;
  // Instantiate the FIFO
  prim_fifo_sync #(
    .Width              (top_pkg::TL_DW),
    .Pass               (1'b0),
    .Depth              (FIFO_DEPTH),
    .OutputZeroIfEmpty  (1'b0)    // Enables "first word fall through"
  ) llkic2_reqfifo_inst (
    .clk_i              (clk),
    .rst_ni             (~rst),
    // Synchronous clear/flush
    .clr_i              (llkic2_reqfifo_clr_i),
    // Write Port
    .wvalid_i           (llkic2_reqfifo_wvalid_i),
    .wready_o           (llkic2_reqfifo_wready_o),
    .wdata_i            (llkic2_reqfifo_wdata_i),
  
    // Read Port
    .rvalid_o           (llkic2_reqfifo_rvalid_o),
    .rready_i           (llkic2_reqfifo_rready_i),
    .rdata_o            (llkic2_reqfifo_rdata_o),
    // Occupancy
    .depth_o            (llkic2_reqfifo_depth_o)
  );
  // Generate the full and empty signals for the LLKIC2 Send FIFO
  assign llkic2_reqfifo_empty = llkic2_reqfifo_depth_o == '0;
  assign llkic2_reqfifo_full  = llkic2_reqfifo_depth_o == FIFO_DEPTH;
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Instantiate the LLKI C2 Receive Message FIFO
  //------------------------------------------------------------------------
  // Define signals associated with the LLKI C2 Received Message FIFO
  reg                               llkic2_respfifo_clr_i;
  reg                               llkic2_respfifo_wvalid_i;
  wire                              llkic2_respfifo_wready_o;
  reg [top_pkg::TL_DW - 1:0]        llkic2_respfifo_wdata_i;
  wire                              llkic2_respfifo_rvalid_o;
  reg                               llkic2_respfifo_rready_i;
  reg [top_pkg::TL_DW - 1:0]        llkic2_respfifo_rdata_o;
  wire [DepthW - 1:0]               llkic2_respfifo_depth_o;
  wire                              llkic2_respfifo_empty;  
  wire                              llkic2_respfifo_full;  
  // Instantiate the FIFO
  prim_fifo_sync #(
    .Width              (top_pkg::TL_DW),
    .Pass               (1'b0),
    .Depth              (FIFO_DEPTH),
    .OutputZeroIfEmpty  (1'b0)    // Enables "first word fall through"
  ) llkic2_respfifo_inst (
    .clk_i              (clk),
    .rst_ni             (~rst),
    // Synchronous clear/flush
    .clr_i              (llkic2_respfifo_clr_i),
    // Write Port
    .wvalid_i           (llkic2_respfifo_wvalid_i),
    .wready_o           (llkic2_respfifo_wready_o),
    .wdata_i            (llkic2_respfifo_wdata_i),
  
    // Read Port
    .rvalid_o           (llkic2_respfifo_rvalid_o),
    .rready_i           (llkic2_respfifo_rready_i),
    .rdata_o            (llkic2_respfifo_rdata_o),
    // Occupancy
    .depth_o            (llkic2_respfifo_depth_o)
  );
  // Generate the full and empty signals for the Rx FIFO
  assign llkic2_respfifo_empty  = llkic2_respfifo_depth_o == '0;
  assign llkic2_respfifo_full   = llkic2_respfifo_depth_o == FIFO_DEPTH;
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Key Index RAM
  //------------------------------------------------------------------------
  reg                       keyindexram_write_i;
  reg [top_pkg::TL_AW-1:0]  keyindexram_addr_i;
  reg [top_pkg::TL_AW-1:0]  keyindexram_stm_addr_i;
  reg [top_pkg::TL_DW-1:0]  keyindexram_wdata_i;
  wire [top_pkg::TL_DW-1:0] keyindexram_rdata_o;
  prim_generic_ram_1p #(
    .Width              (top_pkg::TL_DW),
    .Depth              (SROT_KEYINDEXRAM_SIZE)
  ) key_index_ram_inst (
    .clk_i              (clk),
    .req_i              (1'b1),                     // Always selected
    .write_i            (keyindexram_write_i),
    .addr_i             (keyindexram_addr_i[$clog2(SROT_KEYINDEXRAM_SIZE) - 1:0]),
    .wdata_i            (keyindexram_wdata_i),
    .wmask_i            ('1),                       // Mask is unused
    .rdata_o            (keyindexram_rdata_o)
  );
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Key RAM
  //------------------------------------------------------------------------
  reg                       keyram_write_i;
  reg [top_pkg::TL_AW-1:0]  keyram_addr_i;
  reg [top_pkg::TL_AW-1:0]  keyram_stm_addr_i;
  reg [top_pkg::TL_DW-1:0]  keyram_wdata_i;
  wire [top_pkg::TL_DW-1:0] keyram_rdata_o;
  prim_generic_ram_1p #(
    .Width              (top_pkg::TL_DW),
    .Depth              (SROT_KEYRAM_SIZE)
  ) key_ram_inst (
    .clk_i              (clk),
    .req_i              (1'b1),                 // Always selected
    .write_i            (keyram_write_i),
    .addr_i             (keyram_addr_i[$clog2(SROT_KEYRAM_SIZE) - 1:0]),
    .wdata_i            (keyram_wdata_i),
    .wmask_i            ('1),                   // Mask is unused
    .rdata_o            (keyram_rdata_o)
  );
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // KeyIndexRAM and KeyRAM Address Generation
  //
  // The RAMs have a single read-write port (1RW).  Writes will only
  // occur over Tilelink, but reads could come from either Tilelink OR
  // the SRoT state machine.
  //
  // So, if the STM is not idle, it "owns" the address inputs.
  // 
  // If a write occurs, the address needs to be delayed one cycle to allow
  // the write decode to occur properly.
  //
  // Otherwise, a tilelink read is "assumed" and thus the "raw" address
  // output from the tlul_adapter_reg commponent is used.
  //------------------------------------------------------------------------
  always @*
  begin
    if (srot_current_state != ST_SROT_IDLE) begin
      keyindexram_addr_i          <= keyindexram_stm_addr_i;
      keyram_addr_i               <= keyram_stm_addr_i;
    end else if (reg_we_o_d1) begin
      keyindexram_addr_i          <= (reg_addr_o_d1 - SROT_KEYINDEXRAM_ADDR) >> 3;
      keyram_addr_i               <= (reg_addr_o_d1 - SROT_KEYRAM_ADDR) >> 3;
    end else begin
      keyindexram_addr_i          <= (reg_addr_o - SROT_KEYINDEXRAM_ADDR) >> 3;
      keyram_addr_i               <= (reg_addr_o - SROT_KEYRAM_ADDR) >> 3;
    end   // end if (reg_we_do_d1)
  end // end always @*
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Write Decode Process
  //------------------------------------------------------------------------
  always @(posedge clk or posedge rst)
  begin
    if (rst) begin
      reg_addr_o_d1               <= '0;
      reg_we_o_d1                 <= '0;
      reg_re_o_d1                 <= '0;
      srot_ctrlstatus_register    <= '0;
      srot_scratchpad0_register   <= '0;
      srot_scratchpad1_register   <= '0;
      write_error                 <= '0;
      keyindexram_write_i         <= '0;
      keyram_write_i              <= '0;
      keyindexram_wdata_i         <= '0;
      keyram_wdata_i              <= '0;
      llkic2_reqfifo_wvalid_i     <= '0;
      llkic2_reqfifo_wdata_i      <= '0;
    end else begin
      
      // Default signal assignments
      write_error                 <= 1'b0;
      keyindexram_write_i         <= 1'b0;
      keyram_write_i              <= 1'b0;
      llkic2_reqfifo_wvalid_i     <= 1'b0;
      llkic2_reqfifo_wdata_i      <= 1'b0;
      // Registered version of the tlul_adapter_reg output (used outside of the 
      // write decode process) to ensure proper alignment
      reg_addr_o_d1               <= reg_addr_o;
      reg_we_o_d1                 <= reg_we_o;
      reg_re_o_d1                 <= reg_re_o;
      // Delay the wdata by once cycle to ensure proper alignment
      keyindexram_wdata_i         <= reg_wdata_o;
      keyram_wdata_i              <= reg_wdata_o;
      // Implement other bits of the Control / Status Register
      srot_ctrlstatus_register[SROT_CTRLSTS_RESP_WAITING]   <= ~llkic2_respfifo_empty;
      // Test Bits
      srot_ctrlstatus_register[63:32]						<= 32'hDEAD_BEEF;
      // A write has been requested
      if (reg_we_o) begin
        
        // Read or Writes to either RAMs while in operational mode should cause an error of some
        // sort, but we do not currently have a means of handling tilelink errors.  Thus, the
        // acccess will just be ignored
        // Decode to the Key RAM
        // Note: Addresses are in terms of bytes and the datapath is 64-bit wide
        if (reg_addr_o >= SROT_KEYRAM_ADDR && reg_addr_o <= (SROT_KEYRAM_ADDR + (SROT_KEYRAM_SIZE * 8) - 1)) begin
          
          // Both mode bits MUST BE ZERO to allow access to the key and key index RAMs
          if (srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_0] || srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_1])
            ;
          else
            keyram_write_i                  <= 1'b1;
        // Decode to the Key Index RAM
        end else if (reg_addr_o >= SROT_KEYINDEXRAM_ADDR && reg_addr_o <= (SROT_KEYINDEXRAM_ADDR + (SROT_KEYINDEXRAM_SIZE * 8) - 1)) begin
          // Both mode bits MUST BE ZERO to allow access to the key and key index RAMs
          if (srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_0] || srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_1])
            ;
          else
            keyindexram_write_i             <= 1'b1;
        // All other write decode events
        end else begin
          case (reg_addr_o)
            //
            // SROT Control Status Register
            //
            SROT_CTRLSTS_ADDR         : begin
              if (reg_wdata_o[SROT_CTRLSTS_MODEBIT_0])  srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_0] <= 1'b1;
              if (reg_wdata_o[SROT_CTRLSTS_MODEBIT_1])  srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_1] <= 1'b1;
            end // end SROT_CTRLSTS_ADDR
            // Write to the LLKIC2 Send FIFO (writing to a full FIFO will cause an error)
            SROT_LLKIC2_SENDRECV_ADDR : begin
              // Overflow condition
              if (llkic2_reqfifo_full) begin
                write_error               <= 1'b1;
              end else begin
                llkic2_reqfifo_wdata_i   <= reg_wdata_o;
                llkic2_reqfifo_wvalid_i  <= 1'b1;
              end // end else llkic2_reqfifo_full
            end // end SROT_LLKIC2_SEND_ADDR
            // Write to the Scratchpad 0 Register
            SROT_LLKIC2_SCRATCHPAD0_ADDR : begin
              srot_scratchpad0_register   <= reg_wdata_o;
            end
            // Write to the Scratchpad 1 Register
            SROT_LLKIC2_SCRATCHPAD1_ADDR : begin
              srot_scratchpad1_register   <= reg_wdata_o;
            end
            //    
            // All other decodes
            //            
            default             :
              write_error     <= 1'b1;
          endcase   // endcase reg_addr_o
        end   // end if aaddress decode
      end else begin
          // No writes, no errors.
          write_error     <= 1'b0;
      end // end if reg_we_o
    end // end else if (rst)
  end // end always
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // Read decode process
  //------------------------------------------------------------------------
  always @*
  begin
    // Default signal assignments
    reg_rdata_i                   = '0;
    read_error                    = 1'b0;
    llkic2_respfifo_clr_i         = 1'b0;
    llkic2_respfifo_rready_i      = 1'b0;
    // A read has been requested
    if (reg_re_o_d1) begin
      // Read or Writes to either RAMs while in operational mode should cause an error of some
      // sort, but we do not currently have a means of handling tilelink errors.  Thus, the
      // acccess will just be ignored
      // Decode to the Key RAM
      // Note: Addresses are in terms of bytes and the datapath is 64-bit wide
      if (reg_addr_o_d1 >= SROT_KEYRAM_ADDR && reg_addr_o_d1 <= (SROT_KEYRAM_ADDR + (SROT_KEYRAM_SIZE * 8) - 1)) begin
          
        // Both mode bits MUST BE ZERO to allow access to the key and key index RAMs
        if (srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_0] || srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_1])
          ;
        else
          reg_rdata_i                   = keyram_rdata_o;
      // Decode to the Key Index RAM
      end else if (reg_addr_o_d1 >= SROT_KEYINDEXRAM_ADDR && reg_addr_o_d1 <= (SROT_KEYINDEXRAM_ADDR + (SROT_KEYINDEXRAM_SIZE * 8) - 1)) begin
        // Both mode bits MUST BE ZERO to allow access to the key and key index RAMs
        if (srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_0] || srot_ctrlstatus_register[SROT_CTRLSTS_MODEBIT_1])
          ;
        else
          reg_rdata_i                   = keyindexram_rdata_o;
      // All other write decode events
      end else begin
        case (reg_addr_o_d1)
          //
          // SROT Control Status Register
          //
          SROT_CTRLSTS_ADDR           : begin
            reg_rdata_i                 = srot_ctrlstatus_register; 
          end // end SROT_CTRLSTS_ADDR
          //
          // Decode to the Receive FIFO
          //            
          SROT_LLKIC2_SENDRECV_ADDR   : begin
            if (llkic2_respfifo_empty) begin
              read_error                = 1'b1;
            end else begin
              llkic2_respfifo_rready_i  = 1'b1;
              reg_rdata_i               = llkic2_respfifo_rdata_o;  
            end // end llkic2_respfifo_empty
          end // SROT_LLKIC2_RECV_ADDR
          //
          // Scratchpad 0 Register
          //
          SROT_LLKIC2_SCRATCHPAD0_ADDR : begin
            reg_rdata_i                 = srot_scratchpad0_register;
          end
          //
          // Scratchpad 1 Register
          //
          SROT_LLKIC2_SCRATCHPAD1_ADDR : begin
            reg_rdata_i                 = srot_scratchpad1_register;
          end
          //
          // All other decodes
          //            
          default             : begin
            read_error                  = 1'b1;
          end // end default
        endcase   // endcase reg_addr_o
      end // end if address decode
    end // end if (reg_re_o)
  end // end always @(reg_addr_o or reg_re_o)
  //------------------------------------------------------------------------
  //------------------------------------------------------------------------
  // SRoT State Machine
  // Processes messages received via the SEND message FIFO, initiates
  // transactions with downstream LLKI Protocol Processing blocks via the
  // TL host interface, receives downstream responses, then generates the
  // responses back to the RISC-V.  Once the RISC-V initiates an LLKIC2
  // request, it should poll the SROT_CTRLSTS_RESP_WAITING bit in the
  // SROT_CTRLSTS_ADDR register to determine when a response has been
  // received.
  //------------------------------------------------------------------------
  reg [31:0]            rsvd;
  reg [7:0]             msg_id;
  reg [7:0]             status;
  reg [15:0]            msg_len;
  reg [7:0]             key_index;
  reg [15:0]            low_pointer;
  reg [15:0]            high_pointer;
  reg [15:0]            current_pointer;  // Used to track the currently selected
                                          // Key RAM word
  reg [7:0]             core_index;
  reg                   index_valid;
  reg [7:0]             wait_state_counter;
  // Perform a continuous assignment of the key index RAM fields,
  // making conding of the SRoT STM a bit cleaner.
  always @*
  begin
    low_pointer         = keyindexram_rdata_o[15:0];
    high_pointer        = keyindexram_rdata_o[31:16];
    core_index          = keyindexram_rdata_o[39:32];
    index_valid         = keyindexram_rdata_o[63];
  end   // end always @*
  always @(posedge clk or posedge rst)
  begin
    if (rst) begin
      host_req_i                <= '0;
      host_addr_i               <= '0;
      host_we_i                 <= '0;
      host_wdata_i              <= '0;
      keyindexram_stm_addr_i    <= '0;
      keyram_stm_addr_i         <= '0;
      llkic2_reqfifo_clr_i      <= 1'b0;
      llkic2_reqfifo_rready_i   <= 1'b0;
      llkic2_respfifo_wvalid_i  <= 1'b0;
      llkic2_respfifo_wdata_i   <= '0;
      rsvd                      <= '0;
      msg_id                    <= '0;
      status                    <= '0;
      msg_len                   <= '0;
      key_index                 <= '0;
      current_pointer           <= '0;
      wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
      srot_current_state        <= ST_SROT_IDLE;
    end else begin
  
      // Case for the SRoT STM
      case (srot_current_state)
        //------------------------------------------------------------------
        // IDLE State
        //------------------------------------------------------------------
        ST_SROT_IDLE          : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyindexram_stm_addr_i    <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= 1'b0;
          llkic2_respfifo_wvalid_i  <= 1'b0;
          llkic2_respfifo_wdata_i   <= '0;
          rsvd                      <= '0;
          msg_id                    <= '0;
          status                    <= '0;
          msg_len                   <= '0;
          key_index                 <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_IDLE;
          // The SRoT STM will stay idle until it determines that a message is
          // present in the Send FIFO.  All messages from RISC-V are expected to
          // be one 64-bit word in length.
          if (~llkic2_reqfifo_empty && llkic2_reqfifo_rvalid_o) begin
            // Capture the message elements (incoming status is ignored)
            msg_id                    <= llkic2_reqfifo_rdata_o[7:0];
            msg_len                   <= llkic2_reqfifo_rdata_o[31:16];
            key_index                 <= llkic2_reqfifo_rdata_o[39:32];
            rsvd                      <= llkic2_reqfifo_rdata_o[63:40];
            // Assert the Send FIFO read enable
            llkic2_reqfifo_rready_i  <= 1'b1;
            // Jump to the next state
            srot_current_state        <= ST_SROT_MESSAGE_CHECK;              
          end // end if (~llkic2_reqfifo_empty)
        end // end ST_SROT_IDLE
        //------------------------------------------------------------------
        // Message Check State
        //------------------------------------------------------------------
        ST_SROT_MESSAGE_CHECK   : begin
          // Default signal assignment
          host_req_i                <= '0;  
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyindexram_stm_addr_i    <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_IDLE;
          case (msg_id)
            // A valid request haas been received via the C2 RISCV -> SRoT Inteface
            LLKI_MID_C2LOADKEYREQ,
            LLKI_MID_C2CLEARKEYREQ,
            LLKI_MID_C2KEYSTATUSREQ : begin
              keyindexram_stm_addr_i  <= key_index;
              srot_current_state      <= ST_SROT_RETRIEVE_KEY_INDEX_WAIT_STATE;
              ;
            end
            // All other message ID (error condition)
            // Clear the send FIFO as a precaution
            default                 : begin
              llkic2_reqfifo_clr_i    <= 1'b1;
              status                  <= LLKI_STATUS_BAD_MSG_ID;
              srot_current_state      <= ST_SROT_C2_RESPONSE;
            end 
          endcase   // end case (msg_id)
          // The only valid message length for requests is one
          if (msg_len != 1) begin
            llkic2_reqfifo_clr_i      <= 1'b1;
            status                    <= LLKI_STATUS_BAD_MSG_LEN;
            srot_current_state        <= ST_SROT_C2_RESPONSE;
          end // end if (msg_len != 1)
          // The Key Index must >= 0 and < SROT_KEYINDEXRAM_SIZE
          if (key_index >= SROT_KEYINDEXRAM_SIZE) begin
            llkic2_reqfifo_clr_i      <= 1'b1;
            status                    <= LLKI_STATUS_KEY_INDEX_EXCEED;
            srot_current_state        <= ST_SROT_C2_RESPONSE;
          end // end if (key_index >= SROT_KEYINDEXRAM_SIZE)
        end // end ST_SROT_MESSAGE_CHECK
        //------------------------------------------------------------------
        // Wait State - Since STM outputs are registered as well as the
        // memory outputs, it will take two cycles following the assertion 
        // of the address for the data to show up.
        //------------------------------------------------------------------
        ST_SROT_RETRIEVE_KEY_INDEX_WAIT_STATE : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_RETRIEVE_KEY_INDEX;
        end // end ST_SROT_RETRIEVE_KEY_INDEX_WAIT_STATE
        //------------------------------------------------------------------
        // Retrieve (and check) key index State
        //------------------------------------------------------------------
        ST_SROT_RETRIEVE_KEY_INDEX    : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_RETRIEVE_KEY_INDEX;
          // Perform some error checking on the Key Index 
          // currently being referenced.  Error checking
          // is somewhat "hierchical in nature"
          // 
          // Key Index is NOT valid
          if (!index_valid) begin
            llkic2_reqfifo_clr_i    <= 1'b1;
            status                  <= LLKI_STATUS_KEY_INDEX_INVALID;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // Pointer related checks
          end else if (low_pointer   >= SROT_KEYRAM_SIZE  ||  // Low pointer exceeds the key RAM
                       high_pointer  >= SROT_KEYRAM_SIZE  ||  // High pointer exceeds the key RAM
                        low_pointer  > high_pointer) begin    // Low pointer > high pointer
            llkic2_reqfifo_clr_i    <= 1'b1;
            status                  <= LLKI_STATUS_BAD_POINTER_PAIR;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // The specified target core index exceeds the maximum entry
          // in the LLKI Core Index Array
          end else if (core_index > $high(LLKI_CORE_INDEX_ARRAY)) begin
            llkic2_reqfifo_clr_i    <= 1'b1;
            status                  <= LLKI_STATUS_BAD_CORE_INDEX;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // The received message has been checked for errors and the selected key
          // index looks ok.  
          end else begin
            // Jump to the next state
            srot_current_state      <= ST_SROT_KL_REQ_HEADER;
          end   // end if (!index_valid)
        end   // ST_RETRIEVE_KEY_INDEX
        //------------------------------------------------------------------
        // Create Header for the request to the specified LLKI-PP
        //------------------------------------------------------------------
        ST_SROT_KL_REQ_HEADER             : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_REQ_ISSUE;
          // Save the low pointer, as it will used to determine how many key
          // words we will be sending as well as indexing the Key RAM
          current_pointer           <= low_pointer;
          // Header generation is message specific
          case (msg_id)
            LLKI_MID_C2LOADKEYREQ   : begin
              host_wdata_i[7:0]       <= LLKI_MID_KLLOADKEYREQ;
              // For the Load Key Request Message length is equal
              // to the 2 + (high_pointer - low pointer).
              host_wdata_i[31:16]     <= (high_pointer - low_pointer) + 2;
              host_addr_i             <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
              // Assert write enable and req (indicates a TL PutFullData operation)
              host_req_i              <= 1'b1;
              host_we_i               <= 1'b1;
            end
            LLKI_MID_C2CLEARKEYREQ  : begin
              host_wdata_i[7:0]       <= LLKI_MID_KLCLEARKEYREQ;
              host_wdata_i[31:16]     <= 16'h01;
              host_addr_i             <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
              // Assert write enable and req (indicates a TL PutFullData operation)
              host_req_i              <= 1'b1;
              host_we_i               <= 1'b1;
            end
            LLKI_MID_C2KEYSTATUSREQ : begin
              host_wdata_i[7:0]       <= LLKI_MID_KLKEYSTATUSREQ;
              host_wdata_i[31:16]     <= 16'h01;
              host_addr_i             <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
              // Assert write enable and req (indicates a TL PutFullData operation)
              host_req_i              <= 1'b1;
              host_we_i               <= 1'b1;
            end
            // Since we already checked for valid message IDs,
            // this truely is a trap condition
            default                 : begin
              llkic2_reqfifo_clr_i    <= 1'b1;
              status                  <= LLKI_STATUS_BAD_CORE_INDEX;
              srot_current_state      <= ST_SROT_C2_RESPONSE;
            end
          endcase
        end   // ST_SROT_KL_CREATE_HEADER
        //------------------------------------------------------------------
        // Assert host request in order to send the LLKI-PP Request
        //------------------------------------------------------------------
        ST_SROT_KL_REQ_ISSUE                : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_we_i                 <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_REQ_ISSUE;
          // Continue to assert write enable and req (indicates a TL PutFullData operation)
          host_req_i                <= 1'b1;
          host_we_i                 <= 1'b1;
          // Wait for grant indicating the write has been sent
          if (host_gnt_o) begin
            host_req_i              <= 1'b0;
            host_we_i               <= 1'b0;
            
            // Jump to the Request Wait for Ack state
            srot_current_state      <= ST_SROT_KL_REQ_WAIT_FOR_ACK;
            // Did an error get asserted?
            if (host_err_o) begin
              msg_id                <= LLKI_MID_C2ERRORRESP;        
              status                <= LLKI_STATUS_KL_TILELINK_ERROR;
              msg_len               <= 8'h01;
              srot_current_state    <= ST_SROT_C2_RESPONSE;
            end
          end // end if (host_gnt_o)
        end // ST_SROT_KL_REQ_WAIT_FOR_GRANT
        //------------------------------------------------------------------
        // Using the OpenTitan tlul_adapter_host module, even writes get
        // "acknowledged" through the assertion of the valid_o bit, which
        // is directly mapped from the TL-UL D channel valid bit
        //------------------------------------------------------------------
        ST_SROT_KL_REQ_WAIT_FOR_ACK         : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_we_i                 <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_REQ_WAIT_FOR_ACK;
          // The request has been acknowledged
          if (host_valid_o) begin
            // Point the Key RAM to the current word
            keyram_stm_addr_i       <= current_pointer;
            // If this is a Load Key request, then we need to begin
            // the cycle of reading the ready bit from the selected
            // LLKI-PP block.  When ready, we can issue a key word
            // write.  Once all the key words have be written, then
            // we should look for a standard response from the LLKI-PP
            if (msg_id == LLKI_MID_C2LOADKEYREQ)
              srot_current_state    <= ST_SROT_KL_READ_READY_STATUS;
            else
              srot_current_state    <= ST_SROT_KL_READ_RESP_STATUS;
          end   // end if (host_valid_o)
        end // ST_SROT_KL_REQ_WAIT_FOR_ACK
        //------------------------------------------------------------------
        // Before writing a key word to the select LLKI-PP block, we need
        // read the ready bit
        //------------------------------------------------------------------
        ST_SROT_KL_READ_READY_STATUS        : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_READ_READY_STATUS;
          // We want to read the selected LLKI-PP Control/Status Register
          host_addr_i               <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_CTRLSTS_OFFSET;
          host_req_i                <= 1'b1;
          // Did an error get asserted?
          if (host_err_o) begin
            msg_id                  <= LLKI_MID_C2ERRORRESP;        
            status                  <= LLKI_STATUS_KL_TILELINK_ERROR;
            msg_len                 <= 8'h01;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // Wait until the request has been granted, then jump to
          // the check status state
          end else if (host_gnt_o) begin
            // Jump to next 
            srot_current_state      <= ST_SROT_KL_CHECK_READY_STATUS;
          end
        end // ST_SROT_KL_READ_READY_STATUS
        //------------------------------------------------------------------
        // The Ready Status has been read, now time to check it
        //------------------------------------------------------------------
        ST_SROT_KL_CHECK_READY_STATUS       : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_CHECK_READY_STATUS;
          // Valid data has been returned
          if (host_valid_o) begin
          	// If a response is waiting at this point, the select LLKI PP block
          	// has prematurely generated a response, likely due to an error condition.
          	// Jump to fetching the response status
          	if (host_rdata_o[LLKIKL_CTRLSTS_RESP_WAITING] == 1'b1) begin
              
              srot_current_state        <= ST_SROT_KL_READ_RESP_STATUS;
            // The select LLKI-PP is ready for a key
            end else if (host_rdata_o[LLKIKL_CTRLSTS_READY_FOR_KEY] == 1'b1) begin
              // Issue the key write, understanding that if host_gnt_o is
              // already asserted, this will only be set for a single clock cycle
              host_addr_i               <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
              host_wdata_i              <= keyram_rdata_o;
              host_req_i                <= 1'b1;
              host_we_i                 <= 1'b1;
              srot_current_state        <= ST_SROT_KL_LOAD_KEY_WORD;
            // Response is NOT waiting, jump to wait state
            end else begin
              srot_current_state        <= ST_SROT_KL_READY_WAIT_STATE;
            end
          end // end else if (host_err_o)
        end // ST_SROT_KL_CHECK_READY_STATUS
        //------------------------------------------------------------------
        // Wait state to avoid spamming the LLKI-PP with requests
        //------------------------------------------------------------------
        ST_SROT_KL_READY_WAIT_STATE         : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          srot_current_state        <= ST_SROT_KL_READY_WAIT_STATE;
          // Decrement the wait state counter
          wait_state_counter        <= wait_state_counter - 1;
          // Did an error get asserted?
          if (host_err_o) begin
            msg_id                  <= LLKI_MID_C2ERRORRESP;        
            status                  <= LLKI_STATUS_KL_TILELINK_ERROR;
            msg_len                 <= 8'h01;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          end else if (wait_state_counter == 0) begin
            srot_current_state      <= ST_SROT_KL_READ_READY_STATUS;
          end
        end // ST_SROT_KL_READY_WAIT_STATE
        //------------------------------------------------------------------
        // We know the LLKI-PP is ready for a key word, so let's send it
        //------------------------------------------------------------------
        ST_SROT_KL_LOAD_KEY_WORD          : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_LOAD_KEY_WORD;
          // Hold the signals, until host_gnt_o is issued
          host_addr_i               <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
          host_wdata_i              <= keyram_rdata_o;
          host_req_i                <= 1'b1;
          host_we_i                 <= 1'b1;
          // The write request has been granted
          if (host_gnt_o) begin
            // Clear up some signals
            host_addr_i             <= '0;            
            host_wdata_i            <= '0;
            host_req_i              <= '0;
            host_we_i               <= '0;
            // Jump to the next state
            srot_current_state      <= ST_SROT_KL_LOAD_KEY_WORD_WAIT_FOR_ACK;
          end
        end // ST_SROT_KL_LOAD_KEY_WORD
        //------------------------------------------------------------------
        // The key word write has been issued, we need to wait until it
        // is acknowledged
        //------------------------------------------------------------------
        ST_SROT_KL_LOAD_KEY_WORD_WAIT_FOR_ACK   : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_LOAD_KEY_WORD_WAIT_FOR_ACK;
          // The write has been acknowledged
          if (host_valid_o) begin
            // Is this the last word of the load?  If yes, then jump to the
            // read response status state
            if (current_pointer == high_pointer) begin
              srot_current_state    <= ST_SROT_KL_READ_RESP_STATUS;
            // We have more words.  Increment the current pointer and
            // read the LLKI-PP ready status
            end else begin
              // Point the Key RAM to the next word
              keyram_stm_addr_i     <= current_pointer + 1;
              current_pointer       <= current_pointer + 1;
              srot_current_state    <= ST_SROT_KL_READ_READY_STATUS;
            end // end if (current_pointer == high_pointer)
          end
        end // ST_SROT_KL_LOAD_KEY_WORD_WAIT_FOR_ACK
        //------------------------------------------------------------------
        // Now, the request has been sent, it is time to poll the response
        // waiting bit in the target LLKI-PP
        //------------------------------------------------------------------
        ST_SROT_KL_READ_RESP_STATUS         : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_READ_RESP_STATUS;
          // We want to read the selected LLKI-PP Control/Status Register
          host_addr_i               <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_CTRLSTS_OFFSET;
          host_req_i                <= 1'b1;
          // Did an error get asserted?
          if (host_err_o) begin
            msg_id                  <= LLKI_MID_C2ERRORRESP;        
            status                  <= LLKI_STATUS_KL_TILELINK_ERROR;
            msg_len                 <= 8'h01;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // Wait until the request has been granted, then jump to
          // the check status state
          end else if (host_gnt_o) begin
            srot_current_state      <= ST_SROT_KL_CHECK_RESP_STATUS;
          end
        end // ST_SROT_KL_RESP_READ_STATUS
        //------------------------------------------------------------------
        // The read request has been issued and granted, but now we need
        // to wait until valid data is returned
        //------------------------------------------------------------------
        ST_SROT_KL_CHECK_RESP_STATUS       : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i           <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_CHECK_RESP_STATUS;
          // Valid data has been returned
          if (host_valid_o) begin
            // Response is waiting in the LLKI PP.  Initiate the request 
            // as we tranisition to the next state            
            if (host_rdata_o[LLKIKL_CTRLSTS_RESP_WAITING] == 1'b1) begin
              // We want to read the selected LLKI-PP Send/Receive Queue
              host_addr_i               <= LLKI_CORE_INDEX_ARRAY[core_index] + LLKI_SENDRECV_OFFSET;
              host_req_i                <= 1'b1;
              srot_current_state        <= ST_SROT_KL_RESP_READ;
            // Response is NOT waiting, jump to wait state
            end else begin
              srot_current_state        <= ST_SROT_KL_RESP_WAIT_STATE;
            end
          end // end else if (host_err_o)
        end // ST_SROT_KL_RESP_CHECK_STATUS
        //------------------------------------------------------------------
        // This wait state is used to avoid spaming the Host interface
        // while waiting for the select LLKI-PP block to process a message
        //------------------------------------------------------------------
        ST_SROT_KL_RESP_WAIT_STATE        : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i           <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          srot_current_state        <= ST_SROT_KL_RESP_WAIT_STATE;
          // Decrement the wait state counter
          wait_state_counter        <= wait_state_counter - 1;
          // Did an error get asserted?
          if (host_err_o) begin
            msg_id                  <= LLKI_MID_C2ERRORRESP;        
            status                  <= LLKI_STATUS_KL_TILELINK_ERROR;
            msg_len                 <= 8'h01;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          end else if (wait_state_counter == 0) begin
            srot_current_state      <= ST_SROT_KL_READ_RESP_STATUS;
          end
        end // ST_SROT_KL_RESP_WAIT_STATE
        //------------------------------------------------------------------
        // Read LLKI-PP Reponse
        //------------------------------------------------------------------
        ST_SROT_KL_RESP_READ        : begin
          // Default signal assignment
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyram_stm_addr_i           <= '0;
          llkic2_reqfifo_rready_i   <= 1'b0;
          llkic2_respfifo_wvalid_i  <= 1'b0;
          llkic2_respfifo_wdata_i   <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_KL_RESP_READ;
          // Did an error get asserted?
          if (host_err_o) begin
            msg_id                  <= LLKI_MID_C2ERRORRESP;        
            status                  <= LLKI_STATUS_KL_TILELINK_ERROR;
            msg_len                 <= 8'h01;
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          // Valid data has been received
          end else if (host_valid_o) begin
            // Deassert request and address signals
            host_req_i              <= '0;
            host_addr_i             <= '0;
            // Capture the reponse fields from the LLKI-PP block
            msg_id                  <= host_rdata_o[7:0];
            status                  <= host_rdata_o[15:8];
            msg_len                 <= host_rdata_o[31:16];
            // Just to creating a C2 Response message
            srot_current_state      <= ST_SROT_C2_RESPONSE;
          end // end else if (host_err_o)
        end // end ST_SROT_KL_RESP_READ
        //------------------------------------------------------------------
        // Generate the LLKI C2 Response Message
        //------------------------------------------------------------------
        ST_SROT_C2_RESPONSE         : begin
          // Default signal states
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyindexram_stm_addr_i    <= '0;
          keyram_stm_addr_i         <= '0;
          llkic2_reqfifo_clr_i      <= '0;
          llkic2_reqfifo_rready_i   <= 1'b0;
          llkic2_respfifo_wdata_i   <= '0;
          llkic2_respfifo_wvalid_i  <= 1'b0;
          key_index                 <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_IDLE;
          // Create the response message.  Errors can be generated
          // in the following ways:
          //  - LLKIC2 message is bad
          //  - The reference key index is bad
          //  - A response received via the LLKI-KL interface indicates an error
          //  - A tilelink error is indicated on the LLKI-KL interface
          case (status)
            //------------------------------------------------------------------
            // Processing a good response received via the LLKI-KL interface
            //------------------------------------------------------------------
            LLKI_STATUS_GOOD,
            LLKI_STATUS_KEY_PRESENT,
            LLKI_STATUS_KEY_NOT_PRESENT    : begin
              // Set most of the LLKI-C2 response fields
              llkic2_respfifo_wdata_i[15:8]   <= status;
              llkic2_respfifo_wdata_i[31:16]  <= 8'h01;
              llkic2_respfifo_wdata_i[63:32]  <= rsvd;
              llkic2_respfifo_wvalid_i        <= 1'b1;
              // Determine the LLKI C2 Response ID
              case (msg_id)
                LLKI_MID_KLLOADKEYACK       : llkic2_respfifo_wdata_i[7:0]  <= LLKI_MID_C2LOADKEYACK;
                LLKI_MID_KLCLEARKEYACK      : llkic2_respfifo_wdata_i[7:0]  <= LLKI_MID_C2CLEARKEYACK;
                LLKI_MID_KLKEYSTATUSRESP    : llkic2_respfifo_wdata_i[7:0]  <= LLKI_MID_C2KEYSTATUSRESP;
                default                     : begin
                  llkic2_respfifo_wdata_i[7:0]  <= LLKI_MID_KLERRORRESP;
                  llkic2_respfifo_wdata_i[15:8] <= LLKI_STATUS_KL_RESP_BAD_MSG_ID;
                end
              endcase
            end
            //------------------------------------------------------------------
            // An error has occurred
            //------------------------------------------------------------------
            LLKI_STATUS_BAD_MSG_ID,
            LLKI_STATUS_BAD_MSG_LEN,
            LLKI_STATUS_KEY_INDEX_EXCEED,
            LLKI_STATUS_KEY_INDEX_INVALID,
            LLKI_STATUS_BAD_POINTER_PAIR,
            LLKI_STATUS_BAD_CORE_INDEX,
            LLKI_STATUS_KL_REQ_BAD_MSG_ID,
            LLKI_STATUS_KL_REQ_BAD_MSG_LEN,
            LLKI_STATUS_KL_RESP_BAD_MSG_ID,            
            LLKI_STATUS_KL_TILELINK_ERROR,
            LLKI_STATUS_KL_LOSS_OF_SYNC,
            LLKI_STATUS_KL_BAD_KEY_LEN,
            LLKI_STATUS_KL_KEY_OVERWRITE     	: begin
              llkic2_respfifo_wdata_i[7:0]    <= LLKI_MID_C2ERRORRESP;
              llkic2_respfifo_wdata_i[15:8]   <= status;
              llkic2_respfifo_wdata_i[31:16]  <= 16'h01;
              llkic2_respfifo_wdata_i[63:32]  <= rsvd;
              llkic2_respfifo_wvalid_i        <= 1'b1;
            end
            //------------------------------------------------------------------
            // Trap state - Create an LLKI-C2 message with an unknown error
            //------------------------------------------------------------------
            default                           : begin
              llkic2_respfifo_wdata_i[7:0]    <= LLKI_MID_C2ERRORRESP;
              llkic2_respfifo_wdata_i[15:8]   <= LLKI_STATUS_UNKNOWN_ERROR;
              llkic2_respfifo_wdata_i[31:16]  <= 16'h01;
              llkic2_respfifo_wdata_i[63:32]  <= rsvd;
              llkic2_respfifo_wvalid_i        <= 1'b1;
            end
          endcase // case (status)
          // Return to IDLE
          srot_current_state        <= ST_SROT_IDLE;
        end   // ST_SROT_ERROR_RESPONSE
        //------------------------------------------------------------------
        // Trap State
        //------------------------------------------------------------------
        default                       : begin
          host_req_i                <= '0;
          host_addr_i               <= '0;
          host_we_i                 <= '0;
          host_wdata_i              <= '0;
          keyindexram_stm_addr_i      <= '0;
          keyram_stm_addr_i           <= '0;
          llkic2_reqfifo_clr_i      <= '0;
          llkic2_reqfifo_rready_i   <= '0;
          llkic2_respfifo_wvalid_i  <= '0;
          llkic2_respfifo_wdata_i   <= '0;
          rsvd                      <= '0;
          msg_id                    <= '0;
          status                    <= '0;
          msg_len                   <= '0;
          key_index                 <= '0;
          current_pointer           <= '0;
          wait_state_counter        <= SROT_WAIT_STATE_COUNTER_INIT;
          srot_current_state        <= ST_SROT_IDLE;
        end
        //------------------------------------------------------------------
      endcase   // endcase srot_current_state
    end // end if rst
  end // end always
endmodule   // endmodule srot_wrapper
 | 
| 
	// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//
//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:       tlul_adaptger_reg.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     Component modified from OpenTitan original
//                  to support a broader range of the Tilelink
//                  protocol
//                  
//************************************************************************
`include "prim_assert.sv"
//
// Modifications:
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// Module modified to allow for a delayed read-response (and avoid the live-decode problem)
//
/**
 * Tile-Link UL adapter for Register interface
 */
module tlul_adapter_reg import tlul_pkg::*; #(
  parameter  int RegAw = 8,
  parameter  int RegDw = 32, // Shall be matched with TL_DW
  localparam int RegBw = RegDw/8
) (
  input clk_i,
  input rst_ni,
  // TL-UL interface
  input  tl_h2d_t tl_i,
  output tl_d2h_t tl_o,
  // Register interface
  output logic             re_o,
  output logic             we_o,
  output logic [RegAw-1:0] addr_o,
  output logic [RegDw-1:0] wdata_o,
  output logic [RegBw-1:0] be_o,
  input        [RegDw-1:0] rdata_i,
  input                    ack_i,
  input                    error_i
);
  localparam int IW  = $bits(tl_i.a_source);
  localparam int SZW = $bits(tl_i.a_size);
  logic d_valid;
  logic outstanding_read;   // A read transaction is outstanding
  logic outstanding_write;  // A write transaction is outstanding
  logic a_ack;
  logic [RegDw-1:0] rdata;
  logic             error, err_internal;
  logic malformed_meta_err; // User signal format error or unsupported
  logic tl_err;             // Common TL-UL error checker
  logic [IW-1:0]  req_id;
  logic [SZW-1:0] req_sz;
  tl_d_op_e       resp_opcode;
  logic rd_req, wr_req;
  // Assign individual signals to the D Channel
  assign tl_o = '{
    a_ready:  ~(outstanding_read || outstanding_write),
    d_valid:  d_valid,
    d_opcode: resp_opcode,
    d_param:  '0,
    d_size:   req_sz,
    d_source: req_id,
    d_sink:   '0,
    d_data:   rdata,
    d_user:  '0,
    d_error: error
  };
  // We will immediately begin processing the transaction if we don't currently have one outstanding
  assign a_ack          = tl_i.a_valid & tl_o.a_ready;
  
  // Request signal
  assign wr_req  = a_ack & ((tl_i.a_opcode == PutFullData) | (tl_i.a_opcode == PutPartialData));
  assign rd_req  = a_ack & (tl_i.a_opcode == Get);
  assign we_o    = wr_req & ~err_internal;
  assign re_o    = rd_req & ~err_internal;
  assign addr_o  = tl_i.a_address;
  assign wdata_o = tl_i.a_data;
  assign be_o    = tl_i.a_mask;
  // Given the amount of changes needed to allow an external component to control acknowledgement timing,
  // everything is being moved here
  always_ff @(posedge clk_i or negedge rst_ni) begin
    if (!rst_ni) begin
      outstanding_read      <= '0;
      outstanding_write     <= '0;
      req_id                <= '0;
      req_sz                <= '0;
      resp_opcode           <= AccessAck;
      error                 <= '0;
      d_valid               <= '0;
      rdata                 <= '0;
    end else begin
      // Queue up some of the d channel response fields
      // Internal errors will be detected at the time A Channel is being processed
      if (a_ack) begin
        req_id              <= tl_i.a_source;
        req_sz              <= tl_i.a_size;        
        resp_opcode         <= (rd_req) ? AccessAckData : AccessAck;  // Return AccessAckData regardless of error
        error               <= err_internal; 
      end;
      // Acknowledgements (reads and writes) need to be delayed
      // to allow higher level (external) decode to do things
      if (wr_req) begin
        outstanding_write   <= '1;
      end else if (rd_req) begin
        outstanding_read    <= '1;
      end
      // If a read is ongoing and has been acknowleedge, time
      // to assert valid on the D channel (and capture rdata and or in the external error)
      // Adding a_ack allows for zero-cycle decode on reads
      if (ack_i & (outstanding_read | a_ack)) begin
        d_valid             <= '1;
        rdata               <= rdata_i;
        error               <= error | error_i;
      // If a write is ongoing, just capture the valid and or in the external error)
      // Adding a_ack allows for zero-cycle decode on writes
      end else if (ack_i & (outstanding_write | a_ack)) begin
        d_valid             <= '1;
        error               <= error | error_i;
      end else if (tl_i.d_ready & (outstanding_read | outstanding_write)) begin
        outstanding_read    <= '0;
        outstanding_write   <= '0;
        req_id              <= '0;
        req_sz              <= '0;
        resp_opcode         <= AccessAck;
        error               <= '0;
        d_valid             <= '0;
        rdata               <= '0;
      end
    end // end if (!rst_ni)
  end // end always
  ////////////////////
  // Error Handling //
  ////////////////////
  assign err_internal = malformed_meta_err | tl_err;
  // malformed_meta_err
  //    Raised if not supported feature is turned on or user signal has malformed
  assign malformed_meta_err = (tl_i.a_user.parity_en == 1'b1);
  // tl_err : separate checker
  tlul_err u_err (
    .clk_i,
    .rst_ni,
    .tl_i,
    .err_o (tl_err)
  );
  // Ensure we don't have a data-width mismatch
  `ASSERT_INIT(MatchedWidthAssert, RegDw == top_pkg::TL_DW)
  // Ensure we don't have an error asserted
  `ASSERT(tlul_d_channel_error, !tl_o.d_error, clk_i, !rst_ni)
endmodule
 | 
| 
	// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//
//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD 2-Clause
//
// File Name:       tlul_err.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     OpenTitan tlul_err.sv customized for the Common 
//                  Evaluation Plafform
// Notes:           Updated to support 8-byte transfers
//************************************************************************
`include "prim_assert.sv"
module tlul_err import tlul_pkg::*; (
  input clk_i,
  input rst_ni,
  input tl_h2d_t tl_i,
  output logic err_o
);
  localparam int IW  = $bits(tl_i.a_source);
  localparam int SZW = $bits(tl_i.a_size);
  localparam int DW  = $bits(tl_i.a_data);
  localparam int MW  = $bits(tl_i.a_mask);
  localparam int SubAW = $clog2(DW/8);
  logic opcode_allowed, a_config_allowed;
  logic op_full, op_partial, op_get;
  assign op_full    = (tl_i.a_opcode == PutFullData);
  assign op_partial = (tl_i.a_opcode == PutPartialData);
  assign op_get     = (tl_i.a_opcode == Get);
  // Anything that doesn't fall into the permitted category, it raises an error
  assign err_o = ~(opcode_allowed & a_config_allowed);
  // opcode check
  assign opcode_allowed = (tl_i.a_opcode == PutFullData)
                        | (tl_i.a_opcode == PutPartialData)
                        | (tl_i.a_opcode == Get);
  // a channel configuration check (assertion indicates condition is GOOD)
  logic addr_sz_chk;    // address and size alignment check
  logic mask_chk;       // inactive lane a_mask check
  logic fulldata_chk;   // PutFullData should have size match to mask
  // For single byte transfers, ensure the address offset corresponds to the
  // the appropriate mask bit (and no other mask bits are asserted)
  logic [MW-1:0] mask;
  assign mask = (1 << tl_i.a_address[SubAW-1:0]);
  always_comb begin
    addr_sz_chk  = 1'b0;
    mask_chk     = 1'b0;
    fulldata_chk = 1'b0; // Only valid when opcode is PutFullData
    if (tl_i.a_valid) begin
      unique case (tl_i.a_size)
        'h0: begin // 1 Byte
          addr_sz_chk  = 1'b1;
          mask_chk     = ~|(tl_i.a_mask & ~mask); // ensure no other mask bits are set
          fulldata_chk = |(tl_i.a_mask & mask);   // ensure the address/mask align
        end
        'h1: begin // 2 Bytes
          addr_sz_chk     = ~tl_i.a_address[0];      // Per TL spec, address must be aligned to size
          if (DW==64) begin
            unique case (tl_i.a_address[2:1])
              'h0     : begin
                mask_chk      = ~|(tl_i.a_mask & 8'b11111100);
                fulldata_chk  = &tl_i.a_mask[1:0];
              end
              'h1     : begin
                mask_chk      = ~|(tl_i.a_mask & 8'b11110011);
                fulldata_chk  = &tl_i.a_mask[3:2];
              end
              'h2     : begin
                mask_chk      = ~|(tl_i.a_mask & 8'b11001111);
                fulldata_chk  = &tl_i.a_mask[5:4];
              end
              'h3     : begin
                mask_chk      = ~|(tl_i.a_mask & 8'b00111111);
                fulldata_chk  = &tl_i.a_mask[7:6];
              end
              default : begin
                mask_chk      = 1'b0;  
                fulldata_chk  = 1'b0;
              end
            endcase
          end else begin
            mask_chk          = (tl_i.a_address[1]) ? ~|(tl_i.a_mask & 4'b0011) : ~|(tl_i.a_mask & 4'b1100);
            fulldata_chk      = (tl_i.a_address[1]) ? &tl_i.a_mask[3:2] : &tl_i.a_mask[1:0];
          end // end if (DW==64)
        end
        'h2: begin // 4 Bytes
          if (DW==64) begin
            addr_sz_chk  = ~|tl_i.a_address[1:0];   // Per TL spec, address must be aligned to size
            mask_chk     = (tl_i.a_address[2]) ? ~|(tl_i.a_mask & 8'b00001111) : ~|(tl_i.a_mask & 8'b11110000);
            fulldata_chk = (tl_i.a_address[2]) ? &tl_i.a_mask[7:4] : &tl_i.a_mask[3:0];
          end else begin
            addr_sz_chk  = ~|tl_i.a_address[1:0];   // Per TL spec, address must be aligned to size
            mask_chk     = 1'b1;                    // Mas alignment not an issue when all mask bits are asserted
            fulldata_chk = &tl_i.a_mask[3:0];       // All mask bits should be asserted
          end // end if (DW==64)
        end
        'h3,          // 8 Bytes
        'h6: begin    // 64 Bytes
          if (DW==64) begin
            addr_sz_chk  = ~|tl_i.a_address[2:0]; // Per TL spec, address must be aligned to size
            mask_chk     = 1'b1;
            fulldata_chk = &tl_i.a_mask[7:0];     // Given 8-byte transfer, all mask bits should be set
          // Unsupported sizes for DW != 64
          end else begin
            addr_sz_chk  = 1'b0;
            mask_chk     = 1'b0;
            fulldata_chk = 1'b0;
          end // end if (DW==64)
        end
        default: begin // Unsupported/invalid Sizes
          addr_sz_chk  = 1'b0;
          mask_chk     = 1'b0;
          fulldata_chk = 1'b0;
        end
      endcase
    end else begin
      addr_sz_chk  = 1'b0;
      mask_chk     = 1'b0;
      fulldata_chk = 1'b0;
    end
  end
  assign a_config_allowed = addr_sz_chk
                          & mask_chk
                          & (op_get | op_partial | fulldata_chk) ;
  // Only 32/64 bit data width for current tlul_err
  `ASSERT_INIT(dataWidthOnly32_64_A, (DW == 32) || (DW == 64))
endmodule
 | 
| 
	// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//
// TL-UL fifo, used to add elasticity or an asynchronous clock crossing
// to an TL-UL bus.  This instantiates two FIFOs, one for the request side,
// and one for the response side.
//
//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:       tlul_fifo_sync.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     Sycnhronous TL-UL FIFO from the OpenTitan Project.  
// Notes:           Customized to bring out the depth signals of the
//                  underlying fifo primatives
//
//
//************************************************************************
module tlul_fifo_sync #(
  parameter int unsigned ReqPass    = 1'b1,
  parameter int unsigned RspPass    = 1'b1,
  parameter int unsigned ReqDepth   = 2,
  parameter int unsigned RspDepth   = 2,
  parameter int unsigned SpareReqW  = 1,
  parameter int unsigned SpareRspW  = 1,
  localparam int unsigned ReqDepthW = prim_util_pkg::vbits(ReqDepth + 1),
  localparam int unsigned RspDepthW = prim_util_pkg::vbits(RspDepth + 1)
) (
  input                     clk_i,
  input                     rst_ni,
  input  tlul_pkg::tl_h2d_t tl_h_i,
  output tlul_pkg::tl_d2h_t tl_h_o,
  output tlul_pkg::tl_h2d_t tl_d_o,
  input  tlul_pkg::tl_d2h_t tl_d_i,
  input  [SpareReqW-1:0]    spare_req_i,
  output [SpareReqW-1:0]    spare_req_o,
  input  [SpareRspW-1:0]    spare_rsp_i,
  output [SpareRspW-1:0]    spare_rsp_o,
  output [ReqDepthW-1:0]    req_depth_o,
  output [RspDepthW-1:0]    rsp_depth_o
);
  // Put everything on the request side into one FIFO
  localparam int unsigned REQFIFO_WIDTH = $bits(tlul_pkg::tl_h2d_t) -2 + SpareReqW;
  prim_fifo_sync #(.Width(REQFIFO_WIDTH), .Pass(ReqPass), .Depth(ReqDepth)) reqfifo (
    .clk_i,
    .rst_ni,
    .clr_i         (1'b0          ),
    .wvalid_i      (tl_h_i.a_valid),
    .wready_o      (tl_h_o.a_ready),
    .wdata_i       ({tl_h_i.a_opcode ,
                     tl_h_i.a_param  ,
                     tl_h_i.a_size   ,
                     tl_h_i.a_source ,
                     tl_h_i.a_address,
                     tl_h_i.a_mask   ,
                     tl_h_i.a_data   ,
                     tl_h_i.a_user   ,
                     spare_req_i}),
    .depth_o       (req_depth_o),
    .rvalid_o      (tl_d_o.a_valid),
    .rready_i      (tl_d_i.a_ready),
    .rdata_o       ({tl_d_o.a_opcode ,
                     tl_d_o.a_param  ,
                     tl_d_o.a_size   ,
                     tl_d_o.a_source ,
                     tl_d_o.a_address,
                     tl_d_o.a_mask   ,
                     tl_d_o.a_data   ,
                     tl_d_o.a_user   ,
                     spare_req_o}));
  // Put everything on the response side into the other FIFO
  localparam int unsigned RSPFIFO_WIDTH = $bits(tlul_pkg::tl_d2h_t) -2 + SpareRspW;
  prim_fifo_sync #(.Width(RSPFIFO_WIDTH), .Pass(RspPass), .Depth(RspDepth)) rspfifo (
    .clk_i,
    .rst_ni,
    .clr_i         (1'b0          ),
    .wvalid_i      (tl_d_i.d_valid),
    .wready_o      (tl_d_o.d_ready),
    .wdata_i       ({tl_d_i.d_opcode,
                     tl_d_i.d_param ,
                     tl_d_i.d_size  ,
                     tl_d_i.d_source,
                     tl_d_i.d_sink  ,
                     (tl_d_i.d_opcode == tlul_pkg::AccessAckData) ? tl_d_i.d_data :
                                                                    {top_pkg::TL_DW{1'b0}} ,
                     tl_d_i.d_user  ,
                     tl_d_i.d_error ,
                     spare_rsp_i}),
    .depth_o       (rsp_depth_o),
    .rvalid_o      (tl_h_o.d_valid),
    .rready_i      (tl_h_i.d_ready),
    .rdata_o       ({tl_h_o.d_opcode,
                     tl_h_o.d_param ,
                     tl_h_o.d_size  ,
                     tl_h_o.d_source,
                     tl_h_o.d_sink  ,
                     tl_h_o.d_data  ,
                     tl_h_o.d_user  ,
                     tl_h_o.d_error ,
                     spare_rsp_o}));
endmodule
 | 
| 
	// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       top_pkg.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     OpenTitan top_pkg customized for the Common 
//                  Evaluation Plafform
// Notes:           
//************************************************************************
package top_pkg;
// In the OpenTitan world, TL buses are encapstulated with the structures instantitated above
// and as defined in top_pkg.sv.  This includes field widths.
//
// In the RocketChip world, field widths will vary based on the other system components
// (e.g., source and sink widths).  In order to provide maximum flexibility, without breaking
// OpenTitan, top_pkg.sv is going to be defined with field widths of the maximum expected
// size.  Then the following generate statements, coupled with the parameters passed to 
// this component will provide for a flexible assignment, when necessary
localparam int TL_DW 	= 64;	// = TL_DBW * 8; TL_DBW must be a power-of-two
localparam int TL_AW 	= 32;
localparam int TL_AIW 	= 10;   // a_source, d_source
localparam int TL_DIW 	= 2;    // d_sink
localparam int TL_SZW   = 4;	// a_size, d_size
localparam int TL_DUW 									= 16;   // d_user (unused in the CEP)
localparam int TL_DBW 									= (TL_DW>>3);
localparam int FLASH_BANKS          					= 2;
localparam int FLASH_PAGES_PER_BANK						= 256;
localparam int FLASH_WORDS_PER_PAGE 					= 128;
localparam int FLASH_INFO_TYPES  						= 2;
localparam int FLASH_INFO_PER_BANK [FLASH_INFO_TYPES] 	= '{4, 4};
localparam int FLASH_DATA_WIDTH 						= 64;
localparam int FLASH_METADATA_WIDTH 					= 12;
localparam int NUM_AST_ALERTS 							= 7;
localparam int NUM_IO_RAILS 							= 2;
localparam int ENTROPY_STREAM 							= 4;
localparam int ADC_CHANNELS 							= 2;
localparam int ADC_DATAW 								= 10;
endpackage
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      md5.v
// Program:        Common Evaluation Platform (CEP)
// Description:    MD5 wrapper
// Notes:          The actual core expects input in LE format and output 
//                 is already in BE format. 
//                 This module is to make the inout/output conform to 
//                 BigEndian format (standardized from CEP perspective)
//
//************************************************************************
module md5
  (
   input 	  clk, // input clock
   input 	  rst, // global rst
   input          init,  // clear internal states to start a new transaction   
   input [511:0]  msg_padded, // input message, already padded
   input 	  msg_in_valid, // next transaction with current encryption
   
   output [127:0] msg_output, // output message, always 128 bit wide
   output 	  msg_out_valid, // if asserted, output message is valid
   output 	  ready                    // the core is ready for an input message
   );
   
   pancham md5_core
     (
      .msg_padded   ({xEndian(msg_padded[(0*64)+63: (0*64)]),
		      xEndian(msg_padded[(1*64)+63: (1*64)]),
		      xEndian(msg_padded[(2*64)+63: (2*64)]),
		      xEndian(msg_padded[(3*64)+63: (3*64)]),
		      xEndian(msg_padded[(4*64)+63: (4*64)]),
		      xEndian(msg_padded[(5*64)+63: (5*64)]),
		      xEndian(msg_padded[(6*64)+63: (6*64)]),
		      xEndian(msg_padded[(7*64)+63: (7*64)])}),		   
      // output already math the endian
      .msg_output    (msg_output),
      .clk           (clk),
      .rst           (rst),
      .init          (init ),
      .msg_in_valid  (msg_in_valid),
      .msg_out_valid (msg_out_valid), 
      .ready         (ready)
      );
   
   function [63:0] xEndian;
      input [63:0] inDat;
      begin
	 xEndian = {inDat[(0*8)+7:(0*8)],
		    inDat[(1*8)+7:(1*8)],
		    inDat[(2*8)+7:(2*8)],
		    inDat[(3*8)+7:(3*8)],
		    inDat[(4*8)+7:(4*8)],
		    inDat[(5*8)+7:(5*8)],
		    inDat[(6*8)+7:(6*8)],
		    inDat[(7*8)+7:(7*8)]};
      end
   endfunction
  
endmodule // md5
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       md5_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module md5_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    // Core I/O
    input wire            init,
    input wire            msg_in_valid,
    input wire [511 : 0]  msg_padded,
    output wire [127 : 0] msg_output,
    output wire           msg_out_valid,
    output wire           ready,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = MD5_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [(64*KEY_WORDS) - 1:0]   mock_tss_msg_padded;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  genvar i;
  generate
    for (i = 0; i < KEY_WORDS; i = i + 1) begin
      assign mock_tss_msg_padded[64*i +: 64] = MD5_MOCK_TSS_KEY_WORDS[i] ^
                                          llkid_key_register[64*i +: 64] ^
                                          msg_padded[64*i +: 64];
    end
  endgenerate
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  md5 md5_inst (
    .clk            (clk),
    .rst            (rst),
    .init           (init),
    .msg_padded     (mock_tss_msg_padded),
    .msg_in_valid   (msg_in_valid),
    .msg_output     (msg_output),
    .msg_out_valid  (msg_out_valid),
    .ready          (ready)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	/*****************************************************************
 Pancham is an MD5 compliant IP core for cryptographic 
 applications. 
 Copyright (C) 2003  Swapnajit Mittra, Project VeriPage
 (Contact email: verilog_tutorial at hotmail.com
  Website      : http://www.angelfire.com/ca/verilog)
 
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.
 
 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the 
 
 Free Software Foundation, Inc.
 59 Temple Place, Suite 330
 Boston, MA  02111-1307 
 USA
 ******************************************************************/
/*
 * This is the main module that computes a 128-bit message 
 * digest from a maximum of 512-bit long input message using
 * MD5 algorithm.
 *
 * Modified by Matthew Hicks ([email protected])
 *   Input from 128-bit to 512-bit
 *   Hold valid outputs
 *   Carry over constants between encryptions
 *   Support for arbitrary size encryption
 *   Address some Verilator warnings
 *   Convert vector direction
 *
 */
// ROUNDs
`define ROUND1 2'b00
`define ROUND2 2'b01
`define ROUND3 2'b10
`define ROUND4 2'b11
// T_i = 4294967296*abs(sin(i))
`define T_1  32'hd76aa478
`define T_2  32'he8c7b756
`define T_3  32'h242070db
`define T_4  32'hc1bdceee
`define T_5  32'hf57c0faf
`define T_6  32'h4787c62a
`define T_7  32'ha8304613
`define T_8  32'hfd469501
`define T_9  32'h698098d8
`define T_10 32'h8b44f7af
`define T_11 32'hffff5bb1
`define T_12 32'h895cd7be
`define T_13 32'h6b901122
`define T_14 32'hfd987193
`define T_15 32'ha679438e
`define T_16 32'h49b40821
`define T_17 32'hf61e2562
`define T_18 32'hc040b340
`define T_19 32'h265e5a51
`define T_20 32'he9b6c7aa
`define T_21 32'hd62f105d
`define T_22  32'h2441453
`define T_23 32'hd8a1e681
`define T_24 32'he7d3fbc8
`define T_25 32'h21e1cde6
`define T_26 32'hc33707d6
`define T_27 32'hf4d50d87
`define T_28 32'h455a14ed
`define T_29 32'ha9e3e905
`define T_30 32'hfcefa3f8
`define T_31 32'h676f02d9
`define T_32 32'h8d2a4c8a
`define T_33 32'hfffa3942
`define T_34 32'h8771f681
`define T_35 32'h6d9d6122
`define T_36 32'hfde5380c
`define T_37 32'ha4beea44
`define T_38 32'h4bdecfa9
`define T_39 32'hf6bb4b60
`define T_40 32'hbebfbc70
`define T_41 32'h289b7ec6
`define T_42 32'heaa127fa
`define T_43 32'hd4ef3085
`define T_44  32'h4881d05
`define T_45 32'hd9d4d039
`define T_46 32'he6db99e5
`define T_47 32'h1fa27cf8
`define T_48 32'hc4ac5665
`define T_49 32'hf4292244
`define T_50 32'h432aff97
`define T_51 32'hab9423a7
`define T_52 32'hfc93a039
`define T_53 32'h655b59c3
`define T_54 32'h8f0ccc92
`define T_55 32'hffeff47d
`define T_56 32'h85845dd1
`define T_57 32'h6fa87e4f
`define T_58 32'hfe2ce6e0
`define T_59 32'ha3014314
`define T_60 32'h4e0811a1
`define T_61 32'hf7537e82
`define T_62 32'hbd3af235
`define T_63 32'h2ad7d2bb
`define T_64 32'heb86d391
/* verilator lint_off UNOPTFLAT */
module pancham (
           clk
           , rst
           , init     // Tony D. 05/12/20: to remove reset dependency		
           , msg_padded
           , msg_in_valid
           , msg_output
           , msg_out_valid
           , ready
       );
//--------------------------------
//
// Input/Output declarations
//
//--------------------------------
   input          clk;                      // input clock
   input 	  rst;                    // global rst
   input 	  init;   // clear internal state for new encryption                    
   input [511:0]  msg_padded;               // input message, already padded
   input          msg_in_valid;             // input message is valid, active high
   
   output [127:0] msg_output;               // output message, always 128 bit wide
   output         msg_out_valid;            // if asserted, output message is valid
   output         ready;                    // the core is ready for an input message
//--------------------------------
//
// Variable declarations
//
//--------------------------------
// inputs
wire          clk;
wire          rst;
wire  [511:0] msg_padded;
wire          msg_in_valid;
reg          msg_in_valid_reg;
wire         msg_in_valid_pos_edge;
// output
wire  [127:0] msg_output;
reg           msg_out_valid;
wire          ready;
// scratch pads
reg    [1:0] round;
reg   [31:0] a;
reg   [31:0] A;
reg   [31:0] AA;
reg   [31:0] next_A;
reg   [31:0] b;
reg   [31:0] B;
reg   [31:0] BB;
reg   [31:0] next_B;
reg   [31:0] c;
reg   [31:0] C;
reg   [31:0] CC;
reg   [31:0] next_C;
reg   [31:0] d;
reg   [31:0] D;
reg   [31:0] DD;
reg   [31:0] next_D;
reg   [31:0] m;
reg   [31:0] s;
reg   [31:0] t;
reg    [3:0] phase;         // Counter to determine 16 phases within each round.
wire  [31:0] next_a;
reg    [7:0] current_state;
reg    [7:0] next_state;
reg [8*11:1] ascii_state;
//--------------------------------
//
// Parameter definitions
//
//--------------------------------
parameter SALT_A         = 32'h67452301;
parameter SALT_B         = 32'hefcdab89;
parameter SALT_C         = 32'h98badcfe;
parameter SALT_D         = 32'h10325476;
parameter ONE            = 72'h1;
parameter IDLE_BIT       = 0;
parameter IDLE           = ONE << IDLE_BIT;
parameter ROUND1_BIT     = 1;
parameter ROUND1         = ONE << ROUND1_BIT;
parameter ROUND2_BIT     = 2;
parameter ROUND2         = ONE << ROUND2_BIT;
parameter ROUND3_BIT     = 3;
parameter ROUND3         = ONE << ROUND3_BIT;
parameter ROUND4_BIT     = 4;
parameter ROUND4         = ONE << ROUND4_BIT;
parameter FINISH_OFF_BIT = 5;
parameter FINISH_OFF     = ONE << FINISH_OFF_BIT;
parameter TURN_ARND_BIT  = 6;
parameter TURN_ARND      = ONE << TURN_ARND_BIT;
//--------------------------------
//
// Submodule instantiation
//
//--------------------------------
pancham_round ROUND (
                  .a      (a    )
                  , .b      (b    )
                  , .c      (c    )
                  , .d      (d    )
                  , .m      (m    )
                  , .s      (s    )
                  , .t      (t    )
                  , .round  (round)
                  , .next_a (next_a)
              );
wire [31:0] m0 = msg_padded[31:0];
wire [31:0] m1 = msg_padded[63:32];
wire [31:0] m2 = msg_padded[95:64];
wire [31:0] m3 = msg_padded[127:96];
wire [31:0] m4 = msg_padded[159:128];
wire [31:0] m5 = msg_padded[191:160];
wire [31:0] m6 = msg_padded[223:192];
wire [31:0] m7 = msg_padded[255:224];
wire [31:0] m8 = msg_padded[287:256];
wire [31:0] m9 = msg_padded[319:288];
wire [31:0] m10 = msg_padded[351:320];
wire [31:0] m11 = msg_padded[383:352];
wire [31:0] m12 = msg_padded[415:384];
wire [31:0] m13 = msg_padded[447:416];
wire [31:0] m14 = msg_padded[479:448];
wire [31:0] m15 = msg_padded[511:480];
always @ (posedge (clk))begin
    msg_in_valid_reg <= msg_in_valid;
end
assign msg_in_valid_pos_edge = msg_in_valid & ~msg_in_valid_reg;
//--------------------------------
//
// Actual code starts here
//
//--------------------------------
always @(current_state
             or    msg_in_valid_pos_edge
             or    A
             or    B
             or    C
             or    D
             or    phase
             or    msg_padded
             or    next_a
             or    AA
             or    BB
             or    CC
             or    DD
            )
    begin // {
        round = `ROUND1;
        next_A = A;
        next_B = B;
        next_C = C;
        next_D = D;
        a = 32'h0;
        b = 32'h0;
        c = 32'h0;
        d = 32'h0;
        m = 32'h0;
        s = 32'h0;
        t = 32'h0;
        next_state = current_state;
        case (1'b1) // synopsys full_case parallel_case
            current_state[IDLE_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "IDLE";
                    // synopsys translate_on
                    if (msg_in_valid_pos_edge)
                        next_state = ROUND1[7:0];
                end // }
            //----------------------------------------------------------------
            //--------------------------- ROUND 1 ----------------------------
            //----------------------------------------------------------------
            current_state[ROUND1_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "ROUND1";
                    // synopsys translate_on
                    round = `ROUND1;
                    case (phase)
                        4'b0000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m0;
                                s=32'd07;
                                t= `T_1;
                                next_A=next_a;
                            end
                        4'b0001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m1;
                                s=32'd12;
                                t= `T_2;
                                next_D=next_a;
                            end
                        4'b0010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m2;
                                s=32'd17;
                                t= `T_3;
                                next_C=next_a;
                            end
                        4'b0011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m3;
                                s=32'd22;
                                t= `T_4;
                                next_B=next_a;
                            end
                        4'b0100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m4;
                                s=32'd07;
                                t= `T_5;
                                next_A=next_a;
                            end
                        4'b0101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m5;
                                s=32'd12;
                                t= `T_6;
                                next_D=next_a;
                            end
                        4'b0110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m6;
                                s=32'd17;
                                t= `T_7;
                                next_C=next_a;
                            end
                        4'b0111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m7;
                                s=32'd22;
                                t= `T_8;
                                next_B=next_a;
                            end
                        4'b1000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m8;
                                s=32'd07;
                                t= `T_9;
                                next_A=next_a;
                            end
                        4'b1001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m9;
                                s=32'd12;
                                t=`T_10;
                                next_D=next_a;
                            end
                        4'b1010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m10;
                                s=32'd17;
                                t=`T_11;
                                next_C=next_a;
                            end
                        4'b1011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m11;
                                s=32'd22;
                                t=`T_12;
                                next_B=next_a;
                            end
                        4'b1100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m12;
                                s=32'd7;
                                t=`T_13;
                                next_A=next_a;
                            end
                        4'b1101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m13;
                                s=32'd12;
                                t=`T_14;
                                next_D=next_a;
                            end
                        4'b1110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m14;
                                s=32'd17;
                                t=`T_15;
                                next_C=next_a;
                            end
                        4'b1111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m15;
                                s=32'd22;
                                t=`T_16;
                                next_B=next_a;
                            end
                    endcase
                    if (phase == 4'b1111)
                        next_state = ROUND2[7:0];
                end // }
            //----------------------------------------------------------------
            //--------------------------- ROUND 2 ----------------------------
            //----------------------------------------------------------------
            current_state[ROUND2_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "ROUND2";
                    // synopsys translate_on
                    round = `ROUND2;
                    case (phase)
                        4'b0000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m1;
                                s=32'd05;
                                t=`T_17;
                                next_A=next_a;
                            end
                        4'b0001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m6;
                                s=32'd09;
                                t=`T_18;
                                next_D=next_a;
                            end
                        4'b0010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m11;
                                s=32'd14;
                                t=`T_19;
                                next_C=next_a;
                            end
                        4'b0011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m0;
                                s=32'd20;
                                t=`T_20;
                                next_B=next_a;
                            end
                        4'b0100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m5;
                                s=32'd05;
                                t=`T_21;
                                next_A=next_a;
                            end
                        4'b0101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m10;
                                s=32'd09;
                                t=`T_22;
                                next_D=next_a;
                            end
                        4'b0110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m15;
                                s=32'd14;
                                t=`T_23;
                                next_C=next_a;
                            end
                        4'b0111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m4;
                                s=32'd20;
                                t=`T_24;
                                next_B=next_a;
                            end
                        4'b1000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m9;
                                s=32'd05;
                                t=`T_25;
                                next_A=next_a;
                            end
                        4'b1001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m14;
                                s=32'd9;
                                t=`T_26;
                                next_D=next_a;
                            end
                        4'b1010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m3;
                                s=32'd14;
                                t=`T_27;
                                next_C=next_a;
                            end
                        4'b1011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m8;
                                s=32'd20;
                                t=`T_28;
                                next_B=next_a;
                            end
                        4'b1100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m13;
                                s=32'd05;
                                t=`T_29;
                                next_A=next_a;
                            end
                        4'b1101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m2;
                                s=32'd09;
                                t=`T_30;
                                next_D=next_a;
                            end
                        4'b1110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m7;
                                s=32'd14;
                                t=`T_31;
                                next_C=next_a;
                            end
                        4'b1111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m12;
                                s=32'd20;
                                t=`T_32;
                                next_B=next_a;
                            end
                    endcase
                    if (phase == 4'b1111)
                        next_state = ROUND3[7:0];
                end // }
            //----------------------------------------------------------------
            //--------------------------- ROUND 3 ----------------------------
            //----------------------------------------------------------------
            current_state[ROUND3_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "ROUND3";
                    // synopsys translate_on
                    round = `ROUND3;
                    case (phase)
                        4'b0000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m5;
                                s=32'd04;
                                t=`T_33;
                                next_A=next_a;
                            end
                        4'b0001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m8;
                                s=32'd11;
                                t=`T_34;
                                next_D=next_a;
                            end
                        4'b0010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m11;
                                s=32'd16;
                                t=`T_35;
                                next_C=next_a;
                            end
                        4'b0011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m14;
                                s=32'd23;
                                t=`T_36;
                                next_B=next_a;
                            end
                        4'b0100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m1;
                                s=32'd04;
                                t=`T_37;
                                next_A=next_a;
                            end
                        4'b0101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m4;
                                s=32'd11;
                                t=`T_38;
                                next_D=next_a;
                            end
                        4'b0110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m7;
                                s=32'd16;
                                t=`T_39;
                                next_C=next_a;
                            end
                        4'b0111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m10;
                                s=32'd23;
                                t=`T_40;
                                next_B=next_a;
                            end
                        4'b1000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m13;
                                s=32'd04;
                                t=`T_41;
                                next_A=next_a;
                            end
                        4'b1001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m0;
                                s=32'd11;
                                t=`T_42;
                                next_D=next_a;
                            end
                        4'b1010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m3;
                                s=32'd16;
                                t=`T_43;
                                next_C=next_a;
                            end
                        4'b1011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m6;
                                s=32'd23;
                                t=`T_44;
                                next_B=next_a;
                            end
                        4'b1100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m9;
                                s=32'd04;
                                t=`T_45;
                                next_A=next_a;
                            end
                        4'b1101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m12;
                                s=32'd11;
                                t=`T_46;
                                next_D=next_a;
                            end
                        4'b1110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m15;
                                s=32'd16;
                                t=`T_47;
                                next_C=next_a;
                            end
                        4'b1111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m2;
                                s=32'd23;
                                t=`T_48;
                                next_B=next_a;
                            end
                    endcase
                    if (phase == 4'b1111)
                        next_state = ROUND4[7:0];
                end // }
            //----------------------------------------------------------------
            //--------------------------- ROUND 4 ----------------------------
            //----------------------------------------------------------------
            current_state[ROUND4_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "ROUND4";
                    // synopsys translate_on
                    round = `ROUND4;
                    case (phase)
                        4'b0000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m0;
                                s=32'd06;
                                t=`T_49;
                                next_A=next_a;
                            end
                        4'b0001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m7;
                                s=32'd10;
                                t=`T_50;
                                next_D=next_a;
                            end
                        4'b0010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m14;
                                s=32'd15;
                                t=`T_51;
                                next_C=next_a;
                            end
                        4'b0011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m5;
                                s=32'd21;
                                t=`T_52;
                                next_B=next_a;
                            end
                        4'b0100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m12;
                                s=32'd06;
                                t=`T_53;
                                next_A=next_a;
                            end
                        4'b0101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m3;
                                s=32'd10;
                                t=`T_54;
                                next_D=next_a;
                            end
                        4'b0110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m10;
                                s=32'd15;
                                t=`T_55;
                                next_C=next_a;
                            end
                        4'b0111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m1;
                                s=32'd21;
                                t=`T_56;
                                next_B=next_a;
                            end
                        4'b1000:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m8;
                                s=32'd06;
                                t=`T_57;
                                next_A=next_a;
                            end
                        4'b1001:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m15;
                                s=32'd10;
                                t=`T_58;
                                next_D=next_a;
                            end
                        4'b1010:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m6;
                                s=32'd15;
                                t=`T_59;
                                next_C=next_a;
                            end
                        4'b1011:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m13;
                                s=32'd21;
                                t=`T_60;
                                next_B=next_a;
                            end
                        4'b1100:
                            begin
                                a=A;
                                b=B;
                                c=C;
                                d=D;
                                m=m4;
                                s=32'd06;
                                t=`T_61;
                                next_A=next_a;
                            end
                        4'b1101:
                            begin
                                a=D;
                                b=A;
                                c=B;
                                d=C;
                                m=m11;
                                s=32'd10;
                                t=`T_62;
                                next_D=next_a;
                            end
                        4'b1110:
                            begin
                                a=C;
                                b=D;
                                c=A;
                                d=B;
                                m=m2;
                                s=32'd15;
                                t=`T_63;
                                next_C=next_a;
                            end
                        4'b1111:
                            begin
                                a=B;
                                b=C;
                                c=D;
                                d=A;
                                m=m9;
                                s=32'd21;
                                t=`T_64;
                                next_B=next_a;
                            end
                    endcase
                    if (phase == 4'b1111)
                        next_state = FINISH_OFF[7:0];
                end // }
            //----------------------------------------------------------------
            current_state[FINISH_OFF_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "FINISH_OFF";
                    // synopsys translate_on
                    next_A = AA + A;
                    next_B = BB + B;
                    next_C = CC + C;
                    next_D = DD + D;
                    next_state = TURN_ARND[7:0];
                end // }
            //----------------------------------------------------------------
            // One cycle for making the system to come to reset state
            current_state[TURN_ARND_BIT]:
                begin // {
                    // synopsys translate_off
                    ascii_state = "TURN_ARND";
                    // synopsys translate_on
                    next_state = IDLE[7:0];
                end // }
        endcase
    end // }
//--------------------------------
//
// Flops and other combinatorial
// logic definition
//
//--------------------------------
// Outputs
assign msg_output = {{A[7:0], A[15:8], A[23:16], A[31:24]}
                     ,{B[7:0], B[15:8], B[23:16], B[31:24]}
                     ,{C[7:0], C[15:8], C[23:16], C[31:24]}
                     ,{D[7:0], D[15:8], D[23:16], D[31:24]}};
always @(posedge clk)
    msg_out_valid <= current_state[FINISH_OFF_BIT];
assign ready = current_state[IDLE_BIT];
// Internal scratch pads
always @(posedge clk)
    if (next_state[ROUND1_BIT] && current_state[IDLE_BIT])
        begin // {
            AA <= A;
            BB <= B;
            CC <= C;
            DD <= D;
        end // }
// Initialize A, B, C and D and then compute them
always @(posedge clk)
    if (rst )
        begin // {
            A <= SALT_A;
            B <= SALT_B;
            C <= SALT_C;
            D <= SALT_D;
        end // }
    else if (init) begin // added 05/12/20
            A <= SALT_A;
            B <= SALT_B;
            C <= SALT_C;
            D <= SALT_D;       
    end
    else
        begin // {
            A <= next_A;
            B <= next_B;
            C <= next_C;
            D <= next_D;
        end // }
// Determine one of the 16 phases within each round
always @(posedge clk)
    if (rst)
        phase <= 4'b0;
    else if (init) // added 05/12/20
        phase <= 4'b0;      
    else if (next_state[ROUND1_BIT] && current_state[IDLE_BIT])
        phase <= 4'b0;
    else
        phase <= phase + 4'b1;
// Assign current_state based on rst and the next_state
always @(posedge clk)
    if (rst)
        current_state <= IDLE[7:0];
    else if (init)
        current_state <= IDLE[7:0];      
    else
        current_state <= next_state;
endmodule
 | 
| 
	/*****************************************************************
 Pancham is an MD5 compliant IP core for cryptographic applicati
 -ons. 
 Copyright (C) 2003  Swapnajit Mittra, Project VeriPage
 (Contact email: verilog_tutorial at hotmail.com
  Website      : http://www.angelfire.com/ca/verilog)
 
 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.
 
 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.
 
 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the 
 
 Free Software Foundation, Inc.
 59 Temple Place, Suite 330
 Boston, MA  02111-1307 
 USA
 ******************************************************************/
/*
 * pancham_round performs the rounds 1-4 of the MD5 algorithm 
 * described in RFC1321 for a 128-bit long input message. 
 * 
 * Inputs: [abcd m[k] s abs(sin(2*pi*t/64))] as described 
 *         in RFC1321.Also the round number (1-4).
 * 
 * Outputs: the modified 'a' value as describes in RFC1321
 *         on the left hand side of the round #n equation.
 * 
 */
`define ROUND1 2'b00
`define ROUND2 2'b01
`define ROUND3 2'b10
`define ROUND4 2'b11
module pancham_round (
           a
           , b
           , c
           , d
           , m
           , s
           , t
           , round
           , next_a
       );
input  [31:0] a;
input  [31:0] b;
input  [31:0] c;
input  [31:0] d;
input  [31:0] m;          // Note that for a 128-bit long input message, X[k] = M[k] = m
input  [31:0] s;
input  [31:0] t;          // t-th sample of abs(sin(i)), i = 1, 2, ..., 64
input   [1:0] round;      // round number (1-4).
output [31:0] next_a;
wire  [31:0] a;         //
wire  [31:0] b;
wire  [31:0] c;
wire  [31:0] d;
wire  [31:0] m;
wire  [31:0] s;
wire  [31:0] t;
wire   [1:0] round;
reg   [31:0] next_a;
reg   [31:0] add_result;
reg   [31:0] rotate_result1;
reg   [31:0] rotate_result2;
always @(a
             or    b
             or    c
             or    d
             or    m
             or    s
             or    t
             or    round)
    begin // {
        case (round)
            `ROUND1:
                begin // {
                    add_result = (a + F(b,c,d) + m + t);
                    rotate_result1 = add_result << s;
                    rotate_result2 = add_result >> (32-s);
                    next_a = b + (rotate_result1 | rotate_result2);
                end // }
            `ROUND2:
                begin // {
                    add_result = (a + G(b,c,d) + m + t);
                    rotate_result1 = add_result << s;
                    rotate_result2 = add_result >> (32-s);
                    next_a = b + (rotate_result1 | rotate_result2);
                end // }
            `ROUND3:
                begin // {
                    add_result = (a + H(b,c,d) + m + t);
                    rotate_result1 = add_result << s;
                    rotate_result2 = add_result >> (32-s);
                    next_a = b + (rotate_result1 | rotate_result2);
                end // }
            `ROUND4:
                begin // {
                    add_result = (a + I(b,c,d) + m + t);
                    rotate_result1 = add_result << s;
                    rotate_result2 = add_result >> (32-s);
                    next_a = b + (rotate_result1 | rotate_result2);
                end // }
        endcase
    end // }
//--------------------------------
//
// Function declarations
//
//--------------------------------
// Step 4 functions F, G, H and I
function [31:0] F;
    input [31:0] x, y, z;
    begin // {
        F = (x&y)|((~x)&z);
    end // }
endfunction // }
function [31:0] G;
    input [31:0] x, y, z;
    begin // {
        G = (x&z)|(y&(~z));
    end // }
endfunction
function [31:0] H;
    input [31:0] x, y, z;
    begin // {
        H = (x^y^z);
    end // }
endfunction
function [31:0] I;
    input [31:0] x, y, z;
    begin // {
        I = (y^(x|(~z)));
    end // }
endfunction
endmodule
 | 
| 
	--------------------
Exponent
--------------------
000000ff
255
--------------------
Modulus
--------------------
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095
--------------------
B -> Message
--------------------
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
115792089237316195423570985008687907853269984665640564039457584007913129639935
--------------------
Result
--------------------
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc000000000000000000000000000000000000000000000000000000000000000
3351951982485649274893506249551461531869841455148098344430890360930441007518357796178159245492869964176255792569658195217272060561976778090606433969111040
3351951982485649274893506249551461531869841455148098344430890360930441007518357796178159245492869964176255792569658195217272060561976778090606433969111040
3351951982485649274893506249551461531869841455148098344430890360930441007518357796178159245492869964176255792569658195217272060561976778090606433969111040
 | 
| 
	//------------------------------------------------------------------
// Simulator directives.
//------------------------------------------------------------------
`timescale 1ns/100ps
//------------------------------------------------------------------
// Test module.
//------------------------------------------------------------------
module tb_modexp();
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
// Debug output control.
parameter DEBUG                  = 0;
parameter VCD                    = 1;
// Clock defines.
localparam CLK_HALF_PERIOD       = 1;
localparam CLK_PERIOD            = 2 * CLK_HALF_PERIOD;
// Address defines
localparam OPERAND_WIDTH         = 32;
localparam ADDRESS_WIDTH         = 8;
localparam ADDR_NAME0            = 8'h00;
localparam ADDR_NAME1            = 8'h01;
localparam ADDR_VERSION          = 8'h02;
localparam ADDR_CTRL             = 8'h08;
localparam CTRL_INIT_BIT         = 0;
localparam CTRL_NEXT_BIT         = 1;
localparam ADDR_STATUS           = 8'h09;
localparam STATUS_READY_BIT      = 0;
localparam ADDR_CYCLES_HIGH      = 8'h10;
localparam ADDR_CYCLES_LOW       = 8'h11;
localparam ADDR_MODULUS_LENGTH   = 8'h20;
localparam ADDR_EXPONENT_LENGTH  = 8'h21;
localparam ADDR_MODULUS_PTR_RST  = 8'h30;
localparam ADDR_MODULUS_DATA     = 8'h31;
localparam ADDR_EXPONENT_PTR_RST = 8'h40;
localparam ADDR_EXPONENT_DATA    = 8'h41;
localparam ADDR_MESSAGE_PTR_RST  = 8'h50;
localparam ADDR_MESSAGE_DATA     = 8'h51;
localparam ADDR_RESULT_PTR_RST   = 8'h60;
localparam ADDR_RESULT_DATA      = 8'h61;
localparam DEFAULT_MODLENGTH     = 8'h80; // 2048 bits.
localparam DEFAULT_EXPLENGTH     = 8'h80;
localparam CORE_NAME0            = 32'h6d6f6465; // "mode"
localparam CORE_NAME1            = 32'h78702020; // "xp  "
localparam CORE_VERSION          = 32'h302e3532; // "0.52"
//----------------------------------------------------------------
// Register and Wire declarations.
//----------------------------------------------------------------
reg  [31 : 0] error_ctr;
reg  [31 : 0] tc_ctr;
reg [127 : 0] result_data;
reg           tb_clk;
reg           tb_reset_n;
reg           tb_cs;
reg           tb_we;
reg  [31 : 0] tb_address;
reg  [31 : 0] tb_write_data;
wire [31 : 0] tb_read_data;
wire          tb_error;
reg           tb_cyc;
reg  [3 : 0]  tb_sel;
wire          tb_ack;
wire          tb_err;
wire          tb_int;
reg  [31 : 0] pmsg [63 : 0];
reg  [31 : 0] cmsg [63 : 0];
reg  [31 : 0] gmsg [63 : 0];
integer f1;
//----------------------------------------------------------------
// Device Under Test.
//----------------------------------------------------------------
modexp dut(
           .clk(tb_clk),
           .reset_n(tb_reset_n),
           .cs(tb_cs),
           .we(tb_we),
           .address(tb_address[10:2]),
           .write_data(tb_write_data),
           .read_data(tb_read_data));
//----------------------------------------------------------------
// clk_gen
//
// Always running clock generator process.
//----------------------------------------------------------------
always
    begin : clk_gen
        #CLK_HALF_PERIOD;
        tb_clk = !tb_clk;
    end // clk_gen
//----------------------------------------------------------------
// reset_dut()
//
// Toggle reset to put the DUT into a well known state.
//----------------------------------------------------------------
task reset_dut();
    begin
        $display("*** Toggle reset.");
        tb_reset_n = 0;
        #(2 * CLK_PERIOD);
        tb_reset_n = 1;
        $display("");
    end
endtask // reset_dut
//----------------------------------------------------------------
// init_sim()
//
// Initialize all counters and testbed functionality as well
// as setting the DUT inputs to defined values.
//----------------------------------------------------------------
task init_sim();
    begin
        error_ctr          = 0;
        tc_ctr             = 0;
        tb_clk             = 0;
        tb_reset_n         = 1;
        tb_cs              = 0;
        tb_we              = 0;
        tb_address         = 32'h00000000;
        tb_write_data      = 32'h00000000;
    end
endtask // init_sim
//----------------------------------------------------------------
// read_word()
//
// Read a data word from the given address in the DUT.
//----------------------------------------------------------------
task read_word(input [7 : 0] address);
    begin
        tb_address = {22'b0,address,2'b0};
        tb_cs = 1;
        tb_we = 0;
        #(CLK_PERIOD);
        tb_cs = 0;
        if (DEBUG)
            begin
                $display("*** (read_word) Reading 0x%08x from 0x%02x.", tb_read_data, address);
                $display("");
            end
    end
endtask // read_word
//----------------------------------------------------------------
// write_word()
//
// Write the given word to the DUT using the DUT interface.
//----------------------------------------------------------------
task write_word(input [ 7 : 0] address,
                    input [31 : 0] word);
    begin
        if (DEBUG)
            begin
                $display("*** (write_word) Writing 0x%08x to 0x%02x.", word, address);
                $display("");
            end
        tb_address = {22'b0,address,2'b0};
        tb_write_data = word;
        tb_cs = 1;
        tb_we = 1;
        #(CLK_PERIOD);
        tb_cs = 0;
        tb_we = 0;
    end
endtask // write_word
//----------------------------------------------------------------
// wait_ready()
//
// Wait until the ready flag in the core is set.
//----------------------------------------------------------------
task wait_ready();
    begin
        while (tb_read_data != 32'h00000001)
            read_word(8'h09);
        if (DEBUG)
            $display("*** (wait_ready) Ready flag has been set.");
    end
endtask // wait_ready
//----------------------------------------------------------------
// assertEquals
//----------------------------------------------------------------
function assertEquals(
        input [31:0] expected,
        input [31:0] actual
    );
    begin
        if (expected === actual)
            begin
                assertEquals = 1; // success
            end
        else
            begin
                $display("*** Expected: 0x%08x, got 0x%08x", expected, actual);
                assertEquals = 0; // failure
            end
    end
endfunction // assertEquals
//----------------------------------------------------------------
// assertSuccess
//----------------------------------------------------------------
task assertSuccess(input success);
    begin
        if (success !== 1)
            begin
                $display("*** Test    -> FAILED");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** Test    -> passed");
    end
endtask // assertSuccess
//----------------------------------------------------------------
// display_test_results()
//
// Display the accumulated test results.
//----------------------------------------------------------------
task display_test_results();
    begin
        $display("");
        if (error_ctr == 0)
            begin
                $display("*** All %02d test cases completed successfully", tc_ctr);
            end
        else
            begin
                $display("*** %02d tests completed - %02d test cases did not complete successfully.",
                         tc_ctr, error_ctr);
            end
    end
endtask // display_test_results
//----------------------------------------------------------------
// exp32bit_mod2048bit_test();
//----------------------------------------------------------------
task exp32bit_mod2048bit_test();
    integer i;
    integer success;
    reg [31 : 0] read_data;
    reg  [31 : 0] exp  [63 : 0];
    reg  [31 : 0] mod  [63 : 0];
    reg  [31 : 0] msg  [63 : 0];
    reg  [31 : 0] res  [63 : 0];
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("");
        $display("Test with e = 65537 and 2048 bit modulus -- Encrypting");
        $readmemh("./gen/exp", exp);
        $readmemh("./gen/mod", mod);
        $readmemh("./gen/msg",  msg);
        $readmemh("./gen/res",  res);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , exp[0]);
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, mod[i]);
                if(DEBUG)
                    $display("writing: %d -> %h", i, mod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, msg[i]);
                if(DEBUG)
                    $display("Writing: %d -> %h", i, msg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        read_data=tb_read_data;
        success=success&assertEquals(32'h00000000, read_data);
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                read_data=tb_read_data;
                success=success&assertEquals(res[i], read_data);
                if(DEBUG)
                    $display("Reading: %d -> %h -> %h", i, res[i], read_data);
            end
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_2048bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_2048bit_modulus success.");
    end
endtask // e65537_2048bit_modulus
//----------------------------------------------------------------
// modexp_encrypt
//----------------------------------------------------------------
task modexp_encrypt();
    integer i;
    integer success;
    reg [31 : 0] pubexp [1];
    reg [31 : 0] pubmod [63 : 0];
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("");
        $display("Encrypting -- exp = 65537 and 2048 bit mod");
        $readmemh("./gen/pTextHEX", pmsg);
        $readmemh("./gen/exponent", pubexp);
        $readmemh("./gen/modulus",  pubmod);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , pubexp[0]);
        if(DEBUG)
            $display("Writing EXP: %d %h", pubexp[0], pubexp[0]);
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, pubmod[i]);
                if(DEBUG)
                    $display("Writing MOD: %d -> %h", i, pubmod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, pmsg[i]);
                if(DEBUG)
                    $display("Writing MSG: %d -> %h", i, pmsg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        cmsg[0]=tb_read_data;
        //success=success&assertEquals(32'h00000000, cmsg[0]);
        f1 = $fopen("./gen/cTextHEX", "w");
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                cmsg[i]=tb_read_data;
                if(DEBUG)
                    $display("Reading: %d -> %h ", i, cmsg[i]);
                $fwrite(f1, "%h\n",cmsg[i]);
            end
        $fclose(f1);
        assertSuccess(success);
    end
endtask // e65537_2048bit_modulus
//----------------------------------------------------------------
// modexp_decrypt
//----------------------------------------------------------------
task modexp_decrypt();
    integer i;
    integer success;
    reg [31 : 0] rdata;
    reg [31 : 0] read_data;
    reg [31 : 0] priexp [63 : 0];
    reg [31 : 0] primod [63 : 0];
    begin
        $display("");
        $display("*** Running -> modexp_decrypt()");
        $readmemh("./gen/priExponent", priexp);
        $readmemh("./gen/priModulus",  primod);
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Decrypting -- 2048 bit exp and 2048 bit mod");
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_EXPONENT_DATA, priexp[i]);
                if(DEBUG)
                    $display("Writing EXP: %d -> %h", i, priexp[i]);
            end
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, primod[i]);
                if(DEBUG)
                    $display("Writing MOD: %d -> %h", i, primod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, cmsg[i]);
                if(DEBUG)
                    $display("Writing MSG: %d -> %h", i, cmsg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000041);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        rdata=tb_read_data;
        success=success&assertEquals(32'h00000000, rdata);
        f1 = $fopen("./gen/gTextHEX", "w");
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                rdata=tb_read_data;
                if(DEBUG)
                    $display("Reading: %d -> %h ", i, rdata);
                $fwrite(f1, "%h\n",rdata);
                success=success&assertEquals(pmsg[i], rdata);
            end
        $fclose(f1);
        assertSuccess(success);
    end
endtask // e65537_2048bit_modulus
//----------------------------------------------------------------
// modexp_32bits
//----------------------------------------------------------------
task modexp_32bits(input [31:0] Wmsg,
                       input [31:0] Wexp,
                       input [31:0] Wmod,
                       input [31:0] Wres);
    reg [31 : 0] Rmsg;
    reg [31 : 0] Rexp;
    reg [31 : 0] Rmod;
    reg [31 : 0] Rres;
    integer success;
    begin
        $display("");
        $display("*** Running -> modexp_32bits()");
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("*** Writing -> MES: %h EXP: %h MOD: %h", Wmsg, Wexp, Wmod);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , Wexp);
        write_word(ADDR_MODULUS_PTR_RST , 32'h00000000);
        write_word(ADDR_MODULUS_DATA    , Wmod);
        write_word(ADDR_MESSAGE_PTR_RST , 32'h00000000);
        write_word(ADDR_MESSAGE_DATA    , Wmsg);
        write_word(ADDR_EXPONENT_LENGTH , 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH  , 32'h00000001);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL            , 32'h00000001);
        wait_ready();
        write_word(ADDR_MESSAGE_PTR_RST , 32'h00000000);
        read_word(ADDR_MESSAGE_DATA);
        Rmsg=tb_read_data;
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        read_word(ADDR_EXPONENT_DATA);
        Rexp=tb_read_data;
        write_word(ADDR_MODULUS_PTR_RST , 32'h00000000);
        read_word(ADDR_MODULUS_DATA);
        Rmod=tb_read_data;
        write_word(ADDR_RESULT_PTR_RST  , 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        Rres=tb_read_data;
        $display("*** Reading -> MES: %h EXP: %h MOD: %h RES: %h", Rmsg, Rexp, Rmod, Rres);
        success=success&assertEquals(Wres, Rres);
        assertSuccess(success);
    end
endtask // e65537_2048bit_modulus
//----------------------------------------------------------------
// main
//
// The main test functionality.
//----------------------------------------------------------------
initial
    begin : main
        if(VCD)
            begin
                $dumpfile("./iverilog/tb_modexp.vcd");
                $dumpvars(0,tb_modexp);
                //$dumpvars(1,tb_clk, tb_reset_n, tb_cs, tb_we, tb_address, tb_write_data, tb_read_data);
            end
        $display("   -= Testbench for modexp started =-");
        $display("    =================================");
        $display("");
        init_sim();
        reset_dut();
        modexp_32bits(32'h00000001, 32'h00000002, 32'h00000005, 32'h00000001); //msg^exp < mod -> 1^2 < 5
        modexp_32bits(32'h00000001, 32'h00000002, 32'h00000003, 32'h00000001); //msg^exp < mod -> 1^2 < 3
        modexp_32bits(32'h00000002, 32'h00000002, 32'h00000005, 32'h00000004); //msg^exp < mod -> 2^2 < 5
        modexp_32bits(32'h00000002, 32'h00000002, 32'h00000003, 32'h00000001); //msg^exp > mod -> 2^2 > 3
        modexp_32bits(32'h00000004, 32'h0000000D, 32'h000001F1, 32'h000001bd); //msg^exp > mod -> 4^13 > 497
        modexp_32bits(32'h01234567, 32'h89ABCDEF, 32'h11111111, 32'h0D9EF081); //msg^exp > mod -> 19088743^2309737967 > 286331153
        modexp_32bits(32'h30000000, 32'hC0000000, 32'h00A00001, 32'h0000CC3F); //msg^exp > mod -> 805306368^3221225472 > 10485761 <- Passes
        //modexp_32bits(32'h30000000, 32'hC0000000, 32'h00A00000, 32'h00600000); //msg^exp > mod -> 805306368^3221225472 > 10485760 <- Fails
        //modexp_32bits(32'h00000002, 32'h00000003, 32'h00000001, 32'h00000000); //mod 1 <- FAILS Does not check
        /*
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000002, 32'h00000001); //1 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000003, 32'h00000001); //1 mod 3 = 1 -> 1 <- passes
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000004, 32'h00000001); //1 mod 4 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000005, 32'h00000001); //1 mod 5 = 1 -> 1 <- passes
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000006, 32'h00000001); //1 mod 6 = 1 -> 4 <- FAILS
            
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000002, 32'h00000000); //2 mod 2 = 0 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000003, 32'h00000002); //2 mod 3 = 2 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000004, 32'h00000002); //2 mod 4 = 2 -> 0 <- FAILS
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000005, 32'h00000002); //2 mod 5 = 2 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000006, 32'h00000002); //2 mod 6 = 2 -> passes
            
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000002, 32'h00000001); //3 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000003, 32'h00000000); //3 mod 3 = 0 -> 3 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000004, 32'h00000003); //3 mod 4 = 3 -> 0 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000005, 32'h00000003); //3 mod 5 = 3 -> passes
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000006, 32'h00000003); //3 mod 6 = 3 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000002, 32'h00000000); //4 mod 2 = 0 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000003, 32'h00000001); //4 mod 3 = 1 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000004, 32'h00000000); //4 mod 4 = 0 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000005, 32'h00000004); //4 mod 5 = 4 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000006, 32'h00000004); //4 mod 6 = 4 -> passes
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000002, 32'h00000001); //5 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000003, 32'h00000002); //5 mod 3 = 2 -> passes
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000004, 32'h00000001); //5 mod 4 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000005, 32'h00000000); //5 mod 5 = 0 -> 5 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000006, 32'h00000005); //5 mod 6 = 5 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000002, 32'h00000000); //6 mod 2 = 0 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000003, 32'h00000000); //6 mod 3 = 0 -> 3 <- FAILS
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000004, 32'h00000002); //6 mod 4 = 2 -> 0 <- FAILS
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000005, 32'h00000001); //6 mod 5 = 1 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000006, 32'h00000000); //6 mod 6 = 0 -> 1 <- FAILS
        */
        /*
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000002, 32'h00000000); //8^6 mod 2 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000003, 32'h00000001); //8^6 mod 3 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000004, 32'h00000000); //8^6 mod 4 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000005, 32'h00000004); //8^6 mod 5 = 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000006, 32'h00000004); //8^6 mod 6 = 4 -> 1 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000007, 32'h00000001); //8^6 mod 7 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000008, 32'h00000000); //8^6 mod 8 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000009, 32'h00000001); //8^6 mod 9 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000A, 32'h00000004); //8^6 mod 10= 4 -> 9 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000B, 32'h00000003); //8^6 mod 11= 3 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000C, 32'h00000004); //8^6 mod 12= 4 -> 5 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000D, 32'h0000000C); //8^6 mod 13= 12-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000E, 32'h00000008); //8^6 mod 14= 8 -> 5 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000F, 32'h00000004); //8^6 mod 15= 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000010, 32'h00000000); //8^6 mod 16= 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000011, 32'h00000004); //8^6 mod 17= 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000012, 32'h0000000A); //8^6 mod 18= 10-> 13<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000013, 32'h00000001); //8^6 mod 19= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000014, 32'h00000004); //8^6 mod 20= 4 -> 11<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000015, 32'h00000001); //8^6 mod 21= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000016, 32'h0000000E); //8^6 mod 22= 14-> 1 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000017, 32'h0000000D); //8^6 mod 23= 13-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000018, 32'h00000010); //8^6 mod 24= 16-> 9 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000019, 32'h00000013); //8^6 mod 25= 19-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001A, 32'h0000000C); //8^6 mod 26= 12-> 19<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001B, 32'h00000001); //8^6 mod 27= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001C, 32'h00000008); //8^6 mod 28= 8 -> 19<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001D, 32'h0000000D); //8^6 mod 29= 13-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001E, 32'h00000004); //8^6 mod 30= 4 -> 13<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001F, 32'h00000008); //8^6 mod 31= 8 -> passes
        */
        //exp32bit_mod2048bit_test();
        //modexp_encrypt();
        //modexp_decrypt();
        display_test_results();
        $display("");
        $display("*** modexp simulation done. ***");
        $finish;
    end // main
endmodule // tb_modexp
          //======================================================================
          // EOF tb_modexp.v
          //======================================================================
 | 
| 
	//======================================================================
//
// tb_modexp.v
// -----------
// Testbench modular exponentiation core.
//
//
// Author: Joachim Strombergson, Peter Magnusson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
//------------------------------------------------------------------
// Simulator directives.
//------------------------------------------------------------------
`timescale 1ns/100ps
//------------------------------------------------------------------
// Test module.
//------------------------------------------------------------------
module tb_modexp();
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
// Debug output control.
parameter DEBUG               = 0;
parameter DEBUG_EI            = 0;
parameter DEBUG_RESULT        = 0;
parameter DISPLAY_TEST_CYCLES = 1;
// Clock defines.
localparam CLK_HALF_PERIOD = 1;
localparam CLK_PERIOD      = 2 * CLK_HALF_PERIOD;
// The DUT address map.
localparam GENERAL_PREFIX        = 4'h0;
localparam ADDR_NAME0            = 8'h00;
localparam ADDR_NAME1            = 8'h01;
localparam ADDR_VERSION          = 8'h02;
localparam ADDR_CTRL             = 8'h08;
localparam CTRL_START_BIT        = 0;
localparam ADDR_STATUS           = 8'h09;
localparam STATUS_READY_BIT      = 0;
localparam ADDR_MODULUS_LENGTH   = 8'h20;
localparam ADDR_EXPONENT_LENGTH  = 8'h21;
localparam ADDR_LENGTH           = 8'h22;
localparam ADDR_MODULUS_PTR_RST  = 8'h30;
localparam ADDR_MODULUS_DATA     = 8'h31;
localparam ADDR_EXPONENT_PTR_RST = 8'h40;
localparam ADDR_EXPONENT_DATA    = 8'h41;
localparam ADDR_MESSAGE_PTR_RST  = 8'h50;
localparam ADDR_MESSAGE_DATA     = 8'h51;
localparam ADDR_RESULT_PTR_RST   = 8'h60;
localparam ADDR_RESULT_DATA      = 8'h61;
//----------------------------------------------------------------
// Register and Wire declarations.
//----------------------------------------------------------------
reg [31 : 0]  test_cycle_ctr;
reg           test_cycle_ctr_rst;
reg           test_cycle_ctr_inc;
reg [31 : 0]  cycle_ctr;
reg [31 : 0]  error_ctr;
reg [31 : 0]  tc_ctr;
reg [31 : 0]  read_data;
reg [127 : 0] result_data;
reg           tb_clk;
reg           tb_reset_n;
reg           tb_cs;
reg           tb_we;
reg [11  : 0] tb_address;
reg [31 : 0]  tb_write_data;
wire [31 : 0] tb_read_data;
wire          tb_error;
//----------------------------------------------------------------
// Device Under Test.
//----------------------------------------------------------------
modexp dut(
           .clk(tb_clk),
           .reset_n(tb_reset_n),
           .cs(tb_cs),
           .we(tb_we),
           .address(tb_address),
           .write_data(tb_write_data),
           .read_data(tb_read_data)
       );
//----------------------------------------------------------------
// clk_gen
//
// Always running clock generator process.
//----------------------------------------------------------------
always
    begin : clk_gen
        #CLK_HALF_PERIOD;
        tb_clk = !tb_clk;
    end // clk_gen
//----------------------------------------------------------------
// sys_monitor()
//
// An always running process that creates a cycle counter and
// conditionally displays information about the DUT.
//----------------------------------------------------------------
always
    begin : sys_monitor
        cycle_ctr = cycle_ctr + 1;
        #(CLK_PERIOD);
        if (DEBUG)
            begin
                dump_dut_state();
            end
    end
//----------------------------------------------------------------
// test_cycle_counter
//
// Used to measure the number of cycles it takes to perform
// a given test case.
//----------------------------------------------------------------
always @ (posedge tb_clk)
    begin
        if (test_cycle_ctr_rst)
            test_cycle_ctr = 64'h0000000000000000;
        if (test_cycle_ctr_inc)
            test_cycle_ctr = test_cycle_ctr + 1;
    end
//----------------------------------------------------------------
// start_test_cycle_ctr
//
// Reset and start the test cycle counter.
//----------------------------------------------------------------
task start_test_cycle_ctr();
    begin
        test_cycle_ctr_rst = 1;
        #(CLK_PERIOD);
        test_cycle_ctr_rst = 0;
        test_cycle_ctr_inc = 1;
    end
endtask // start_test_cycle_ctr()
//----------------------------------------------------------------
// stop_test_cycle_ctr()
//
// Stop the test cycle counter and optionally display the
// result.
//----------------------------------------------------------------
task stop_test_cycle_ctr();
    begin
        test_cycle_ctr_inc = 0;
        #(CLK_PERIOD);
        if (DISPLAY_TEST_CYCLES)
            $display("*** Number of cycles performed during test: 0x%016x", test_cycle_ctr);
    end
endtask // stop_test_cycle_ctr()
//----------------------------------------------------------------
// ei_monitor()
//
// Displays ei_new, the most important variable for determining
// what modexp will do (i.e. should Z=MONTPROD( Z, P, M) be
// performed
//----------------------------------------------------------------
always @*
    begin : ei_monitor
        if (DEBUG_EI)
            if (dut.modexp_ctrl_reg == dut.CTRL_ITERATE_Z_P)
                $display("loop counter %d: ei = %d", dut.loop_counter_reg, dut.ei_reg);
    end
//----------------------------------------------------------------
// z_monitor()
//
// Displays the contents of the result_mem.
//----------------------------------------------------------------
always @*
    begin : result_monitor
        if (DEBUG_RESULT)
            $display("result_mem[0][1] = %x %x",dut.result_mem.mem[0],dut.result_mem.mem[1]);
    end
//----------------------------------------------------------------
// dump_dut_state()
//
// Dump the state of the dump when needed.
//----------------------------------------------------------------
task dump_dut_state();
    begin
        $display("cycle: 0x%016x", cycle_ctr);
        $display("State of DUT");
        $display("------------");
        $display("Inputs and outputs:");
        $display("cs   = 0x%01x, we = 0x%01x", tb_cs, tb_we);
        $display("addr = 0x%08x, read_data = 0x%08x, write_data = 0x%08x",
                 tb_address, tb_read_data, tb_write_data);
        $display("");
        $display("State:");
        $display("ready_reg = 0x%01x, start_reg = 0x%01x, start_new = 0x%01x",
                 dut.core_inst.ready_reg, dut.start_reg, dut.start_new);
        $display("residue_valid = 0x%01x", dut.core_inst.residue_valid_reg);
        $display("loop_counter_reg = 0x%08x", dut.core_inst.loop_counter_reg);
        $display("exponent_length_reg = 0x%02x exponent_length_m1 = 0x%02x modulus_length_reg = 0x%02x modulus_length_m1 = 0x%02x",
                 dut.exponent_length_reg,  dut.core_inst.exponent_length_m1, dut.modulus_length_reg, dut.core_inst.modulus_length_m1);
        $display("ctrl_reg = 0x%04x", dut.core_inst.modexp_ctrl_reg);
        $display("");
    end
endtask // dump_dut_state
//----------------------------------------------------------------
// reset_dut()
//
// Toggle reset to put the DUT into a well known state.
//----------------------------------------------------------------
task reset_dut();
    begin
        $display("*** Toggle reset.");
        tb_reset_n = 0;
        #(2 * CLK_PERIOD);
        tb_reset_n = 1;
        $display("");
    end
endtask // reset_dut
//----------------------------------------------------------------
// display_test_results()
//
// Display the accumulated test results.
//----------------------------------------------------------------
task display_test_results();
    begin
        if (error_ctr == 0)
            begin
                $display("*** All %02d test cases completed successfully", tc_ctr);
            end
        else
            begin
                $display("*** %02d tests completed - %02d test cases did not complete successfully.",
                         tc_ctr, error_ctr);
            end
    end
endtask // display_test_results
//----------------------------------------------------------------
// init_sim()
//
// Initialize all counters and testbed functionality as well
// as setting the DUT inputs to defined values.
//----------------------------------------------------------------
task init_sim();
    begin
        cycle_ctr          = 0;
        error_ctr          = 0;
        tc_ctr             = 0;
        tb_clk             = 0;
        tb_reset_n         = 1;
        tb_cs              = 0;
        tb_we              = 0;
        tb_address         = 8'h00;
        tb_write_data      = 32'h00000000;
    end
endtask // init_sim
//----------------------------------------------------------------
// read_word()
//
// Read a data word from the given address in the DUT.
// the word read will be available in the global variable
// read_data.
//----------------------------------------------------------------
task read_word(input [11 : 0] address);
    begin
        tb_address = address;
        tb_cs = 1;
        tb_we = 0;
        #(CLK_PERIOD);
        read_data = tb_read_data;
        tb_cs = 0;
        if (DEBUG)
            begin
                $display("*** (read_word) Reading 0x%08x from 0x%02x.", read_data, address);
                $display("");
            end
    end
endtask // read_word
//----------------------------------------------------------------
// write_word()
//
// Write the given word to the DUT using the DUT interface.
//----------------------------------------------------------------
task write_word(input [11 : 0] address,
                    input [31 : 0] word);
    begin
        if (DEBUG)
            begin
                $display("*** (write_word) Writing 0x%08x to 0x%02x.", word, address);
                $display("");
            end
        tb_address = address;
        tb_write_data = word;
        tb_cs = 1;
        tb_we = 1;
        #(CLK_PERIOD);
        tb_cs = 0;
        tb_we = 0;
    end
endtask // write_word
//----------------------------------------------------------------
// wait_ready()
//
// Wait until the ready flag in the core is set.
//----------------------------------------------------------------
task wait_ready();
    begin
        while (tb_read_data != 32'h00000001)
            read_word({GENERAL_PREFIX, ADDR_STATUS});
        if (DEBUG)
            $display("*** (wait_ready) Ready flag has been set.");
    end
endtask // wait_ready
//----------------------------------------------------------------
// dump_message_mem()
//
// Dump the contents of the message memory.
//----------------------------------------------------------------
task dump_message_mem();
    reg [8 : 0] i;
    begin
        $display("Contents of the message memory:");
        for (i = 0 ; i < 256 ; i = i + 8)
            begin
                $display("message_mem[0x%02x .. 0x%02x] = 0x%08x 0x%08x 0x%08x 0x%08x  0x%08x 0x%08x 0x%08x 0x%08x",
                         i[7 : 0], (i[7 : 0] + 8'h07),
                         dut.core_inst.message_mem.mem[(i[7 : 0] + 0)], dut.core_inst.message_mem.mem[(i[7 : 0] + 1)],
                         dut.core_inst.message_mem.mem[(i[7 : 0] + 2)], dut.core_inst.message_mem.mem[(i[7 : 0] + 3)],
                         dut.core_inst.message_mem.mem[(i[7 : 0] + 4)], dut.core_inst.message_mem.mem[(i[7 : 0] + 5)],
                         dut.core_inst.message_mem.mem[(i[7 : 0] + 6)], dut.core_inst.message_mem.mem[(i[7 : 0] + 7)],
                        );
            end
        $display("");
    end
endtask // dump_message_mem
//----------------------------------------------------------------
// dump_exponent_mem()
//
// Dump the contents of the exponent memory.
//----------------------------------------------------------------
task dump_exponent_mem();
    reg [8 : 0] i;
    begin
        $display("Contents of the exponent memory:");
        for (i = 0 ; i < 256 ; i = i + 8)
            begin
                $display("exponent_mem[0x%02x .. 0x%02x] = 0x%08x 0x%08x 0x%08x 0x%08x  0x%08x 0x%08x 0x%08x 0x%08x",
                         i[7 : 0], (i[7 : 0] + 8'h07),
                         dut.core_inst.exponent_mem.mem[(i[7 : 0] + 0)], dut.core_inst.exponent_mem.mem[(i[7 : 0] + 1)],
                         dut.core_inst.exponent_mem.mem[(i[7 : 0] + 2)], dut.core_inst.exponent_mem.mem[(i[7 : 0] + 3)],
                         dut.core_inst.exponent_mem.mem[(i[7 : 0] + 4)], dut.core_inst.exponent_mem.mem[(i[7 : 0] + 5)],
                         dut.core_inst.exponent_mem.mem[(i[7 : 0] + 6)], dut.core_inst.exponent_mem.mem[(i[7 : 0] + 7)],
                        );
            end
        $display("");
    end
endtask // dump_exponent_mem
//----------------------------------------------------------------
// dump_modulus_mem()
//
// Dump the contents of the modulus memory.
//----------------------------------------------------------------
task dump_modulus_mem();
    reg [8 : 0] i;
    begin
        $display("Contents of the modulus memory:");
        for (i = 0 ; i < 256 ; i = i + 8)
            begin
                $display("modulus_mem[0x%02x .. 0x%02x] = 0x%08x 0x%08x 0x%08x 0x%08x  0x%08x 0x%08x 0x%08x 0x%08x",
                         i[7 : 0], (i[7 : 0] + 8'h07),
                         dut.core_inst.modulus_mem.mem[(i[7 : 0] + 0)], dut.core_inst.modulus_mem.mem[(i[7 : 0] + 1)],
                         dut.core_inst.modulus_mem.mem[(i[7 : 0] + 2)], dut.core_inst.modulus_mem.mem[(i[7 : 0] + 3)],
                         dut.core_inst.modulus_mem.mem[(i[7 : 0] + 4)], dut.core_inst.modulus_mem.mem[(i[7 : 0] + 5)],
                         dut.core_inst.modulus_mem.mem[(i[7 : 0] + 6)], dut.core_inst.modulus_mem.mem[(i[7 : 0] + 7)],
                        );
            end
        $display("");
    end
endtask // dump_modulus_mem
//----------------------------------------------------------------
// dump_residue_mem()
//
// Dump the contents of the residue memory.
//----------------------------------------------------------------
task dump_residue_mem();
    reg [8 : 0] i;
    begin
        $display("Contents of the residue memory:");
        for (i = 0 ; i < 256 ; i = i + 8)
            begin
                $display("residue_mem[0x%02x .. 0x%02x] = 0x%08x 0x%08x 0x%08x 0x%08x  0x%08x 0x%08x 0x%08x 0x%08x",
                         i[7 : 0], (i[7 : 0] + 8'h07),
                         dut.core_inst.residue_mem.mem[(i[7 : 0] + 0)], dut.core_inst.residue_mem.mem[(i[7 : 0] + 1)],
                         dut.core_inst.residue_mem.mem[(i[7 : 0] + 2)], dut.core_inst.residue_mem.mem[(i[7 : 0] + 3)],
                         dut.core_inst.residue_mem.mem[(i[7 : 0] + 4)], dut.core_inst.residue_mem.mem[(i[7 : 0] + 5)],
                         dut.core_inst.residue_mem.mem[(i[7 : 0] + 6)], dut.core_inst.residue_mem.mem[(i[7 : 0] + 7)],
                        );
            end
        $display("");
    end
endtask // dump_residue_mem
//----------------------------------------------------------------
// dump_result_mem()
//
// Dump the contents of the result memory.
//----------------------------------------------------------------
task dump_result_mem();
    reg [8 : 0] i;
    begin
        $display("Contents of the result memory:");
        for (i = 0 ; i < 256 ; i = i + 8)
            begin
                $display("result_mem[0x%02x .. 0x%02x] = 0x%08x 0x%08x 0x%08x 0x%08x  0x%08x 0x%08x 0x%08x 0x%08x",
                         i[7 : 0], (i[7 : 0] + 8'h07),
                         dut.core_inst.result_mem.mem[(i[7 : 0] + 0)], dut.core_inst.result_mem.mem[(i[7 : 0] + 1)],
                         dut.core_inst.result_mem.mem[(i[7 : 0] + 2)], dut.core_inst.result_mem.mem[(i[7 : 0] + 3)],
                         dut.core_inst.result_mem.mem[(i[7 : 0] + 4)], dut.core_inst.result_mem.mem[(i[7 : 0] + 5)],
                         dut.core_inst.result_mem.mem[(i[7 : 0] + 6)], dut.core_inst.result_mem.mem[(i[7 : 0] + 7)],
                        );
            end
        $display("");
    end
endtask // dump_result_mem
//----------------------------------------------------------------
// dump_memories()
//
// Dump the contents of the memories in the dut.
//----------------------------------------------------------------
task dump_memories();
    begin
        dump_message_mem();
        dump_exponent_mem();
        dump_modulus_mem();
        dump_residue_mem();
        dump_result_mem();
    end
endtask // dump_memories
//----------------------------------------------------------------
// tc1
//
// A first, very simple testcase where we want to do:
// c = m ** e % N with the following (decimal) test values:
//  m = 3
//  e = 7
//  n = 11
//  c = 3 ** 7 % 11 = 9
//----------------------------------------------------------------
task tc1();
    reg [31 : 0] read_data;
    begin
        tc_ctr = tc_ctr + 1;
        $display("TC1: Trying to calculate 3**7 mod 11 = 9");
        // Write 3 to message memory.
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000003);
        // Write 7 to exponent memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000007);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        // Write 11 to modulus memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h0000000b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000001);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        // Read out result word and check result.
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        if (read_data == 32'h00000009)
            begin
                $display("*** TC1 successful.");
                $display("");
            end
        else
            begin
                $display("*** ERROR: TC1 NOT successful.");
                $display("Expected: 0x09, got 0x%08x", read_data);
                error_ctr = error_ctr + 1;
                dump_memories();
            end
    end
endtask // tc1
//----------------------------------------------------------------
// tc2
//
// c = m ** e % N with the following (decimal) test values:
//  m = 251
//  e = 251
//  n = 257
//  c = 251 ** 251 % 257 = 183
//----------------------------------------------------------------
task tc2();
    reg [31 : 0] read_data;
    begin
        tc_ctr = tc_ctr + 1;
        $display("TC2: Trying to calculate 251**251 mod 257 = 183");
        // Write 13 to message memory.
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h000000fb);
        // Write 11 to exponent memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h000000fb);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        // Write 7 to modulus memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000101);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000001);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        // Read out result word and check result.
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        if (read_data == 32'h000000b7)
            begin
                $display("*** TC2 successful.");
                $display("");
            end
        else
            begin
                $display("*** ERROR: TC2 NOT successful.");
                $display("Expected: 0x000000b7, got 0x%08x", read_data);
                error_ctr = error_ctr + 1;
            end
    end
endtask // tc2
//----------------------------------------------------------------
// tc3
//
// c = m ** e % N with the following (decimal) test values:
//  m = 0x81
//  e = 0x41
//  n = 0x87
//  c = 0x81 ** 0x41 % 0x87 = 0x36
//----------------------------------------------------------------
task tc3();
    reg [31 : 0] read_data;
    begin
        tc_ctr = tc_ctr + 1;
        $display("TC3: Trying to calculate 0x81 ** 0x41 mod 0x87 = 0x36");
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000081);
        // Write 11 to exponent memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000041);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        // Write 7 to modulus memory and set length to one word.
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000087);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000001);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        // Read out result word and check result.
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        if (read_data == 32'h00000036)
            begin
                $display("*** TC3 successful.");
                $display("");
            end
        else
            begin
                $display("*** ERROR: TC3 NOT successful.");
                $display("Expected: 0x06, got 0x%08x", read_data);
                error_ctr = error_ctr + 1;
            end
    end
endtask // tc3
//----------------------------------------------------------------
// assertEquals
//----------------------------------------------------------------
function assertEquals(
        input [31:0] expected,
        input [31:0] actual
    );
    begin
        if (expected === actual)
            begin
                assertEquals = 1; // success
            end
        else
            begin
                $display("Expected: 0x%08x, got 0x%08x", expected, actual);
                assertEquals = 0; // failure
            end
    end
endfunction // assertEquals
integer success;
//----------------------------------------------------------------
// autogenerated_BASIC_33bit()
//
// Task that tests modexp with 33 bit oprerands.
//----------------------------------------------------------------
task autogenerated_BASIC_33bit();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("autogenerated_BASIC_33bit: 00000001946473e1 ** h000000010e85e74f mod 0000000170754797 ");
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h946473e1);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h0e85e74f);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h70754797);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000002);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000002);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h7761ed4f, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: autogenerated_BASIC_33bit was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** autogenerated_BASIC_33bit success.");
    end
endtask // autogenerated_BASIC_33bit
//----------------------------------------------------------------
// autogenerated_BASIC_128bit()
//
// Task that tests modexp with 128 bit operands.
//----------------------------------------------------------------
task autogenerated_BASIC_128bit();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("autogenerated_BASIC_128bit");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h3285c343);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h2acbcb0f);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h4d023228);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h2ecc73db);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h29462882);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h12caa2d5);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb80e1c66);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h1006807f);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h267d2f2e);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h51c216a7);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hda752ead);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h48d22d89);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000004);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000005);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h0ddc404d, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h91600596, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h7425a8d8, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha066ca56, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: autogenerated_BASIC_128bit was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** autogenerated_BASIC_128bit success.");
    end
endtask // autogenerated_BASIC_128bit
//----------------------------------------------------------------
// e64bit_64bit_modulus()
//----------------------------------------------------------------
task e64bit_64bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with 64 bit exponent and 64 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h12345678);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h97543211);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hfeababab);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hdeadbeef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffee);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hbeefbeef);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000002);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000003);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'he52c5b9f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h85de87eb, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: 64 bit exponent and 64 bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** 64 bit exponent and 64 bit modulus success.");
    end
endtask // e64bit_64bit_modulus
//----------------------------------------------------------------
// e65537_64bit_modulus()
//----------------------------------------------------------------
task e65537_64bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 64 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hf077656f);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h3bf9e69b);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb6684dc3);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h79a5824b);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000003);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h132d8e17, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hdd4d85a4, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_64bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_64bit_modulus success.");
    end
endtask // e65537_64bit_modulus
//----------------------------------------------------------------
// e65537_64bit_modulus_elength()
//----------------------------------------------------------------
task e65537_64bit_modulus_elength();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 64 bit modulus, explicit exponent length.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hf077656f);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h3bf9e69b);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb6684dc3);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h79a5824b);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000003);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h132d8e17, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hdd4d85a4, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_64bit_modulus with explicit elength was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_64bit_modulus success.");
    end
endtask // e65537_64bit_modulus_elength
//----------------------------------------------------------------
// e65537_128bit_modulus()
//----------------------------------------------------------------
task e65537_128bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 128 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hf5e8eee0);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc06b048a);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h964b2105);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h2c36ad6b);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h956e61b3);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h27997bc4);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h94e7e5c9);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb53585cf);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000005);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h9c6d322c, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h25ab8bd3, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4aa80100, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf0f3a02c, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_128bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_128bit_modulus success.");
    end
endtask // e65537_128bit_modulus
//----------------------------------------------------------------
// e65537_256bit_modulus()
//
// Task that tests modexp with small exponent and 256 bit modulus.
//----------------------------------------------------------------
task e65537_256bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 256 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hf169d36e);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hbe2ce61d);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc2e87809);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h4fed15c3);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h7c70eac5);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'ha123e643);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h299b36d2);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h788e583b);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hf169d36e);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hbe2ce61d);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hc2e87809);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h4fed15c3);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h7c70eac5);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'ha123e643);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h299b36d2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h788e583a);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000009);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf169d36e, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hbe2ce61d, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hc2e87809, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4fed15c3, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h7c70eac5, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha123e643, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h299b36d2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h788e583a, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_256bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_256bit_modulus success.");
    end
endtask // e65537_256bit_modulus
//----------------------------------------------------------------
// e65537_1024bit_modulus()
//
// Task that tests modexp with small exponent and
//  2048 bit modulus.
//----------------------------------------------------------------
task e65537_1024bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 1024 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000021);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h45d55343, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha0971add, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_1024bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_1024bit_modulus success.");
    end
endtask // e65537_1024bit_modulus
//----------------------------------------------------------------
// e65537_1536bit_modulus()
//
// Task that tests modexp with small exponent and
// 1536 bit modulus.
//----------------------------------------------------------------
task e65537_1536bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 1536 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000031);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4ade4f46, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h02cb4a2f, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_1536bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_1536bit_modulus success.");
    end
endtask // e65537_1536bit_modulus
//----------------------------------------------------------------
// e65537_1664bit_modulus()
//
// Task that tests modexp with small exponent and
// 1664 bit modulus.
//----------------------------------------------------------------
task e65537_1664bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 1664 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000035);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h88671c15, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2aeeb8b2, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_1664bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_1664it_modulus success.");
    end
endtask // e65537_1664bit_modulus
//----------------------------------------------------------------
// e65537_2048bit_modulus()
//
// Task that tests modexp with small exponent and
//  2048 bit modulus.
//----------------------------------------------------------------
task e65537_2048bit_modulus();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Test with e = 65537 and 2048 bit modulus.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hffeeffef);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffaabbcc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hddeeffff);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000001);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000041);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf1752196, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4c36e92f, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_2048bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_2048bit_modulus success.");
    end
endtask // e65537_2048bit_modulus
//----------------------------------------------------------------
// rob_dec_1024()
//
// Task that tests modexp with 1024 bit decipher/sign with
// real RSA key operands.
//----------------------------------------------------------------
task rob_dec_1024();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Desipher/Sign Test with Rob 1024 bit operands.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h3ff26c9e);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h32685b93);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h66570228);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hf0603c4e);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h04a717c1);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h8038b116);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'heb48325e);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hcada992a);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h920bb241);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h5aee4afe);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'he2a37e87);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hb35b9519);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hb335775d);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h989553e9);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h1326f46e);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h2cdf6b7b);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h84aabfa9);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hef24c600);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hb56872ad);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h5edb9041);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'he8ecd7f8);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h535133fb);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hdefc92c7);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h42384226);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h7d40e5f5);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hc91bd745);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h9578e460);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hfc858374);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h3172bed3);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h73b6957c);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'hc0d6a68e);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h33156a61);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h0001ffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hffffffff);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00303130);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h0d060960);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h86480165);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h03040201);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h05000420);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h8e36fc9a);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'ha31724c3);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h2416263c);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h0366a175);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hfabbb92b);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h741ca649);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h6107074d);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h0343b597);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hd075ec0a);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h95048ef8);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hcaa69073);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h8d9d58e9);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h1764b437);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h50b58cad);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h8a6e3199);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h135f80ee);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h84eb2bde);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h58d38ee3);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h5825e91e);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hafdeb1ba);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'ha15a160b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h0057c47c);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc7765e31);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h868a3e15);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h5ee57cef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hb008c4dd);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h6a0a89ee);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h98a4ee9c);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h971a07de);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h61e5b0d3);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hcf70e1cd);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc6a0de5b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h451f2fb9);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hdb995196);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h9f2f884b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h4b09749a);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'he6c4ddbe);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h7ee61f79);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h265c6adf);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hb16b3015);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000021);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000021);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h06339a64, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h367db02a, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf41158cc, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h95e76049, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4519c165, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h111184be, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'he41d8ee2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2ae5f5d1, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h1da7f962, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hac93ac88, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h915eee13, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha3350c22, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hf0dfa62e, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hfdfc2b62, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h29f26e27, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hbebdc84e, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h4746df79, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h7b387ad2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h13423c9f, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h98e8a146, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hff486b6c, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h1a85414e, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h73117121, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hb700e547, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hab4e07b2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h21b988b8, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h24dd77c2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h046b0a20, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hcddb986a, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hac75c2f2, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hb044ed59, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hea565879, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: rob_dec_1024 was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** rob_dec_1024 success.");
    end
endtask // rob_dec_1024
//----------------------------------------------------------------
// rob_enc_1024()
//
// Task that tests modexp with 1024 bit encipher/verify with
// real RSA key operands.
//----------------------------------------------------------------
task rob_enc_1024();
    reg [31 : 0] read_data;
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Encipher/Verify Test with Rob 1024 bit operands.");
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_DATA}, 32'h00010001);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h06339a64);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h367db02a);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hf41158cc);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h95e76049);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h4519c165);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h111184be);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'he41d8ee2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h2ae5f5d1);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h1da7f962);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hac93ac88);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h915eee13);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'ha3350c22);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hf0dfa62e);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hfdfc2b62);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h29f26e27);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hbebdc84e);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h4746df79);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h7b387ad2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h13423c9f);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h98e8a146);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hff486b6c);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h1a85414e);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h73117121);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb700e547);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hab4e07b2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h21b988b8);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h24dd77c2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'h046b0a20);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hcddb986a);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hac75c2f2);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hb044ed59);
        write_word({GENERAL_PREFIX, ADDR_MESSAGE_DATA}, 32'hea565879);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_PTR_RST}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h00000000);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hd075ec0a);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h95048ef8);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hcaa69073);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h8d9d58e9);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h1764b437);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h50b58cad);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h8a6e3199);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h135f80ee);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h84eb2bde);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h58d38ee3);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h5825e91e);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hafdeb1ba);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'ha15a160b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h0057c47c);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc7765e31);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h868a3e15);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h5ee57cef);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hb008c4dd);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h6a0a89ee);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h98a4ee9c);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h971a07de);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h61e5b0d3);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hcf70e1cd);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hc6a0de5b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h451f2fb9);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hdb995196);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h9f2f884b);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h4b09749a);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'he6c4ddbe);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h7ee61f79);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'h265c6adf);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_DATA}, 32'hb16b3015);
        write_word({GENERAL_PREFIX, ADDR_EXPONENT_LENGTH}, 32'h00000021);
        write_word({GENERAL_PREFIX, ADDR_MODULUS_LENGTH}, 32'h00000021);
        start_test_cycle_ctr();
        // Start processing and wait for ready.
        write_word({GENERAL_PREFIX, ADDR_CTRL}, 32'h00000001);
        wait_ready();
        stop_test_cycle_ctr();
        write_word({GENERAL_PREFIX, ADDR_RESULT_PTR_RST}, 32'h00000000);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00000000, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h0001ffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hffffffff, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h00303130, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h0d060960, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h86480165, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h03040201, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h05000420, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h8e36fc9a, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'ha31724c3, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h2416263c, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h0366a175, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'hfabbb92b, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h741ca649, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h6107074d, read_data);
        read_word({GENERAL_PREFIX, ADDR_RESULT_DATA});
        read_data = tb_read_data;
        success = success & assertEquals(32'h0343b597, read_data);
        if (success !== 1)
            begin
                $display("*** ERROR: rob_enc_1024 was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** rob_enc_1024 success.");
    end
endtask // rob_enc_1024
//----------------------------------------------------------------
// main
//
// The main test functionality.
//----------------------------------------------------------------
initial
    begin : main
        $display("   -= Testbench for modexp started =-");
        $display("    =================================");
        $display("");
        init_sim();
        dump_dut_state();
        reset_dut();
        dump_dut_state();
        //      tc1();
        //      tc2();
        //      tc3();
        //      autogenerated_BASIC_33bit();
        //      autogenerated_BASIC_128bit();
        //      e64bit_64bit_modulus();
        //      e65537_64bit_modulus();
        //      e65537_64bit_modulus_elength();
        //      e65537_128bit_modulus();
        //      e65537_256bit_modulus();
        //      e65537_1024bit_modulus();
        //      e65537_1536bit_modulus();
        //      e65537_1664bit_modulus();
        e65537_2048bit_modulus();
        //      rob_dec_1024();
        //      rob_enc_1024();
        display_test_results();
        $display("");
        $display("*** modexp simulation done. ***");
        $finish;
    end // main
endmodule // tb_modexp
          //======================================================================
          // EOF tb_modexp.v
          //======================================================================
 | 
| 
	//------------------------------------------------------------------
// Simulator directives.
//------------------------------------------------------------------
`timescale 1ns/100ps
//------------------------------------------------------------------
// Test module.
//------------------------------------------------------------------
module tb_top();
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
// Debug output control.
parameter DEBUG                  = 0;
parameter VCD                    = 1;
// Clock defines.
localparam CLK_HALF_PERIOD       = 1;
localparam CLK_PERIOD            = 2 * CLK_HALF_PERIOD;
// Address defines
localparam OPERAND_WIDTH         = 32;
localparam ADDRESS_WIDTH         = 8;
localparam ADDR_NAME0            = 8'h00;
localparam ADDR_NAME1            = 8'h01;
localparam ADDR_VERSION          = 8'h02;
localparam ADDR_CTRL             = 8'h08;
localparam CTRL_INIT_BIT         = 0;
localparam CTRL_NEXT_BIT         = 1;
localparam ADDR_STATUS           = 8'h09;
localparam STATUS_READY_BIT      = 0;
localparam ADDR_CYCLES_HIGH      = 8'h10;
localparam ADDR_CYCLES_LOW       = 8'h11;
localparam ADDR_MODULUS_LENGTH   = 8'h20;
localparam ADDR_EXPONENT_LENGTH  = 8'h21;
localparam ADDR_MODULUS_PTR_RST  = 8'h30;
localparam ADDR_MODULUS_DATA     = 8'h31;
localparam ADDR_EXPONENT_PTR_RST = 8'h40;
localparam ADDR_EXPONENT_DATA    = 8'h41;
localparam ADDR_MESSAGE_PTR_RST  = 8'h50;
localparam ADDR_MESSAGE_DATA     = 8'h51;
localparam ADDR_RESULT_PTR_RST   = 8'h60;
localparam ADDR_RESULT_DATA      = 8'h61;
localparam DEFAULT_MODLENGTH     = 8'h80; // 2048 bits.
localparam DEFAULT_EXPLENGTH     = 8'h80;
localparam CORE_NAME0            = 32'h6d6f6465; // "mode"
localparam CORE_NAME1            = 32'h78702020; // "xp  "
localparam CORE_VERSION          = 32'h302e3532; // "0.52"
//----------------------------------------------------------------
// Register and Wire declarations.
//----------------------------------------------------------------
reg  [31 : 0] error_ctr;
reg  [31 : 0] tc_ctr;
reg [127 : 0] result_data;
reg           tb_clk;
reg           tb_reset;
reg           tb_cs;
reg           tb_we;
reg  [31 : 0] tb_address;
reg  [31 : 0] tb_write_data;
wire [31 : 0] tb_read_data;
wire          tb_error;
reg           tb_cyc;
reg  [3 : 0]  tb_sel;
wire          tb_ack;
wire          tb_err;
wire          tb_int;
reg  [31 : 0] pmsg [63 : 0];
reg  [31 : 0] cmsg [63 : 0];
reg  [31 : 0] gmsg [63 : 0];
integer f1;
//----------------------------------------------------------------
// Device Under Test.
//----------------------------------------------------------------
modexp_top dut(
               .wb_adr_i(tb_address),
               .wb_cyc_i(tb_cyc),//
               .wb_dat_i(tb_write_data),
               .wb_sel_i(tb_sel),//
               .wb_stb_i(tb_cs),
               .wb_we_i(tb_we),
               .wb_ack_o(tb_ack),//
               .wb_err_o(tb_err),//
               .wb_dat_o(tb_read_data),
               .wb_clk_i(tb_clk),
               .wb_rst_i(tb_reset),
               .int_o(tb_int)//
           );
//----------------------------------------------------------------
// clk_gen
//
// Always running clock generator process.
//----------------------------------------------------------------
always
    begin : clk_gen
        #CLK_HALF_PERIOD;
        tb_clk = !tb_clk;
    end // clk_gen
//----------------------------------------------------------------
// reset_dut()
//
// Toggle reset to put the DUT into a well known state.
//----------------------------------------------------------------
task reset_dut();
    begin
        $display("*** Toggle reset.");
        tb_reset = 1;
        #(2 * CLK_PERIOD);
        tb_reset = 0;
        $display("");
    end
endtask // reset_dut
//----------------------------------------------------------------
// init_sim()
//
// Initialize all counters and testbed functionality as well
// as setting the DUT inputs to defined values.
//----------------------------------------------------------------
task init_sim();
    begin
        error_ctr          = 0;
        tc_ctr             = 0;
        tb_clk             = 0;
        tb_reset           = 0;
        tb_cs              = 0;
        tb_we              = 0;
        tb_address         = 32'h00000000;
        tb_write_data      = 32'h00000000;
    end
endtask // init_sim
//----------------------------------------------------------------
// read_word()
//
// Read a data word from the given address in the DUT.
//----------------------------------------------------------------
task read_word(input [7 : 0] address);
    begin
        tb_address = {22'b0,address,2'b0};
        tb_cs = 1;
        tb_we = 0;
        #(CLK_PERIOD);
        tb_cs = 0;
        if (DEBUG)
            begin
                $display("*** (read_word) Reading 0x%08x from 0x%02x.", tb_read_data, address);
                $display("");
            end
    end
endtask // read_word
//----------------------------------------------------------------
// write_word()
//
// Write the given word to the DUT using the DUT interface.
//----------------------------------------------------------------
task write_word(input [ 7 : 0] address,
                    input [31 : 0] word);
    begin
        if (DEBUG)
            begin
                $display("*** (write_word) Writing 0x%08x to 0x%02x.", word, address);
                $display("");
            end
        tb_address = {22'b0,address,2'b0};
        tb_write_data = word;
        tb_cs = 1;
        tb_we = 1;
        #(CLK_PERIOD);
        tb_cs = 0;
        tb_we = 0;
    end
endtask // write_word
//----------------------------------------------------------------
// wait_ready()
//
// Wait until the ready flag in the core is set.
//----------------------------------------------------------------
task wait_ready();
    begin
        while (tb_read_data != 32'h00000001)
            read_word(8'h09);
        if (DEBUG)
            $display("*** (wait_ready) Ready flag has been set.");
    end
endtask // wait_ready
//----------------------------------------------------------------
// assertEquals
//----------------------------------------------------------------
function assertEquals(
        input [31:0] expected,
        input [31:0] actual
    );
    begin
        if (expected === actual)
            begin
                assertEquals = 1; // success
            end
        else
            begin
                $display("*** Expected: 0x%08x, got 0x%08x", expected, actual);
                assertEquals = 0; // failure
            end
    end
endfunction // assertEquals
//----------------------------------------------------------------
// assertSuccess
//----------------------------------------------------------------
task assertSuccess(input success);
    begin
        if (success !== 1)
            begin
                $display("*** Test    -> FAILED");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** Test    -> passed");
    end
endtask // assertSuccess
//----------------------------------------------------------------
// display_test_results()
//
// Display the accumulated test results.
//----------------------------------------------------------------
task display_test_results();
    begin
        $display("");
        if (error_ctr == 0)
            begin
                $display("*** All %02d test cases completed successfully", tc_ctr);
            end
        else
            begin
                $display("*** %02d tests completed - %02d test cases did not complete successfully.",
                         tc_ctr, error_ctr);
            end
    end
endtask // display_test_results
//----------------------------------------------------------------
// exp32bit_mod2048bit_test
//----------------------------------------------------------------
task exp32bit_mod2048bit_test();
    integer i;
    integer success;
    reg [31 : 0] read_data;
    reg  [31 : 0] exp  [63 : 0];
    reg  [31 : 0] mod  [63 : 0];
    reg  [31 : 0] msg  [63 : 0];
    reg  [31 : 0] res  [63 : 0];
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("");
        $display("Test with e = 65537 and 2048 bit modulus -- Encrypting");
        $readmemh("./gen/exp", exp);
        $readmemh("./gen/mod", mod);
        $readmemh("./gen/msg",  msg);
        $readmemh("./gen/res",  res);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , exp[0]);
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, mod[i]);
                if(DEBUG)
                    $display("writing: %d -> %h", i, mod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, msg[i]);
                if(DEBUG)
                    $display("Writing: %d -> %h", i, msg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        read_data=tb_read_data;
        success=success&assertEquals(32'h00000000, read_data);
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                read_data=tb_read_data;
                success=success&assertEquals(res[i], read_data);
                if(DEBUG)
                    $display("Reading: %d -> %h -> %h", i, res[i], read_data);
            end
        if (success !== 1)
            begin
                $display("*** ERROR: e65537_2048bit_modulus was NOT successful.");
                error_ctr = error_ctr + 1;
            end
        else
            $display("*** e65537_2048bit_modulus success.");
    end
endtask // exp32bit_mod2048bit_test
//----------------------------------------------------------------
// modexp_encrypt
//----------------------------------------------------------------
task modexp_encrypt();
    integer i;
    integer success;
    reg [31 : 0] pubexp [1];
    reg [31 : 0] pubmod [63 : 0];
    begin
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("");
        $display("Encrypting -- exp = 65537 and 2048 bit mod");
        $readmemh("./gen/pTextHEX", pmsg);
        $readmemh("./gen/exponent", pubexp);
        $readmemh("./gen/modulus",  pubmod);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , pubexp[0]);
        if(DEBUG)
            $display("Writing EXP: %d %h", pubexp[0], pubexp[0]);
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, pubmod[i]);
                if(DEBUG)
                    $display("Writing MOD: %d -> %h", i, pubmod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, pmsg[i]);
                if(DEBUG)
                    $display("Writing MSG: %d -> %h", i, pmsg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        cmsg[0]=tb_read_data;
        //success=success&assertEquals(32'h00000000, cmsg[0]);
        f1 = $fopen("./gen/cTextHEX", "w");
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                cmsg[i]=tb_read_data;
                if(DEBUG)
                    $display("Reading: %d -> %h ", i, cmsg[i]);
                $fwrite(f1, "%h\n",cmsg[i]);
            end
        $fclose(f1);
        assertSuccess(success);
    end
endtask // modexp_encrypt
//----------------------------------------------------------------
// modexp_decrypt
//----------------------------------------------------------------
task modexp_decrypt();
    integer i;
    integer success;
    reg [31 : 0] rdata;
    reg [31 : 0] read_data;
    reg [31 : 0] priexp [63 : 0];
    reg [31 : 0] primod [63 : 0];
    begin
        $display("");
        $display("*** Running -> modexp_decrypt()");
        $readmemh("./gen/priExponent", priexp);
        $readmemh("./gen/priModulus",  primod);
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("Decrypting -- 2048 bit exp and 2048 bit mod");
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_EXPONENT_DATA, priexp[i]);
                if(DEBUG)
                    $display("Writing EXP: %d -> %h", i, priexp[i]);
            end
        write_word(ADDR_MODULUS_PTR_RST, 32'h00000000);
        write_word(ADDR_MODULUS_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MODULUS_DATA, primod[i]);
                if(DEBUG)
                    $display("Writing MOD: %d -> %h", i, primod[i]);
            end
        write_word(ADDR_MESSAGE_PTR_RST, 32'h00000000);
        write_word(ADDR_MESSAGE_DATA   , 32'h00000000);
        for(i=0; i<64; i=i+1)
            begin
                write_word(ADDR_MESSAGE_DATA, cmsg[i]);
                if(DEBUG)
                    $display("Writing MSG: %d -> %h", i, cmsg[i]);
            end
        write_word(ADDR_EXPONENT_LENGTH, 32'h00000041);
        write_word(ADDR_MODULUS_LENGTH , 32'h00000041);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL, 32'h00000001);
        wait_ready();
        write_word(ADDR_RESULT_PTR_RST, 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        rdata=tb_read_data;
        success=success&assertEquals(32'h00000000, rdata);
        f1 = $fopen("./gen/gTextHEX", "w");
        for(i=0; i<64; i=i+1)
            begin
                read_word(ADDR_RESULT_DATA);
                rdata=tb_read_data;
                if(DEBUG)
                    $display("Reading: %d -> %h ", i, rdata);
                $fwrite(f1, "%h\n",rdata);
                success=success&assertEquals(pmsg[i], rdata);
            end
        $fclose(f1);
        assertSuccess(success);
    end
endtask // modexp_decrypt
//----------------------------------------------------------------
// modexp_32bits
//----------------------------------------------------------------
task modexp_32bits(input [31:0] Wmsg,
                       input [31:0] Wexp,
                       input [31:0] Wmod,
                       input [31:0] Wres);
    reg [31 : 0] Rmsg;
    reg [31 : 0] Rexp;
    reg [31 : 0] Rmod;
    reg [31 : 0] Rres;
    integer success;
    begin
        $display("");
        $display("*** Running -> modexp_32bits()");
        success = 32'h1;
        tc_ctr = tc_ctr + 1;
        $display("*** Writing -> MES: %h EXP: %h MOD: %h", Wmsg, Wexp, Wmod);
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        write_word(ADDR_EXPONENT_DATA   , Wexp);
        write_word(ADDR_MODULUS_PTR_RST , 32'h00000000);
        write_word(ADDR_MODULUS_DATA    , Wmod);
        write_word(ADDR_MESSAGE_PTR_RST , 32'h00000000);
        write_word(ADDR_MESSAGE_DATA    , Wmsg);
        write_word(ADDR_EXPONENT_LENGTH , 32'h00000001);
        write_word(ADDR_MODULUS_LENGTH  , 32'h00000001);
        // Start processing and wait for ready.
        write_word(ADDR_CTRL            , 32'h00000001);
        wait_ready();
        write_word(ADDR_MESSAGE_PTR_RST , 32'h00000000);
        read_word(ADDR_MESSAGE_DATA);
        Rmsg=tb_read_data;
        write_word(ADDR_EXPONENT_PTR_RST, 32'h00000000);
        read_word(ADDR_EXPONENT_DATA);
        Rexp=tb_read_data;
        write_word(ADDR_MODULUS_PTR_RST , 32'h00000000);
        read_word(ADDR_MODULUS_DATA);
        Rmod=tb_read_data;
        write_word(ADDR_RESULT_PTR_RST  , 32'h00000000);
        read_word(ADDR_RESULT_DATA);
        Rres=tb_read_data;
        $display("*** Reading -> MES: %h EXP: %h MOD: %h RES: %h", Rmsg, Rexp, Rmod, Rres);
        success=success&assertEquals(Wres, Rres);
        assertSuccess(success);
    end
endtask // modexp_32bits
//----------------------------------------------------------------
// main
//
// The main test functionality.
//----------------------------------------------------------------
initial
    begin : main
        if(VCD)
            begin
                $dumpfile("./iverilog/tb_top.vcd");
                $dumpvars(0,tb_top);
                //$dumpvars(1,tb_clk, tb_reset, tb_cs, tb_we, tb_address, tb_write_data, tb_read_data);
            end
        $display("   -= Testbench for modexp started =-");
        $display("    =================================");
        $display("");
        init_sim();
        reset_dut();
        modexp_32bits(32'h00000001, 32'h00000002, 32'h00000005, 32'h00000001); //msg^exp < mod -> 1^2 < 5
        modexp_32bits(32'h00000001, 32'h00000002, 32'h00000003, 32'h00000001); //msg^exp < mod -> 1^2 < 3
        modexp_32bits(32'h00000002, 32'h00000002, 32'h00000005, 32'h00000004); //msg^exp < mod -> 2^2 < 5
        modexp_32bits(32'h00000002, 32'h00000002, 32'h00000003, 32'h00000001); //msg^exp > mod -> 2^2 > 3
        modexp_32bits(32'h00000004, 32'h0000000D, 32'h000001F1, 32'h000001bd); //msg^exp > mod -> 4^13 > 497
        modexp_32bits(32'h01234567, 32'h89ABCDEF, 32'h11111111, 32'h0D9EF081); //msg^exp > mod -> 19088743^2309737967 > 286331153
        modexp_32bits(32'h30000000, 32'hC0000000, 32'h00A00001, 32'h0000CC3F); //msg^exp > mod -> 805306368^3221225472 > 10485761 <- Passes
        //modexp_32bits(32'h30000000, 32'hC0000000, 32'h00A00000, 32'h00600000); //msg^exp > mod -> 805306368^3221225472 > 10485760 <- Fails
        //modexp_32bits(32'h00000002, 32'h00000003, 32'h00000001, 32'h00000000); //mod 1 <- FAILS Does not check
        /*
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000002, 32'h00000001); //1 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000003, 32'h00000001); //1 mod 3 = 1 -> 1 <- passes
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000004, 32'h00000001); //1 mod 4 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000005, 32'h00000001); //1 mod 5 = 1 -> 1 <- passes
            modexp_32bits(32'h00000001, 32'h00000002, 32'h00000006, 32'h00000001); //1 mod 6 = 1 -> 4 <- FAILS
            
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000002, 32'h00000000); //2 mod 2 = 0 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000003, 32'h00000002); //2 mod 3 = 2 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000004, 32'h00000002); //2 mod 4 = 2 -> 0 <- FAILS
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000005, 32'h00000002); //2 mod 5 = 2 -> passes
            modexp_32bits(32'h00000002, 32'h00000001, 32'h00000006, 32'h00000002); //2 mod 6 = 2 -> passes
            
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000002, 32'h00000001); //3 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000003, 32'h00000000); //3 mod 3 = 0 -> 3 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000004, 32'h00000003); //3 mod 4 = 3 -> 0 <- FAILS
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000005, 32'h00000003); //3 mod 5 = 3 -> passes
            modexp_32bits(32'h00000003, 32'h00000001, 32'h00000006, 32'h00000003); //3 mod 6 = 3 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000002, 32'h00000000); //4 mod 2 = 0 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000003, 32'h00000001); //4 mod 3 = 1 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000004, 32'h00000000); //4 mod 4 = 0 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000005, 32'h00000004); //4 mod 5 = 4 -> passes
            modexp_32bits(32'h00000004, 32'h00000001, 32'h00000006, 32'h00000004); //4 mod 6 = 4 -> passes
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000002, 32'h00000001); //5 mod 2 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000003, 32'h00000002); //5 mod 3 = 2 -> passes
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000004, 32'h00000001); //5 mod 4 = 1 -> 0 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000005, 32'h00000000); //5 mod 5 = 0 -> 5 <- FAILS
            modexp_32bits(32'h00000005, 32'h00000001, 32'h00000006, 32'h00000005); //5 mod 6 = 5 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000002, 32'h00000000); //6 mod 2 = 0 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000003, 32'h00000000); //6 mod 3 = 0 -> 3 <- FAILS
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000004, 32'h00000002); //6 mod 4 = 2 -> 0 <- FAILS
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000005, 32'h00000001); //6 mod 5 = 1 -> passes
            modexp_32bits(32'h00000006, 32'h00000001, 32'h00000006, 32'h00000000); //6 mod 6 = 0 -> 1 <- FAILS
        */
        /*
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000002, 32'h00000000); //8^6 mod 2 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000003, 32'h00000001); //8^6 mod 3 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000004, 32'h00000000); //8^6 mod 4 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000005, 32'h00000004); //8^6 mod 5 = 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000006, 32'h00000004); //8^6 mod 6 = 4 -> 1 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000007, 32'h00000001); //8^6 mod 7 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000008, 32'h00000000); //8^6 mod 8 = 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000009, 32'h00000001); //8^6 mod 9 = 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000A, 32'h00000004); //8^6 mod 10= 4 -> 9 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000B, 32'h00000003); //8^6 mod 11= 3 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000C, 32'h00000004); //8^6 mod 12= 4 -> 5 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000D, 32'h0000000C); //8^6 mod 13= 12-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000E, 32'h00000008); //8^6 mod 14= 8 -> 5 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000000F, 32'h00000004); //8^6 mod 15= 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000010, 32'h00000000); //8^6 mod 16= 0 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000011, 32'h00000004); //8^6 mod 17= 4 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000012, 32'h0000000A); //8^6 mod 18= 10-> 13<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000013, 32'h00000001); //8^6 mod 19= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000014, 32'h00000004); //8^6 mod 20= 4 -> 11<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000015, 32'h00000001); //8^6 mod 21= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000016, 32'h0000000E); //8^6 mod 22= 14-> 1 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000017, 32'h0000000D); //8^6 mod 23= 13-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000018, 32'h00000010); //8^6 mod 24= 16-> 9 <- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h00000019, 32'h00000013); //8^6 mod 25= 19-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001A, 32'h0000000C); //8^6 mod 26= 12-> 19<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001B, 32'h00000001); //8^6 mod 27= 1 -> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001C, 32'h00000008); //8^6 mod 28= 8 -> 19<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001D, 32'h0000000D); //8^6 mod 29= 13-> passes
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001E, 32'h00000004); //8^6 mod 30= 4 -> 13<- FAILS
            modexp_32bits(32'h00000008, 32'h00000006, 32'h0000001F, 32'h00000008); //8^6 mod 31= 8 -> passes
        */
        //exp32bit_mod2048bit_test();
        //modexp_encrypt();
        //modexp_decrypt();
        display_test_results();
        $display("");
        $display("*** modexp simulation done. ***");
        $finish;
    end // main
endmodule // tb_modexp
          //======================================================================
          // EOF tb_modexp.v
          //======================================================================
 | 
| 
	//======================================================================
//
// adder.v
// -------
// Adder with separate carry in and carry out. Used in the montprod
// amd residue modules of the modexp core.
//
//
// Author: Peter Magnusson, Joachim Strömbergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module adder #(parameter OPW = 32)
       (
           input      [(OPW - 1) : 0]  a,
           input      [(OPW - 1) : 0]  b,
           input                       carry_in,
           output wire [(OPW - 1) : 0] sum,
           output wire                 carry_out
       );
reg [(OPW) : 0] adder_result;
assign sum = adder_result[(OPW - 1) : 0];
assign carry_out = adder_result[(OPW)];
always @*
    begin
        adder_result = {1'b0, a} + {1'b0, b} + {{OPW{1'b0}}, carry_in};
    end
endmodule // adder
          //======================================================================
          // EOF adder.v
          //======================================================================
 | 
| 
	//======================================================================
//
// blockmem1rw1.v
// --------------
// Synchronous block memory with one read and one write port.
// The data size is the same for both read and write operations.
//
// The memory is used in the modexp core.
//
// paremeter OPW is operand word width in bits.
// parameter ADW is address width in bits.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module blockmem1r1w #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire  [(ADW - 1) : 0] read_addr,
           output wire [(OPW - 1) : 0] read_data,
           input wire                  wr,
           input wire  [(ADW - 1) : 0] write_addr,
           input wire  [(OPW - 1) : 0] write_data
       );
reg [(OPW - 1) : 0] mem [0 : ((2**ADW) - 1)];
reg [(OPW - 1) : 0] tmp_read_data;
assign read_data = tmp_read_data;
always @ (posedge clk)
    begin : reg_mem
        if (wr)
            mem[write_addr] <= write_data;
        tmp_read_data <= mem[read_addr];
    end
endmodule // blockmem1r1w
          //======================================================================
          // EOF blockmem1r1w.v
          //======================================================================
 | 
| 
	//======================================================================
//
// blockmem2r1w.v
// --------------
// Synchronous block memory with two read ports and one write port.
// The data size is the same for both read and write operations.
//
// The memory is used in the modexp core.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module blockmem2r1w #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire  [(ADW - 1) : 0] read_addr0,
           output wire [(OPW - 1) : 0] read_data0,
           input wire  [(ADW - 1) : 0] read_addr1,
           output wire [(OPW - 1) : 0] read_data1,
           input wire                  wr,
           input wire  [(ADW - 1) : 0] write_addr,
           input wire  [(OPW - 1) : 0] write_data
       );
reg [(OPW - 1) : 0] mem [0 : ((2**ADW) - 1)];
reg [(OPW - 1) : 0] tmp_read_data0;
reg [(OPW - 1) : 0] tmp_read_data1;
assign read_data0 = tmp_read_data0;
assign read_data1 = tmp_read_data1;
always @ (posedge clk)
    begin : reg_mem
        if (wr)
            mem[write_addr] <= write_data;
        tmp_read_data0 <= mem[read_addr0];
        tmp_read_data1 <= mem[read_addr1];
    end
endmodule // blockmem2r1w
          //======================================================================
          // EOF blockmem2r1w.v
          //======================================================================
 | 
| 
	//======================================================================
//
// blockmem2r1wptr.v
// -----------------
// Synchronous block memory with two read ports and one write port.
// For port 1 the address is implicit and instead given by the
// internal pointer. The pointer is automatically increased
// when the cs signal is set. The pointer is reset to zero when
// the rst signal is asserted.
//
//
// NOTE: This memory needs to be rebuilt if interface 0 is changed
// to use bigger operand widths and fewer words than interface 1.
// This adaption is NOT automatic.
//
//
// The memory is used in the modexp core.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module blockmem2r1wptr #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire                  reset_n,
           input wire  [(ADW - 1) : 0] read_addr0,
           output wire [(OPW - 1) : 0] read_data0,
           output wire [31 : 0]        read_data1,
           input wire                  rst,
           input wire                  cs,
           input wire                  wr,
           input wire  [31 : 0]        write_data
       );
//----------------------------------------------------------------
// Memories and regs including update variables and write enable.
//----------------------------------------------------------------
reg [(OPW - 1) : 0] mem [0 : ((2**ADW) - 1)];
reg [(OPW - 1) : 0] tmp_read_data0;
reg [31 : 0]        tmp_read_data1;
reg [7 : 0]         ptr_reg;
reg [7 : 0]         ptr_new;
reg                 ptr_we;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign read_data0 = tmp_read_data0;
assign read_data1 = tmp_read_data1;
//----------------------------------------------------------------
// mem_update
//
// Clocked update of memory This should cause
// the memory to be implemented as a block memory.
//----------------------------------------------------------------
always @ (posedge clk)
    begin : mem_update
        if (wr)
            mem[ptr_reg] <= write_data;
        tmp_read_data0 <= mem[read_addr0];
        tmp_read_data1 <= mem[ptr_reg];
    end
//----------------------------------------------------------------
// ptr_update
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin : ptr_update
        if (!reset_n)
            ptr_reg <= 8'h00;
        else
            if (ptr_we)
                ptr_reg <= ptr_new;
    end
//----------------------------------------------------------------
// ptr_logic
//----------------------------------------------------------------
always @*
    begin : ptr_logic
        ptr_new = 8'h00;
        ptr_we  = 1'b0;
        if (rst)
            begin
                ptr_new = 8'h00;
                ptr_we  = 1'b1;
            end
        if (cs)
            begin
                ptr_new = ptr_reg + 1'b1;
                ptr_we  = 1'b1;
            end
    end
endmodule // blockmem2r1wptr
          //======================================================================
          // EOF blockmem2r1wptr.v
          //======================================================================
 | 
| 
	//======================================================================
//
// blockmem2r1wptr.v
// -----------------
// Synchronous block memory with two read ports and one write port.
// For port 1 the address is implicit and instead given by the
// internal pointer. But write address is explicitly given.
//
// The memory is used in the modexp core.
//
//
// NOTE: This memory needs to be rebuilt if interface 0 is changed
// to use bigger operand widths and fewer words than interface 1.
// This adaption is NOT automatic.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module blockmem2rptr1w #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire                  reset_n,
           input wire  [(ADW - 1) : 0] read_addr0,
           output wire [(OPW - 1) : 0] read_data0,
           output wire [31 : 0]        read_data1,
           input wire                  rst,
           input wire                  cs,
           input wire                  wr,
           input wire  [07 : 0]        write_addr,
           input wire  [31 : 0]        write_data
       );
//----------------------------------------------------------------
// Memories and regs including update variables and write enable.
//----------------------------------------------------------------
reg [(OPW - 1) : 0] mem [0 : ((2**ADW) - 1)];
reg [(OPW - 1) : 0] tmp_read_data0;
reg [31 : 0]        tmp_read_data1;
reg [7 : 0]         ptr_reg;
reg [7 : 0]         ptr_new;
reg                 ptr_we;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign read_data0 = tmp_read_data0;
assign read_data1 = tmp_read_data1;
//----------------------------------------------------------------
// mem_update
//
// Clocked update of memory This should cause
// the memory to be implemented as a block memory.
//----------------------------------------------------------------
always @ (posedge clk)
    begin : mem_update
        if (wr)
            mem[write_addr] <= write_data;
        tmp_read_data0 <= mem[read_addr0];
        tmp_read_data1 <= mem[ptr_reg];
    end
//----------------------------------------------------------------
// reg_update
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin : reg_mem_update
        if (!reset_n)
            ptr_reg <= 8'h00;
        else
            if (ptr_we)
                ptr_reg <= ptr_new;
    end
//----------------------------------------------------------------
// ptr_logic
//----------------------------------------------------------------
always @*
    begin : ptr_logic
        ptr_new = 8'h00;
        ptr_we  = 1'b0;
        if (rst)
            begin
                ptr_new = 8'h00;
                ptr_we  = 1'b1;
            end
        if (cs)
            begin
                ptr_new = ptr_reg + 1'b1;
                ptr_we  = 1'b1;
            end
    end
endmodule // blockmem2r1wptr
          //======================================================================
          // EOF blockmem2r1wptr.v
          //======================================================================
 | 
| 
	//======================================================================
//
// modexp.v
// --------
// Top level wrapper for the modula exponentiation core. The core
// is used to implement public key algorithms such as RSA,
// DH, ElGamal etc.
//
// The core calculates the following function:
//
//   C = M ** e mod N
//
//   M is a message with a length of n bits
//   e is the exponent with a length of m bits
//   N is the modulus  with a length of n bits
//
//   n can be 32 and up to and including 8192 bits in steps
//   of 32 bits.
//   m can be one and up to and including 8192 bits in steps
//   of 32 bits.
//
// The core has a 32-bit memory like interface, but provides
// status signals to inform the system that a given operation
// has is done. Additionally, any errors will also be asserted.
//
//
// Author: Joachim Strombergson, Peter Magnusson
// Copyright (c) 2015, NORDUnet A/S
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
//======================================================================
module modexp(
           input wire           clk,
           input wire           reset_n,
           input wire           cs,
           input wire           we,
           input wire  [ 7 : 0] address,
           input wire  [31 : 0] write_data,
           output wire [31 : 0] read_data
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
// The operand width is the internal operand width in bits.
// The address width is the size of the address space used. This
// value must be balances with OPERAND_WIDTH to allow a total
// of 8192 bits of data. OPERAND_WIDTH * (ADDRESS_WIDTH ** 2)
// is the formula. Note that the API data with is always 32 bits.
localparam OPERAND_WIDTH         = 32;
localparam ADDRESS_WIDTH         = 8;
localparam ADDR_NAME0            = 8'h00;
localparam ADDR_NAME1            = 8'h01;
localparam ADDR_VERSION          = 8'h02;
localparam ADDR_CTRL             = 8'h08;
localparam CTRL_INIT_BIT         = 0;
localparam CTRL_NEXT_BIT         = 1;
localparam ADDR_STATUS           = 8'h09;
localparam STATUS_READY_BIT      = 0;
localparam ADDR_CYCLES_HIGH      = 8'h10;
localparam ADDR_CYCLES_LOW       = 8'h11;
localparam ADDR_MODULUS_LENGTH   = 8'h20;
localparam ADDR_EXPONENT_LENGTH  = 8'h21;
localparam ADDR_MODULUS_PTR_RST  = 8'h30;
localparam ADDR_MODULUS_DATA     = 8'h31;
localparam ADDR_EXPONENT_PTR_RST = 8'h40;
localparam ADDR_EXPONENT_DATA    = 8'h41;
localparam ADDR_MESSAGE_PTR_RST  = 8'h50;
localparam ADDR_MESSAGE_DATA     = 8'h51;
localparam ADDR_RESULT_PTR_RST   = 8'h60;
localparam ADDR_RESULT_DATA      = 8'h61;
localparam DEFAULT_MODLENGTH     = 8'h80; // 2048 bits.
localparam DEFAULT_EXPLENGTH     = 8'h80;
localparam CORE_NAME0            = 32'h6d6f6465; // "mode"
localparam CORE_NAME1            = 32'h78702020; // "xp  "
localparam CORE_VERSION          = 32'h302e3532; // "0.52"
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg [07 : 0] exponent_length_reg;
reg [07 : 0] exponent_length_new;
reg          exponent_length_we;
reg [07 : 0] modulus_length_reg;
reg [07 : 0] modulus_length_new;
reg          modulus_length_we;
reg          start_reg;
reg          start_new;
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
reg           exponent_mem_api_rst;
reg           exponent_mem_api_cs;
reg           exponent_mem_api_wr;
wire [31 : 0] exponent_mem_api_read_data;
reg           modulus_mem_api_rst;
reg           modulus_mem_api_cs;
reg           modulus_mem_api_wr;
wire [31 : 0] modulus_mem_api_read_data;
reg           message_mem_api_rst;
reg           message_mem_api_cs;
reg           message_mem_api_wr;
wire [31 : 0] message_mem_api_read_data;
reg           result_mem_api_rst;
reg           result_mem_api_cs;
wire [31 : 0] result_mem_api_read_data;
wire          ready;
wire [63 : 0] cycles;
reg [31 : 0]  tmp_read_data;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign read_data = tmp_read_data;
//----------------------------------------------------------------
// core instantiations.
//----------------------------------------------------------------
modexp_core #(.OPW(OPERAND_WIDTH), .ADW(ADDRESS_WIDTH))
            core_inst(
                .clk(clk),
                .reset_n(reset_n),
                .start(start_reg),
                .ready(ready),
                .exponent_length(exponent_length_reg),
                .modulus_length(modulus_length_reg),
                .cycles(cycles),
                .exponent_mem_api_cs(exponent_mem_api_cs),
                .exponent_mem_api_wr(exponent_mem_api_wr),
                .exponent_mem_api_rst(exponent_mem_api_rst),
                .exponent_mem_api_write_data(write_data),
                .exponent_mem_api_read_data(exponent_mem_api_read_data),
                .modulus_mem_api_cs(modulus_mem_api_cs),
                .modulus_mem_api_wr(modulus_mem_api_wr),
                .modulus_mem_api_rst(modulus_mem_api_rst),
                .modulus_mem_api_write_data(write_data),
                .modulus_mem_api_read_data(modulus_mem_api_read_data),
                .message_mem_api_cs(message_mem_api_cs),
                .message_mem_api_wr(message_mem_api_wr),
                .message_mem_api_rst(message_mem_api_rst),
                .message_mem_api_write_data(write_data),
                .message_mem_api_read_data(message_mem_api_read_data),
                .result_mem_api_cs(result_mem_api_cs),
                .result_mem_api_rst(result_mem_api_rst),
                .result_mem_api_read_data(result_mem_api_read_data)
            );
//----------------------------------------------------------------
// reg_update
//
// Update functionality for all registers in the core.
// All registers are positive edge triggered with asynchronous
// active low reset. All registers have write enable.
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin
        if (!reset_n)
            begin
                start_reg           <= 1'b0;
                exponent_length_reg <= DEFAULT_EXPLENGTH;
                modulus_length_reg  <= DEFAULT_MODLENGTH;
            end
        else
            begin
                start_reg <= start_new;
                if (exponent_length_we)
                    begin
                        exponent_length_reg <= write_data[7 : 0];
                    end
                if (modulus_length_we)
                    begin
                        modulus_length_reg <= write_data[7 : 0];
                    end
            end
    end // reg_update
//----------------------------------------------------------------
// api
//
// The interface command decoding logic.
//----------------------------------------------------------------
always @*
    begin : api
        modulus_length_we    = 1'b0;
        exponent_length_we   = 1'b0;
        start_new            = 1'b0;
        modulus_mem_api_rst  = 1'b0;
        modulus_mem_api_cs   = 1'b0;
        modulus_mem_api_wr   = 1'b0;
        exponent_mem_api_rst = 1'b0;
        exponent_mem_api_cs  = 1'b0;
        exponent_mem_api_wr  = 1'b0;
        message_mem_api_rst  = 1'b0;
        message_mem_api_cs   = 1'b0;
        message_mem_api_wr   = 1'b0;
        result_mem_api_rst   = 1'b0;
        result_mem_api_cs    = 1'b0;
        tmp_read_data        = 32'h00000000;
        if (cs)
            begin
                if (we)
                    begin
                        case (address)
                            ADDR_CTRL:
                                begin
                                    start_new = write_data[0];
                                end
                            ADDR_MODULUS_LENGTH:
                                begin
                                    modulus_length_we = 1'b1;
                                end
                            ADDR_EXPONENT_LENGTH:
                                begin
                                    exponent_length_we = 1'b1;
                                end
                            ADDR_MODULUS_PTR_RST:
                                begin
                                    modulus_mem_api_rst = 1'b1;
                                end
                            ADDR_MODULUS_DATA:
                                begin
                                    modulus_mem_api_cs = 1'b1;
                                    modulus_mem_api_wr = 1'b1;
                                end
                            ADDR_EXPONENT_PTR_RST:
                                begin
                                    exponent_mem_api_rst = 1'b1;
                                end
                            ADDR_EXPONENT_DATA:
                                begin
                                    exponent_mem_api_cs = 1'b1;
                                    exponent_mem_api_wr = 1'b1;
                                end
                            ADDR_MESSAGE_PTR_RST:
                                begin
                                    message_mem_api_rst = 1'b1;
                                end
                            ADDR_MESSAGE_DATA:
                                begin
                                    message_mem_api_cs = 1'b1;
                                    message_mem_api_wr = 1'b1;
                                end
                            ADDR_RESULT_PTR_RST:
                                begin
                                    result_mem_api_rst = 1'b1;
                                end
                            default:
                                begin
                                end
                        endcase // case (address[7 : 0])
                    end // if (we)
                else
                    begin
                        case (address)
                            ADDR_NAME0:
                                tmp_read_data = CORE_NAME0;
                            ADDR_NAME1:
                                tmp_read_data = CORE_NAME1;
                            ADDR_VERSION:
                                tmp_read_data = CORE_VERSION;
                            ADDR_CTRL:
                                tmp_read_data = {31'h00000000, start_reg};
                            ADDR_STATUS:
                                tmp_read_data = {31'h00000000, ready};
                            ADDR_CYCLES_HIGH:
                                tmp_read_data = cycles[63 : 32];
                            ADDR_CYCLES_LOW:
                                tmp_read_data = cycles[31 : 0];
                            ADDR_MODULUS_LENGTH:
                                tmp_read_data = {24'h000000, modulus_length_reg};
                            ADDR_EXPONENT_LENGTH:
                                tmp_read_data = {24'h000000, exponent_length_reg};
                            ADDR_MODULUS_DATA:
                                begin
                                    modulus_mem_api_cs = 1'b1;
                                    tmp_read_data      = modulus_mem_api_read_data;
                                end
                            ADDR_EXPONENT_DATA:
                                begin
                                    exponent_mem_api_cs = 1'b1;
                                    tmp_read_data       = exponent_mem_api_read_data;
                                end
                            ADDR_MESSAGE_DATA:
                                begin
                                    message_mem_api_cs = 1'b1;
                                    tmp_read_data      = message_mem_api_read_data;
                                end
                            ADDR_RESULT_DATA:
                                begin
                                    result_mem_api_cs = 1'b1;
                                    tmp_read_data     = result_mem_api_read_data;
                                end
                            default:
                                begin
                                end
                        endcase // case (address)
                    end // else: !if(we)
            end // if (cs)
    end // block: api
endmodule // modexp
          //======================================================================
          // EOF modexp.v
          //======================================================================
 | 
| 
	//======================================================================
//
// modexp_core.v
// -------------
// Modular exponentiation core for implementing public key algorithms
// such as RSA, DH, ElGamal etc.
//
// The core calculates the following function:
//
//   C = M ** e mod N
//
//   M is a message with a length of n bits
//   e is the exponent with a length of m bits
//   N is the modulus  with a length of n bits
//
//   n can be 32 and up to and including 8192 bits in steps
//   of 32 bits.
//   m can be one and up to and including 8192 bits in steps
//   of 32 bits.
//
// The core has access ports for the exponent, modulus, message and
// result memories.
//
//
// Author: Joachim Strombergson, Peter Magnusson
// Copyright (c) 2015, NORDUnet A/S
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
//======================================================================
module modexp_core #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire 		clk,
           input wire 		reset_n,
           input wire 		start,
           output wire 		ready,
//           input wire [07 : 0]  exponent_length,
// tony duong 05/27/20: change from unit of 32-bits to actual bits to speed up
           input wire [12 : 0] 	exponent_length, 
           input wire [07 : 0] 	modulus_length,
           output wire [63 : 0] cycles,
           input wire 		exponent_mem_api_cs,
           input wire 		exponent_mem_api_wr,
           input wire 		exponent_mem_api_rst,
           input wire [31 : 0] 	exponent_mem_api_write_data,
           output wire [31 : 0] exponent_mem_api_read_data,
           input wire 		modulus_mem_api_cs,
           input wire 		modulus_mem_api_wr,
           input wire 		modulus_mem_api_rst,
           input wire [31 : 0] 	modulus_mem_api_write_data,
           output wire [31 : 0] modulus_mem_api_read_data,
           input wire 		message_mem_api_cs,
           input wire 		message_mem_api_wr,
           input wire 		message_mem_api_rst,
           input wire [31 : 0] 	message_mem_api_write_data,
           output wire [31 : 0] message_mem_api_read_data,
           input wire 		result_mem_api_cs,
           input wire 		result_mem_api_rst,
           output wire [31 : 0] result_mem_api_read_data
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
localparam MONTPROD_SELECT_ONE_NR = 3'h0;
localparam MONTPROD_SELECT_X_NR   = 3'h1;
localparam MONTPROD_SELECT_Z_P    = 3'h2;
localparam MONTPROD_SELECT_P_P    = 3'h3;
localparam MONTPROD_SELECT_Z_ONE  = 3'h4;
localparam MONTPROD_DEST_Z        = 2'b00;
localparam MONTPROD_DEST_P        = 2'b01;
localparam MONTPROD_DEST_NOWHERE  = 2'b10;
localparam CTRL_IDLE              = 4'h0;
localparam CTRL_RESIDUE           = 4'h1;
localparam CTRL_CALCULATE_Z0      = 4'h2;
localparam CTRL_CALCULATE_P0      = 4'h3;
localparam CTRL_ITERATE           = 4'h4;
localparam CTRL_ITERATE_Z_P       = 4'h5;
localparam CTRL_ITERATE_P_P       = 4'h6;
localparam CTRL_ITERATE_END       = 4'h7;
localparam CTRL_CALCULATE_ZN      = 4'h8;
localparam CTRL_DONE              = 4'h9;
//for rsa, c=M^65537 etc, there is no need to slow down to hide the exponent
localparam EXPONATION_MODE_SECRET_SECURE = 1'b0;
localparam EXPONATION_MODE_PUBLIC_FAST   = 1'b1;
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg          ready_reg;
reg          ready_new;
reg          ready_we;
reg [2 : 0]  montprod_select_reg;
reg [2 : 0]  montprod_select_new;
reg          montprod_select_we;
reg [1 : 0]  montprod_dest_reg;
reg [1 : 0]  montprod_dest_new;
reg          montprod_dest_we;
reg [3 : 0]  modexp_ctrl_reg;
reg [3 : 0]  modexp_ctrl_new;
reg          modexp_ctrl_we;
reg [31 : 0] one_reg;
reg [31 : 0] one_new;
reg [31 : 0] b_one_reg;
reg [31 : 0] b_one_new;
reg [12 : 0] loop_counter_reg;
reg [12 : 0] loop_counter_new;
reg          loop_counter_we;
reg [07 : 0] E_word_index;
reg [04 : 0] E_bit_index;
reg          last_iteration;
reg          ei_reg;
reg          ei_new;
reg          ei_we;
reg          exponation_mode_reg;
reg          exponation_mode_new;
reg          exponation_mode_we;
reg [31 : 0] cycle_ctr_low_reg;
reg [31 : 0] cycle_ctr_low_new;
reg          cycle_ctr_low_we;
reg [31 : 0] cycle_ctr_high_reg;
reg [31 : 0] cycle_ctr_high_new;
reg          cycle_ctr_high_we;
reg          cycle_ctr_state_reg;
reg          cycle_ctr_state_new;
reg          cycle_ctr_state_we;
reg          cycle_ctr_start;
reg          cycle_ctr_stop;
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
reg [07 : 0]  modulus_mem_int_rd_addr;
wire [31 : 0] modulus_mem_int_rd_data;
reg [07 : 0]  message_mem_int_rd_addr;
wire [31 : 0] message_mem_int_rd_data;
reg [07 : 0]  exponent_mem_int_rd_addr;
wire [31 : 0] exponent_mem_int_rd_data;
reg  [07 : 0] result_mem_int_rd_addr;
wire [31 : 0] result_mem_int_rd_data;
reg  [07 : 0] result_mem_int_wr_addr;
reg  [31 : 0] result_mem_int_wr_data;
reg           result_mem_int_we;
reg  [07 : 0] p_mem_rd0_addr;
wire [31 : 0] p_mem_rd0_data;
reg  [07 : 0] p_mem_rd1_addr;
wire [31 : 0] p_mem_rd1_data;
reg  [07 : 0] p_mem_wr_addr;
reg  [31 : 0] p_mem_wr_data;
reg           p_mem_we;
reg [31 : 0]  tmp_read_data;
reg           montprod_calc;
wire          montprod_ready;
reg [07 : 0]  montprod_length;
wire [07 : 0] montprod_opa_addr;
reg [31 : 0]  montprod_opa_data;
wire [07 : 0] montprod_opb_addr;
reg [31 : 0]  montprod_opb_data;
wire [07 : 0] montprod_opm_addr;
reg [31 : 0]  montprod_opm_data;
wire [07 : 0] montprod_result_addr;
wire [31 : 0] montprod_result_data;
wire          montprod_result_we;
reg           residue_calculate;
wire          residue_ready;
reg [14 : 0]  residue_nn;
reg  [07 : 0] residue_length;
wire [07 : 0] residue_opa_rd_addr;
wire [31 : 0] residue_opa_rd_data;
wire [07 : 0] residue_opa_wr_addr;
wire [31 : 0] residue_opa_wr_data;
wire          residue_opa_wr_we;
wire [07 : 0] residue_opm_addr;
reg [31 : 0]  residue_opm_data;
reg  [07 : 0] residue_mem_montprod_read_addr;
wire [31 : 0] residue_mem_montprod_read_data;
reg           residue_valid_reg;
reg           residue_valid_new;
reg           residue_valid_int_validated;
wire [7 : 0]  modulus_length_m1;
   // tony duong
//wire [7 : 0]  exponent_length_m1;
wire [12 : 0]  exponent_length_m1;   
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign ready  = ready_reg;
assign cycles = {cycle_ctr_high_reg, cycle_ctr_low_reg};
assign modulus_length_m1  = modulus_length - 8'h1;
assign exponent_length_m1 = exponent_length - 8'h1;
//----------------------------------------------------------------
// core instantiations.
//----------------------------------------------------------------
montprod #(.OPW(OPW), .ADW(ADW))
         montprod_inst(
             .clk(clk),
             .reset_n(reset_n),
             .calculate(montprod_calc),
             .ready(montprod_ready),
             .length(montprod_length),
             .opa_addr(montprod_opa_addr),
             .opa_data(montprod_opa_data),
             .opb_addr(montprod_opb_addr),
             .opb_data(montprod_opb_data),
             .opm_addr(montprod_opm_addr),
             .opm_data(montprod_opm_data),
             .result_addr(montprod_result_addr),
             .result_data(montprod_result_data),
             .result_we(montprod_result_we)
         );
residue #(.OPW(OPW), .ADW(ADW))
        residue_inst(
            .clk(clk),
            .reset_n(reset_n),
            .calculate(residue_calculate),
            .ready(residue_ready),
            .nn(residue_nn),
            .length(residue_length),
            .opa_rd_addr(residue_opa_rd_addr),
            .opa_rd_data(residue_opa_rd_data),
            .opa_wr_addr(residue_opa_wr_addr),
            .opa_wr_data(residue_opa_wr_data),
            .opa_wr_we(residue_opa_wr_we),
            .opm_addr(residue_opm_addr),
            .opm_data(residue_opm_data)
        );
blockmem2r1w #(.OPW(OPW), .ADW(ADW))
             residue_mem(
                 .clk(clk),
                 .read_addr0(residue_opa_rd_addr),
                 .read_data0(residue_opa_rd_data),
                 .read_addr1(residue_mem_montprod_read_addr),
                 .read_data1(residue_mem_montprod_read_data),
                 .wr(residue_opa_wr_we),
                 .write_addr(residue_opa_wr_addr),
                 .write_data(residue_opa_wr_data)
             );
blockmem2r1w #(.OPW(OPW), .ADW(ADW))
             p_mem(
                 .clk(clk),
                 .read_addr0(p_mem_rd0_addr),
                 .read_data0(p_mem_rd0_data),
                 .read_addr1(p_mem_rd1_addr),
                 .read_data1(p_mem_rd1_data),
                 .wr(p_mem_we),
                 .write_addr(p_mem_wr_addr),
                 .write_data(p_mem_wr_data)
             );
blockmem2r1wptr #(.OPW(OPW), .ADW(ADW))
                exponent_mem(
                    .clk(clk),
                    .reset_n(reset_n),
                    .read_addr0(exponent_mem_int_rd_addr),
                    .read_data0(exponent_mem_int_rd_data),
                    .read_data1(exponent_mem_api_read_data),
                    .rst(exponent_mem_api_rst),
                    .cs(exponent_mem_api_cs),
                    .wr(exponent_mem_api_wr),
                    .write_data(exponent_mem_api_write_data)
                );
blockmem2r1wptr #(.OPW(OPW), .ADW(ADW))
                modulus_mem(
                    .clk(clk),
                    .reset_n(reset_n),
                    .read_addr0(modulus_mem_int_rd_addr),
                    .read_data0(modulus_mem_int_rd_data),
                    .read_data1(modulus_mem_api_read_data),
                    .rst(modulus_mem_api_rst),
                    .cs(modulus_mem_api_cs),
                    .wr(modulus_mem_api_wr),
                    .write_data(modulus_mem_api_write_data)
                );
blockmem2r1wptr #(.OPW(OPW), .ADW(ADW))
                message_mem(
                    .clk(clk),
                    .reset_n(reset_n),
                    .read_addr0(message_mem_int_rd_addr),
                    .read_data0(message_mem_int_rd_data),
                    .read_data1(message_mem_api_read_data),
                    .rst(message_mem_api_rst),
                    .cs(message_mem_api_cs),
                    .wr(message_mem_api_wr),
                    .write_data(message_mem_api_write_data)
                );
blockmem2rptr1w #(.OPW(OPW), .ADW(ADW))
                result_mem(
                    .clk(clk),
                    .reset_n(reset_n),
                    .read_addr0(result_mem_int_rd_addr[7 : 0]),
                    .read_data0(result_mem_int_rd_data),
                    .read_data1(result_mem_api_read_data),
                    .rst(result_mem_api_rst),
                    .cs(result_mem_api_cs),
                    .wr(result_mem_int_we),
                    .write_addr(result_mem_int_wr_addr),
                    .write_data(result_mem_int_wr_data)
                );
//----------------------------------------------------------------
// reg_update
//
// Update functionality for all registers in the core.
// All registers are positive edge triggered with asynchronous
// active low reset. All registers have write enable.
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin
        if (!reset_n)
            begin
                ready_reg           <= 1'b1;
                montprod_select_reg <= MONTPROD_SELECT_ONE_NR;
                montprod_dest_reg   <= MONTPROD_DEST_NOWHERE;
                modexp_ctrl_reg     <= CTRL_IDLE;
                one_reg             <= 32'h0;
                b_one_reg           <= 32'h0;
                loop_counter_reg    <= 13'b0;
                ei_reg              <= 1'b0;
                residue_valid_reg   <= 1'b0;
                exponation_mode_reg <= EXPONATION_MODE_SECRET_SECURE;
                cycle_ctr_low_reg   <= 32'h00000000;
                cycle_ctr_high_reg  <= 32'h00000000;
                cycle_ctr_state_reg <= 1'b0;
            end
        else
            begin
                one_reg             <= one_new;
                b_one_reg           <= b_one_new;
                residue_valid_reg   <= residue_valid_new;
                if (ready_we)
                    ready_reg <= ready_new;
                if (montprod_select_we)
                    montprod_select_reg <= montprod_select_new;
                if (montprod_dest_we)
                    montprod_dest_reg <= montprod_dest_new;
                if (loop_counter_we)
                    loop_counter_reg <= loop_counter_new;
                if (ei_we)
                    ei_reg <= ei_new;
                if (exponation_mode_we)
                    exponation_mode_reg <= exponation_mode_new;
                if (cycle_ctr_low_we)
                    cycle_ctr_low_reg <= cycle_ctr_low_new;
                if (cycle_ctr_high_we)
                    cycle_ctr_high_reg <= cycle_ctr_high_new;
                if (cycle_ctr_state_we)
                    cycle_ctr_state_reg <= cycle_ctr_state_new;
                if (modexp_ctrl_we)
                    modexp_ctrl_reg <= modexp_ctrl_new;
            end
    end // reg_update
//----------------------------------------------------------------
// cycle_ctr
//
// Implementation of the cycle counter
//----------------------------------------------------------------
always @*
    begin : cycle_ctr
        cycle_ctr_low_new   = 32'h00000000;
        cycle_ctr_low_we    = 1'b0;
        cycle_ctr_high_new  = 32'h00000000;
        cycle_ctr_high_we   = 1'b0;
        cycle_ctr_state_new = 1'b0;
        cycle_ctr_state_we  = 1'b0;
        if (cycle_ctr_start)
            begin
                cycle_ctr_low_new   = 32'h00000000;
                cycle_ctr_low_we    = 1'b1;
                cycle_ctr_high_new  = 32'h00000000;
                cycle_ctr_high_we   = 1'b1;
                cycle_ctr_state_new = 1'b1;
                cycle_ctr_state_we  = 1'b1;
            end
        if (cycle_ctr_stop)
            begin
                cycle_ctr_state_new = 1'b0;
                cycle_ctr_state_we  = 1'b1;
            end
        if (cycle_ctr_state_reg)
            begin
                cycle_ctr_low_new = cycle_ctr_low_reg + 1'b1;
                cycle_ctr_low_we  = 1'b1;
                if (cycle_ctr_low_new == 32'h00000000)
                    begin
                        cycle_ctr_high_new  = cycle_ctr_high_reg + 1'b1;
                        cycle_ctr_high_we   = 1'b1;
                    end
            end
    end // cycle_ctr
//----------------------------------------------------------------
// one
//
// generates the big integer one ( 00... 01 )
//----------------------------------------------------------------
always @*
    begin : one_process
        one_new   = 32'h00000000;
        b_one_new = 32'h00000000;
        if (montprod_opa_addr == modulus_length_m1)
            one_new = 32'h00000001;
        if (montprod_opb_addr == modulus_length_m1)
            b_one_new = 32'h00000001;
    end
//----------------------------------------------------------------
// Read mux for modulus. Needed since it is being
// addressed by two sources.
//----------------------------------------------------------------
always @*
    begin : modulus_mem_reader_process
        if (modexp_ctrl_reg == CTRL_RESIDUE)
            modulus_mem_int_rd_addr = residue_opm_addr;
        else
            modulus_mem_int_rd_addr = montprod_opm_addr;
    end
//----------------------------------------------------------------
// Feeds residue calculator.
//----------------------------------------------------------------
always @*
    begin : residue_process
        //N*2, N=length*32, *32 = shl5, *64 = shl6
        residue_nn = { 1'b0, modulus_length, 6'h0 };
        residue_length = modulus_length;
        residue_opm_data = modulus_mem_int_rd_data;
    end
//----------------------------------------------------------------
// Detects if modulus has been updated and we need to
// recalculate the residue
// and we need residue is valid or not.
//----------------------------------------------------------------
always @*
    begin : residue_valid_process
        residue_valid_new = residue_valid_reg;
        if (modulus_mem_api_cs & modulus_mem_api_wr)
            residue_valid_new = 1'b0;
        else if ( residue_valid_int_validated == 1'b1)
            residue_valid_new = 1'b1;
    end
//----------------------------------------------------------------
// montprod_op_select
//
// Select operands used during montprod calculations depending
// on what operation we want to do.
//----------------------------------------------------------------
always @*
    begin : montprod_op_select
        montprod_length          = modulus_length;
        result_mem_int_rd_addr   = montprod_opa_addr;
        message_mem_int_rd_addr  = montprod_opa_addr;
        p_mem_rd0_addr           = montprod_opa_addr;
        residue_mem_montprod_read_addr = montprod_opb_addr;
        p_mem_rd1_addr                 = montprod_opb_addr;
        montprod_opm_data = modulus_mem_int_rd_data;
        case (montprod_select_reg)
            MONTPROD_SELECT_ONE_NR:
                begin
                    montprod_opa_data  = one_reg;
                    montprod_opb_data  = residue_mem_montprod_read_data;
                end
            MONTPROD_SELECT_X_NR:
                begin
                    montprod_opa_data  = message_mem_int_rd_data;
                    montprod_opb_data  = residue_mem_montprod_read_data;
                end
            MONTPROD_SELECT_Z_P:
                begin
                    montprod_opa_data  = result_mem_int_rd_data;
                    montprod_opb_data  = p_mem_rd1_data;
                end
            MONTPROD_SELECT_P_P:
                begin
                    montprod_opa_data  = p_mem_rd0_data;
                    montprod_opb_data  = p_mem_rd1_data;
                end
            MONTPROD_SELECT_Z_ONE:
                begin
                    montprod_opa_data  = result_mem_int_rd_data;
                    montprod_opb_data  = b_one_reg;
                end
            default:
                begin
                    montprod_opa_data  = 32'h00000000;
                    montprod_opb_data  = 32'h00000000;
                end
        endcase // case (montprod_selcect_reg)
    end
//----------------------------------------------------------------
// memory write mux
//
// Direct memory write signals to correct memory.
//----------------------------------------------------------------
always @*
    begin : memory_write_process
        result_mem_int_wr_addr = montprod_result_addr;
        result_mem_int_wr_data = montprod_result_data;
        result_mem_int_we      = 1'b0;
        p_mem_wr_addr = montprod_result_addr;
        p_mem_wr_data = montprod_result_data;
        p_mem_we      = 1'b0;
        case (montprod_dest_reg)
            MONTPROD_DEST_Z:
                result_mem_int_we = montprod_result_we;
            MONTPROD_DEST_P:
                p_mem_we = montprod_result_we;
            default:
                begin
                end
        endcase
        // inhibit Z=Z*P when ei = 0
        if (modexp_ctrl_reg == CTRL_ITERATE_Z_P)
            result_mem_int_we = result_mem_int_we & ei_reg;
    end
//----------------------------------------------------------------
// loop_counter
//
// Calculate the loop counter and related variables.
//----------------------------------------------------------------
always @*
    begin : loop_counters_process
        loop_counter_new = 13'b0;
        loop_counter_we  = 1'b0;
       // tony duong
//        if (loop_counter_reg == {exponent_length_m1, 5'b11111})
       if (loop_counter_reg == exponent_length_m1)
            last_iteration = 1'b1;
        else
            last_iteration = 1'b0;
        case (modexp_ctrl_reg)
            CTRL_CALCULATE_P0:
                begin
                    loop_counter_new = 13'b0;
                    loop_counter_we  = 1'b1;
                end
            CTRL_ITERATE_END:
                begin
                    loop_counter_new = loop_counter_reg + 1'b1;
                    loop_counter_we  = 1'b1;
                end
            default:
                begin
                end
        endcase
    end
//----------------------------------------------------------------
// exponent
//
// Reads the exponent.
//----------------------------------------------------------------
always @*
    begin : exponent_process
        // Accessing new instead of reg - pick up update at
        // CTRL_ITERATE_NEW to remove a pipeline stall.
// tony duong       
//        E_word_index  = exponent_length_m1 - loop_counter_new[ 12 : 5 ];
        E_word_index  = exponent_length_m1[12:5] - loop_counter_new[ 12 : 5 ];	   
        E_bit_index   = loop_counter_reg[ 04 : 0 ];
        exponent_mem_int_rd_addr = E_word_index;
        ei_new = exponent_mem_int_rd_data[ E_bit_index ];
        if (modexp_ctrl_reg == CTRL_ITERATE)
            ei_we = 1'b1;
        else
            ei_we = 1'b0;
    end
//----------------------------------------------------------------
// modexp_ctrl
//
// Control FSM logic needed to perform the modexp operation.
//----------------------------------------------------------------
always @*
    begin
        ready_new           = 1'b0;
        ready_we            = 1'b0;
        montprod_select_new = MONTPROD_SELECT_ONE_NR;
        montprod_select_we  = 0;
        montprod_dest_new   = MONTPROD_DEST_NOWHERE;
        montprod_dest_we    = 0;
        montprod_calc       = 0;
        modexp_ctrl_new     = CTRL_IDLE;
        modexp_ctrl_we      = 1'b0;
        cycle_ctr_start     = 1'b0;
        cycle_ctr_stop      = 1'b0;
        exponation_mode_we  = 1'b0;
        residue_calculate = 1'b0;
        residue_valid_int_validated = 1'b0;
        case (modexp_ctrl_reg)
            CTRL_IDLE:
                begin
                    if (start)
                        begin
                            ready_new       = 1'b0;
                            ready_we        = 1'b1;
                            cycle_ctr_start = 1'b1;
                            if (residue_valid_reg)
                                begin
                                    //residue has alrady been calculated, start with MONTPROD( 1, Nr, MODULUS )
                                    montprod_select_new = MONTPROD_SELECT_ONE_NR;
                                    montprod_select_we  = 1;
                                    montprod_dest_new   = MONTPROD_DEST_Z;
                                    montprod_dest_we    = 1;
                                    montprod_calc       = 1;
                                    modexp_ctrl_new     = CTRL_CALCULATE_Z0;
                                    modexp_ctrl_we      = 1;
                                end
                            else
                                begin
                                    //modulus has been written and residue (Nr) must be calculated
                                    modexp_ctrl_new = CTRL_RESIDUE;
                                    modexp_ctrl_we  = 1;
                                    residue_calculate = 1'b1;
                                end
                        end
                end
            CTRL_RESIDUE:
                begin
                    if (residue_ready)
                        begin
                            montprod_select_new = MONTPROD_SELECT_ONE_NR;
                            montprod_select_we  = 1;
                            montprod_dest_new   = MONTPROD_DEST_Z;
                            montprod_dest_we    = 1;
                            montprod_calc       = 1;
                            modexp_ctrl_new     = CTRL_CALCULATE_Z0;
                            modexp_ctrl_we      = 1;
                            residue_valid_int_validated = 1'b1; //update registers telling residue is valid
                        end
                end
            CTRL_CALCULATE_Z0:
                begin
                    if (montprod_ready)
                        begin
                            montprod_select_new = MONTPROD_SELECT_X_NR;
                            montprod_select_we  = 1;
                            montprod_dest_new   = MONTPROD_DEST_P;
                            montprod_dest_we    = 1;
                            montprod_calc       = 1;
                            modexp_ctrl_new = CTRL_CALCULATE_P0;
                            modexp_ctrl_we  = 1;
                        end
                end
            CTRL_CALCULATE_P0:
                begin
                    if (montprod_ready == 1'b1)
                        begin
                            modexp_ctrl_new = CTRL_ITERATE;
                            modexp_ctrl_we  = 1;
                        end
                end
            CTRL_ITERATE:
                begin
                    montprod_select_new = MONTPROD_SELECT_Z_P;
                    montprod_select_we  = 1;
                    montprod_dest_new   = MONTPROD_DEST_Z;
                    montprod_dest_we    = 1;
                    montprod_calc       = 1;
                    modexp_ctrl_new     = CTRL_ITERATE_Z_P;
                    modexp_ctrl_we      = 1;
                    if (ei_new == 1'b0 && exponation_mode_reg == EXPONATION_MODE_PUBLIC_FAST)
                        begin
                            //Skip the fake montgomery calculation, exponation_mode_reg optimizing for speed not blinding.
                            montprod_select_new = MONTPROD_SELECT_P_P;
                            montprod_dest_new   = MONTPROD_DEST_P;
                            modexp_ctrl_new     = CTRL_ITERATE_P_P;
                        end
                end
            CTRL_ITERATE_Z_P:
                if (montprod_ready)
                    begin
                        montprod_select_new = MONTPROD_SELECT_P_P;
                        montprod_select_we  = 1;
                        montprod_dest_new   = MONTPROD_DEST_P;
                        montprod_dest_we    = 1;
                        montprod_calc       = 1;
                        modexp_ctrl_new     = CTRL_ITERATE_P_P;
                        modexp_ctrl_we      = 1;
                    end
            CTRL_ITERATE_P_P:
                if (montprod_ready == 1'b1)
                    begin
                        modexp_ctrl_new = CTRL_ITERATE_END;
                        modexp_ctrl_we  = 1;
                    end
            CTRL_ITERATE_END:
                begin
                    if (!last_iteration)
                        begin
                            modexp_ctrl_new = CTRL_ITERATE;
                            modexp_ctrl_we  = 1;
                        end
                    else
                        begin
                            montprod_select_new = MONTPROD_SELECT_Z_ONE;
                            montprod_select_we  = 1;
                            montprod_dest_new   = MONTPROD_DEST_Z;
                            montprod_dest_we    = 1;
                            montprod_calc       = 1;
                            modexp_ctrl_new     = CTRL_CALCULATE_ZN;
                            modexp_ctrl_we      = 1;
                        end
                end
            CTRL_CALCULATE_ZN:
                begin
                    if (montprod_ready)
                        begin
                            modexp_ctrl_new = CTRL_DONE;
                            modexp_ctrl_we  = 1;
                        end
                end
            CTRL_DONE:
                begin
                    cycle_ctr_stop  = 1'b1;
                    ready_new       = 1'b1;
                    ready_we        = 1'b1;
                    modexp_ctrl_new = CTRL_IDLE;
                    modexp_ctrl_we  = 1;
                end
            default:
                begin
                end
        endcase // case (modexp_ctrl_reg)
    end
endmodule // modexp_core
          //======================================================================
          // EOF modexp_core.v
          //======================================================================
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       modexp_core_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module modexp_core_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    // Core I/O
    input wire            start,
    output wire           ready,
    input wire [12 : 0]   exponent_length, 
    input wire [07 : 0]   modulus_length,
    output wire [63 : 0]  cycles,
    input wire            exponent_mem_api_cs,
    input wire            exponent_mem_api_wr,
    input wire            exponent_mem_api_rst,
    input wire [31 : 0]   exponent_mem_api_write_data,
    output wire [31 : 0]  exponent_mem_api_read_data,
    input wire            modulus_mem_api_cs,
    input wire            modulus_mem_api_wr,
    input wire            modulus_mem_api_rst,
    input wire [31 : 0]   modulus_mem_api_write_data,
    output wire [31 : 0]  modulus_mem_api_read_data,
    input wire            message_mem_api_cs,
    input wire            message_mem_api_wr,
    input wire            message_mem_api_rst,
    input wire [31 : 0]   message_mem_api_write_data,
    output wire [31 : 0]  message_mem_api_read_data,
    input wire            result_mem_api_cs,
    input wire            result_mem_api_rst,
    output wire [31 : 0]  result_mem_api_read_data,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = RSA_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [31:0]                   mock_tss_modulus_mem_api_write_data;
  wire [31:0]                   mock_tss_message_mem_api_write_data;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  assign mock_tss_modulus_mem_api_write_data  = RSA_MOCK_TSS_KEY_WORDS[0][63:32] ^
                                                llkid_key_register[63:32] ^
                                                modulus_mem_api_write_data;
  assign mock_tss_message_mem_api_write_data  = RSA_MOCK_TSS_KEY_WORDS[0][31:00] ^
                                                llkid_key_register[31:00] ^
                                                message_mem_api_write_data;
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  modexp_core modexp_core_inst (
    .clk                          (clk),
    .reset_n                      (~rst),
    .start                        (start),
    .ready                        (ready),
    .exponent_length              (exponent_length),
    .modulus_length               (modulus_length),
    .cycles                       (cycles),
    .exponent_mem_api_cs          (exponent_mem_api_cs),
    .exponent_mem_api_wr          (exponent_mem_api_wr),
    .exponent_mem_api_rst         (exponent_mem_api_rst),
    .exponent_mem_api_write_data  (exponent_mem_api_write_data),
    .exponent_mem_api_read_data   (exponent_mem_api_read_data),
    .modulus_mem_api_cs           (modulus_mem_api_cs),
    .modulus_mem_api_wr           (modulus_mem_api_wr),
    .modulus_mem_api_rst          (modulus_mem_api_rst),
    .modulus_mem_api_write_data   (mock_tss_modulus_mem_api_write_data),
    .modulus_mem_api_read_data    (modulus_mem_api_read_data),
    .message_mem_api_cs           (message_mem_api_cs),
    .message_mem_api_wr           (message_mem_api_wr),
    .message_mem_api_rst          (message_mem_api_rst),
    .message_mem_api_write_data   (mock_tss_message_mem_api_write_data),
    .message_mem_api_read_data    (message_mem_api_read_data),
    .result_mem_api_cs            (result_mem_api_cs),
    .result_mem_api_rst           (result_mem_api_rst),
    .result_mem_api_read_data     (result_mem_api_read_data)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	//======================================================================
//
// montprod.v
// ---------
// Montgomery product calculator for the modular exponentiantion core.
//
// parameter OPW is operand word width in bits.
// parameter ADW is address width in bits.
//
//
// Author: Peter Magnusson, Joachim Strombergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module montprod #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire                  reset_n,
           input wire                  calculate,
           output wire                 ready,
           input wire [(ADW - 1) : 0]  length,
           output wire [(ADW - 1) : 0] opa_addr,
           input wire [(OPW - 1) : 0]  opa_data,
           output wire [(ADW - 1) : 0] opb_addr,
           input wire [(OPW - 1) : 0]  opb_data,
           output wire [(ADW - 1) : 0] opm_addr,
           input wire [(OPW - 1) : 0]  opm_data,
           output wire [(ADW - 1) : 0] result_addr,
           output wire [(OPW - 1) : 0] result_data,
           output wire                 result_we
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
localparam CTRL_IDLE            = 4'h0;
localparam CTRL_LOOP_ITER       = 4'h1;
localparam CTRL_LOOP_BQ         = 4'h2;
localparam CTRL_CALC_ADD        = 4'h3;
localparam CTRL_STALLPIPE_ADD   = 4'h4;
localparam CTRL_CALC_SDIV2      = 4'h5;
localparam CTRL_STALLPIPE_SDIV2 = 4'h6;
localparam CTRL_L_STALLPIPE_ES  = 4'h7;
localparam CTRL_EMIT_S          = 4'h8;
localparam SMUX_ZERO            = 2'h0;
localparam SMUX_ADD             = 2'h1;
localparam SMUX_SHR             = 2'h2;
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg                  ready_reg;
reg                  ready_new;
reg                  ready_we;
reg [3 : 0]          montprod_ctrl_reg;
reg [3 : 0]          montprod_ctrl_new;
reg                  montprod_ctrl_we;
reg  [1 : 0]         s_mux_new;
reg  [1 : 0]         s_mux_reg;
reg                  s_mem_we_reg;
reg                  s_mem_we_new;
reg [(ADW - 1) : 0]  s_mem_read_addr_reg;
reg                  q_new;
reg                  q_reg;
reg                  b_new;
reg                  b_reg;
reg                  bq_we;
reg [12 : 0]         loop_ctr_reg;
reg [12 : 0]         loop_ctr_new;
reg                  loop_ctr_we;
reg                  loop_ctr_set;
reg                  loop_ctr_dec;
reg [(13 - ADW - 1) : 0] b_bit_index_reg;
reg [(13 - ADW - 1) : 0] b_bit_index_new;
reg                      b_bit_index_we;
reg [(ADW - 1) : 0]  word_index_reg;
reg [(ADW - 1) : 0]  word_index_new;
reg                  word_index_we;
reg [(ADW - 1) : 0]  word_index_prev_reg;
reg                  reset_word_index_lsw;
reg                  reset_word_index_msw;
reg                  inc_word_index;
reg                  dec_word_index;
reg                  add_carry_in_sa_reg;
reg                  add_carry_in_sa_new;
reg                  add_carry_in_sm_reg;
reg                  add_carry_in_sm_new;
reg                  shr_carry_in_reg;
reg                  shr_carry_in_new;
reg                  first_iteration_reg;
reg                  first_iteration_new;
reg                  first_iteration_we;
reg                  test_reg;
reg                  test_new;
reg [(OPW - 2) : 0]  shr_data_out_reg;
reg                  shr_carry_out_reg;
reg                  shr_carry_out_new;
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
wire [(OPW - 1) : 0] add_result_sa;
wire                 add_carry_out_sa;
wire [(OPW - 1) : 0] add_result_sm;
wire                 add_carry_out_sm;
reg [(ADW - 1) : 0]  b_word_index; //loop counter as a word index
/* verilator lint_off UNOPTFLAT */
reg  [(OPW - 1) : 0] shr_data_in;
/* verilator lint_on UNOPTFLAT */
wire                 shr_carry_out;
wire [(OPW - 1) : 0] shr_data_out;
reg [(ADW - 1) : 0]  tmp_opa_addr;
reg                  tmp_result_we;
reg [(ADW - 1) : 0]  s_mem_read_addr;
wire [(OPW - 1) : 0] s_mem_read_data;
reg [(ADW - 1) : 0]  s_mem_write_addr;
reg [(OPW - 1) : 0]  s_mem_write_data;
reg [(OPW - 1) : 0]  tmp_s_mem_write_data;
reg [(OPW - 1) : 0]  sa_adder_data_in;
/* verilator lint_off UNOPTFLAT */
reg [(OPW - 1) : 0]  muxed_s_mem_read_data;
/* verilator lint_on UNOPTFLAT */
reg [(OPW - 1) : 0]  shifted_s_mem_write_data;
wire [(ADW - 1) : 0] length_m1;
// Temporary debug wires.
reg [1 : 0] state_trace;
reg [1 : 0] mux_trace;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign length_m1   = length - 1'b1;
assign opa_addr    = tmp_opa_addr;
assign opb_addr    = b_word_index;
assign opm_addr    = word_index_reg;
assign result_addr = word_index_prev_reg;
assign result_data = s_mem_read_data;
assign result_we   = tmp_result_we;
assign ready       = ready_reg;
//----------------------------------------------------------------
// Instantions
//----------------------------------------------------------------
blockmem1r1w #(.OPW(OPW), .ADW(ADW)) s_mem(
                 .clk(clk),
                 .read_addr(s_mem_read_addr),
                 .read_data(s_mem_read_data),
                 .wr(s_mem_we_reg),
                 .write_addr(s_mem_write_addr),
                 .write_data(s_mem_write_data)
             );
adder #(.OPW(OPW)) s_adder_sm(
          .a(muxed_s_mem_read_data),
          .b(opm_data),
          .carry_in(add_carry_in_sm_reg),
          .sum(add_result_sm),
          .carry_out(add_carry_out_sm)
      );
adder #(.OPW(OPW)) s_adder_sa(
          .a(sa_adder_data_in),
          .b(opa_data),
          .carry_in(add_carry_in_sa_reg),
          .sum(add_result_sa),
          .carry_out(add_carry_out_sa)
      );
shr #(.OPW(OPW)) shifter(
        .a(shr_data_in),
        .carry_in(shr_carry_in_reg),
        .adiv2(shr_data_out),
        .carry_out(shr_carry_out)
    );
//----------------------------------------------------------------
// reg_update
//
// Update functionality for all registers in the core.
// All registers are positive edge triggered with asynchronous
// active low reset. All registers have write enable.
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin : reg_update
        if (!reset_n)
            begin
                test_reg            <= 1'b1;
                ready_reg           <= 1'b1;
                loop_ctr_reg        <= 13'h0;
                word_index_reg      <= {ADW{1'b0}};
                word_index_prev_reg <= {ADW{1'b0}};
                add_carry_in_sa_reg <= 1'b0;
                add_carry_in_sm_reg <= 1'b0;
                shr_data_out_reg    <= {(OPW - 1){1'b0}};
                shr_carry_in_reg    <= 1'b0;
                b_reg               <= 1'b0;
                q_reg               <= 1'b0;
                s_mux_reg           <= SMUX_ZERO;
                s_mem_we_reg        <= 1'b0;
                s_mem_read_addr_reg <= {ADW{1'b0}};
                b_bit_index_reg     <= {(13 - ADW){1'b0}};
                first_iteration_reg <= 1'b0;
                montprod_ctrl_reg   <= CTRL_IDLE;
            end
        else
            begin
                test_reg            <= test_new;
                s_mem_read_addr_reg <= s_mem_read_addr;
                s_mem_we_reg        <= s_mem_we_new;
                s_mux_reg           <= s_mux_new;
                word_index_prev_reg <= word_index_reg;
                shr_carry_in_reg    <= shr_carry_in_new;
                add_carry_in_sa_reg <= add_carry_in_sa_new;
                add_carry_in_sm_reg <= add_carry_in_sm_new;
                shr_data_out_reg    <= shr_data_out[(OPW - 2) : 0];
                if (word_index_we)
                    word_index_reg <= word_index_new;
                if (first_iteration_we)
                    first_iteration_reg <= first_iteration_new;
                if (b_bit_index_we)
                    b_bit_index_reg <= b_bit_index_new;
                if (bq_we)
                    begin
                        b_reg <= b_new;
                        q_reg <= q_new;
                    end
                if (ready_we)
                    ready_reg <= ready_new;
                if (loop_ctr_we)
                    loop_ctr_reg <= loop_ctr_new;
                if (montprod_ctrl_we)
                    begin
                        montprod_ctrl_reg <= montprod_ctrl_new;
                    end
            end
    end // reg_update
//----------------------------------------------------------------
// s_logic
//
// Logic to calculate S memory updates including address
// and write enable. This is the main montprod datapath.
//----------------------------------------------------------------
always @*
    begin : s_logic
        shr_carry_in_new      = 1'b0;
        muxed_s_mem_read_data = {OPW{1'b0}};
        sa_adder_data_in      = {OPW{1'b0}};
        add_carry_in_sa_new   = 1'b0;
        add_carry_in_sm_new   = 1'b0;
        s_mem_read_addr       = word_index_reg;
        s_mem_write_addr      = s_mem_read_addr_reg;
        s_mem_write_data      = {OPW{1'b0}};
        s_mem_we_new          = 1'b0;
        state_trace           = 0;
        mux_trace             = 0;
        tmp_s_mem_write_data  = {OPW{1'b0}};
        test_new              = 1'b0;
       // Added missing default statement to avoid latches!! Tony Duong 04/01/2020
        shr_data_in = 0;
       
        case (montprod_ctrl_reg)
            CTRL_LOOP_ITER:
                begin
                    s_mem_read_addr = length_m1;
                end
            CTRL_CALC_ADD:
                begin
                    //s = (s + q*M + b*A) >>> 1;, if(b==1) S+= A. Takes (1..length) cycles.
                    s_mem_we_new = b_reg | q_reg | first_iteration_reg;
                    state_trace  = 1;
                    test_new     = 1'b1;
                end
            CTRL_CALC_SDIV2:
                begin
                    //s = (s + q*M + b*A) >>> 1; s>>=1.  Takes (1..length) cycles.
                    s_mem_we_new = 1'b1;
                end
            default:
                begin
                end
        endcase
        case (s_mux_reg)
            SMUX_ADD:
                begin
                    mux_trace = 1;
                    if (first_iteration_reg)
                        muxed_s_mem_read_data = {OPW{1'b0}};
                    else
                        muxed_s_mem_read_data = s_mem_read_data;
                    if (q_reg)
                        sa_adder_data_in = add_result_sm;
                    else
                        sa_adder_data_in = muxed_s_mem_read_data;
                    if (b_reg)
                        tmp_s_mem_write_data = add_result_sa;
                    else if (q_reg)
                        tmp_s_mem_write_data = add_result_sm;
                    else if (first_iteration_reg)
                        tmp_s_mem_write_data = {OPW{1'b0}};
                    s_mem_write_data = tmp_s_mem_write_data;
                    add_carry_in_sa_new = add_carry_out_sa;
                    add_carry_in_sm_new = add_carry_out_sm;
                    // Experimental integration of shift in add.
                    shr_data_in              = tmp_s_mem_write_data;
                    shifted_s_mem_write_data = {shr_carry_out, shr_data_out_reg};
                end
            SMUX_SHR:
                begin
                    shr_data_in      = s_mem_read_data;
                    s_mem_write_data = shr_data_out;
                    shr_carry_in_new = shr_carry_out;
                end
            default:
                begin
                end
        endcase
    end // s_logic
//----------------------------------------------------------------
// bq
//
// Extract b and q bits.
// b: current bit of B used.
// q = (s - b * A) & 1
// update the b bit and word indices based on loop counter.
//----------------------------------------------------------------
always @*
    begin : bq
        b_new = opb_data[b_bit_index_reg];
        if (first_iteration_reg)
            q_new = 1'b0 ^ (opa_data[0] & b_new);
        else
            q_new = s_mem_read_data[0] ^ (opa_data[0] & b_new);
        // B_bit_index      = 5'h1f - loop_counter[4:0];
        b_bit_index_new = ((2**(13 - ADW)) - 1'b1) - loop_ctr_reg[(13 - ADW - 1) : 0];
        b_word_index    = loop_ctr_reg[12 : (13 - ADW)];
    end // bq
//----------------------------------------------------------------
// word_index
//
// Logic that implements the word index used to drive
// addresses for operands.
//----------------------------------------------------------------
always @*
    begin : word_index
        word_index_new = {ADW{1'b0}};
        word_index_we  = 1'b0;
        if (reset_word_index_lsw)
            begin
                word_index_new = length_m1;
                word_index_we  = 1'b1;
            end
        if (reset_word_index_msw)
            begin
                word_index_new = {ADW{1'b0}};
                word_index_we  = 1'b1;
            end
        if (inc_word_index)
            begin
                word_index_new = word_index_reg + 1'b1;
                word_index_we  = 1'b1;
            end
        if (dec_word_index)
            begin
                word_index_new = word_index_reg - 1'b1;
                word_index_we  = 1'b1;
            end
    end // word_index
//----------------------------------------------------------------
// loop_ctr
// Logic for updating the loop counter.
//----------------------------------------------------------------
always @*
    begin : loop_ctr
        loop_ctr_new = 13'h0;
        loop_ctr_we  = 1'b0;
        if (loop_ctr_set)
            begin
                loop_ctr_new = {length, {(13 - ADW){1'b0}}} - 1'b1;
                loop_ctr_we  = 1'b1;
            end
        if (loop_ctr_dec)
            begin
                loop_ctr_new = loop_ctr_reg - 1'b1;
                loop_ctr_we  = 1'b1;
            end
    end
//----------------------------------------------------------------
// montprod_ctrl
//
// Control FSM for the montgomery product calculator.
//----------------------------------------------------------------
always @*
    begin : montprod_ctrl
        ready_new            = 1'b0;
        ready_we             = 1'b0;
        loop_ctr_set         = 1'b0;
        loop_ctr_dec         = 1'b0;
        b_bit_index_we       = 1'b0;
        bq_we                = 1'b0;
        s_mux_new            = SMUX_ZERO;
        dec_word_index       = 1'b0;
        inc_word_index       = 1'b0;
        reset_word_index_lsw = 1'b0;
        reset_word_index_msw = 1'b0;
        first_iteration_new  = 1'b0;
        first_iteration_we   = 1'b0;
        tmp_opa_addr         = word_index_reg;
        tmp_result_we        = 1'b0;
        montprod_ctrl_new    = CTRL_IDLE;
        montprod_ctrl_we     = 1'b0;
        case (montprod_ctrl_reg)
            CTRL_IDLE:
                begin
                    if (calculate)
                        begin
                            first_iteration_new  = 1'b1;
                            first_iteration_we   = 1'b1;
                            ready_new            = 1'b0;
                            ready_we             = 1'b1;
                            reset_word_index_lsw = 1'b1;
                            loop_ctr_set         = 1'b1;
                            montprod_ctrl_new    = CTRL_LOOP_ITER;
                            montprod_ctrl_we     = 1'b1;
                        end
                end
            //calculate q = (s - b * A) & 1;.
            // Also abort loop if done.
            CTRL_LOOP_ITER:
                begin
                    tmp_opa_addr         = length_m1;
                    b_bit_index_we       = 1'b1;
                    montprod_ctrl_new    = CTRL_LOOP_BQ;
                    montprod_ctrl_we     = 1'b1;
                end
            CTRL_LOOP_BQ:
                begin
                    reset_word_index_lsw = 1'b1;
                    bq_we                = 1'b1;
                    montprod_ctrl_new    = CTRL_CALC_ADD;
                    montprod_ctrl_we     = 1'b1;
                end
            CTRL_CALC_ADD:
                begin
                    s_mux_new      = SMUX_ADD;
                    if (word_index_reg == 0)
                        begin
                            reset_word_index_lsw = 1'b1;
                            montprod_ctrl_new    = CTRL_STALLPIPE_ADD;
                            montprod_ctrl_we     = 1'b1;
                        end
                    else
                        begin
                            dec_word_index = 1'b1;
                        end
                end
            CTRL_STALLPIPE_ADD:
                begin
                    first_iteration_new  = 1'b0;
                    first_iteration_we   = 1'b1;
                    reset_word_index_msw = 1'b1;
                    montprod_ctrl_new    = CTRL_CALC_SDIV2;
                    montprod_ctrl_we     = 1'b1;
                end
            CTRL_CALC_SDIV2:
                begin
                    s_mux_new      = SMUX_SHR;
                    if (word_index_reg == length_m1)
                        begin
                            montprod_ctrl_new = CTRL_STALLPIPE_SDIV2;
                            montprod_ctrl_we  = 1'b1;
                        end
                    else
                        inc_word_index = 1'b1;
                end
            CTRL_STALLPIPE_SDIV2:
                begin
                    loop_ctr_dec         = 1'b1;
                    montprod_ctrl_new    = CTRL_LOOP_ITER;
                    montprod_ctrl_we     = 1'b1;
                    reset_word_index_lsw = 1'b1;
                    if (loop_ctr_reg == 0)
                        begin
                            montprod_ctrl_new = CTRL_L_STALLPIPE_ES;
                            montprod_ctrl_we  = 1'b1;
                        end
                end
            CTRL_L_STALLPIPE_ES:
                begin
                    montprod_ctrl_new = CTRL_EMIT_S;
                    montprod_ctrl_we  = 1'b1;
                end
            CTRL_EMIT_S:
                begin
                    dec_word_index = 1'b1;
                    tmp_result_we  = 1'b1;
                    if (word_index_prev_reg == 0)
                        begin
                            ready_new         = 1'b1;
                            ready_we          = 1'b1;
                            montprod_ctrl_new = CTRL_IDLE;
                            montprod_ctrl_we  = 1'b1;
                        end
                end
            default:
                begin
                end
        endcase // case (montprod_ctrl_reg)
    end // montprod_ctrl
endmodule // montprod
          //======================================================================
          // EOF montprod.v
          //======================================================================
 | 
| 
	//======================================================================
//
// residue.v
// ---------
// Modulus 2**2N residue calculator for montgomery calculations.
//
// m_residue_2_2N_array( N, M, Nr)
//   Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
//   for (int i = 0; i < 2 * N; i++)
//     Nr = Nr shift left 1
//     if (Nr less than M) continue;
//     Nr = Nr - M
// return Nr
//
//
//
// Author: Peter Magnusson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module residue #(parameter OPW = 32, parameter ADW = 8)
       (
           input wire                  clk,
           input wire                  reset_n,
           input wire                  calculate,
           output wire                 ready,
           input wire  [14 : 0]        nn, //MAX(2*N)=8192*2 (14 bit)
           input wire  [(ADW - 1) : 0] length,
           output wire [(ADW - 1) : 0] opa_rd_addr,
           input wire  [(OPW - 1) : 0] opa_rd_data,
           output wire [(ADW - 1) : 0] opa_wr_addr,
           output wire [(OPW - 1) : 0] opa_wr_data,
           output wire                 opa_wr_we,
           output wire [(ADW - 1) : 0] opm_addr,
           input wire  [(OPW - 1) : 0] opm_data
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
localparam CTRL_IDLE          = 4'h0;
localparam CTRL_INIT          = 4'h1;
localparam CTRL_INIT_STALL    = 4'h2;
localparam CTRL_SHL           = 4'h3;
localparam CTRL_SHL_STALL     = 4'h4;
localparam CTRL_COMPARE       = 4'h5;
localparam CTRL_COMPARE_STALL = 4'h6;
localparam CTRL_SUB           = 4'h7;
localparam CTRL_SUB_STALL     = 4'h8;
localparam CTRL_LOOP          = 4'h9;
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg [(ADW - 1) : 0]  opa_rd_addr_reg;
reg [(ADW - 1) : 0]  opa_wr_addr_reg;
reg [(OPW - 1) : 0]  opa_wr_data_reg;
reg                  opa_wr_we_reg;
reg [(ADW - 1) : 0]  opm_addr_reg;
reg                  ready_reg;
reg                  ready_new;
reg                  ready_we;
reg [03 : 0]         residue_ctrl_reg;
reg [03 : 0]         residue_ctrl_new;
reg                  residue_ctrl_we;
reg                  reset_word_index;
reg                  reset_n_counter;
reg [14 : 0]         loop_counter_1_to_nn_reg; //for i = 1 to nn (2*N)
reg [14 : 0]         loop_counter_1_to_nn_new;
reg                  loop_counter_1_to_nn_we;
reg [14 : 0]         nn_reg;
reg                  nn_we;
reg [(ADW - 1) : 0]  length_m1_reg;
reg [(ADW - 1) : 0]  length_m1_new;
reg                  length_m1_we;
reg [(ADW - 1) : 0]  word_index_reg;
reg [(ADW - 1) : 0]  word_index_new;
reg                  word_index_we;
reg  [(OPW - 1) : 0] one_data;
wire [(OPW - 1) : 0] sub_data;
wire [(OPW - 1) : 0] shl_data;
reg                  sub_carry_in_new;
reg                  sub_carry_in_reg;
wire                 sub_carry_out;
reg                  shl_carry_in_new;
reg                  shl_carry_in_reg;
wire                 shl_carry_out;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign opa_rd_addr = opa_rd_addr_reg;
assign opa_wr_addr = opa_wr_addr_reg;
assign opa_wr_data = opa_wr_data_reg;
assign opa_wr_we   = opa_wr_we_reg;
assign opm_addr    = opm_addr_reg;
assign ready       = ready_reg;
//----------------------------------------------------------------
// Instantions
//----------------------------------------------------------------
adder #(.OPW(OPW)) add_inst(
          .a(opa_rd_data),
          .b( ~ opm_data),
          .carry_in(sub_carry_in_reg),
          .sum(sub_data),
          .carry_out(sub_carry_out)
      );
shl #(.OPW(OPW)) shl_inst(
        .a(opa_rd_data),
        .carry_in(shl_carry_in_reg),
        .amul2(shl_data),
        .carry_out(shl_carry_out)
    );
//----------------------------------------------------------------
// reg_update
//----------------------------------------------------------------
always @ (posedge clk or negedge reset_n)
    begin
        if (!reset_n)
            begin
                residue_ctrl_reg         <= CTRL_IDLE;
                word_index_reg           <= {ADW{1'b1}};
                length_m1_reg            <= {ADW{1'b1}};
                nn_reg                   <= 15'h0;
                loop_counter_1_to_nn_reg <= 15'h0;
                ready_reg                <= 1'b1;
                sub_carry_in_reg         <= 1'b0;
                shl_carry_in_reg         <= 1'b0;
            end
        else
            begin
                if (residue_ctrl_we)
                    residue_ctrl_reg <= residue_ctrl_new;
                if (word_index_we)
                    word_index_reg <= word_index_new;
                if (length_m1_we)
                    length_m1_reg <= length_m1_new;
                if (nn_we)
                    nn_reg <= nn;
                if (loop_counter_1_to_nn_we)
                    loop_counter_1_to_nn_reg <= loop_counter_1_to_nn_new;
                if (ready_we)
                    ready_reg <= ready_new;
                sub_carry_in_reg <= sub_carry_in_new;
                shl_carry_in_reg <= shl_carry_in_new;
            end
    end // reg_update
//----------------------------------------------------------------
// loop counter process. implements for (int i = 0; i < 2 * N; i++)
//
// m_residue_2_2N_array( N, M, Nr)
//   Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
//   for (int i = 0; i < 2 * N; i++)
//     Nr = Nr shift left 1
//     if (Nr less than M) continue;
//     Nr = Nr - M
// return Nr
//
//----------------------------------------------------------------
always @*
    begin : process_1_to_2n
        loop_counter_1_to_nn_new = loop_counter_1_to_nn_reg + 15'h1;
        loop_counter_1_to_nn_we  = 1'b0;
        if (reset_n_counter)
            begin
                loop_counter_1_to_nn_new = 15'h1;
                loop_counter_1_to_nn_we  = 1'b1;
            end
        if (residue_ctrl_reg == CTRL_LOOP)
            loop_counter_1_to_nn_we  = 1'b1;
    end
//----------------------------------------------------------------
// implements looping over words in a multiword operation
//----------------------------------------------------------------
always @*
    begin : word_index_process
        word_index_new = word_index_reg - 1'b1;
        word_index_we  = 1'b1;
        if (reset_word_index)
            word_index_new = length_m1_reg;
        if (residue_ctrl_reg == CTRL_IDLE)
            //reduce a pipeline stage with early read
            word_index_new = length_m1_new;
    end
//----------------------------------------------------------------
// writer process. implements:
//   Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
//   Nr = Nr shift left 1
//   Nr = Nr - M
//
// m_residue_2_2N_array( N, M, Nr)
//   Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
//   for (int i = 0; i < 2 * N; i++)
//     Nr = Nr shift left 1
//     if (Nr less than M) continue;
//     Nr = Nr - M
// return Nr
//----------------------------------------------------------------
always @*
    begin : writer_process
        opa_wr_addr_reg = word_index_reg;
        case (residue_ctrl_reg)
            CTRL_INIT:
                begin
                    opa_wr_data_reg = one_data;
                    opa_wr_we_reg   = 1'b1;
                end
            CTRL_SUB:
                begin
                    opa_wr_data_reg = sub_data;
                    opa_wr_we_reg   = 1'b1;
                end
            CTRL_SHL:
                begin
                    opa_wr_data_reg = shl_data;
                    opa_wr_we_reg   = 1'b1;
                end
            default:
                begin
                    opa_wr_data_reg = 32'h0;
                    opa_wr_we_reg   = 1'b0;
                end
        endcase
    end
//----------------------------------------------------------------
// reader process. reads from new value because it occurs one
// cycle earlier than the writer.
//----------------------------------------------------------------
always @*
    begin : reader_process
        opa_rd_addr_reg = word_index_new;
        opm_addr_reg    = word_index_new;
    end
//----------------------------------------------------------------
// carry process. "Ripple carry awesomeness!"
//----------------------------------------------------------------
always @*
    begin : carry_process
        case (residue_ctrl_reg)
            CTRL_COMPARE:
                sub_carry_in_new = sub_carry_out;
            CTRL_SUB:
                sub_carry_in_new = sub_carry_out;
            default:
                sub_carry_in_new = 1'b1;
        endcase
        case (residue_ctrl_reg)
            CTRL_SHL:
                shl_carry_in_new = shl_carry_out;
            default:
                shl_carry_in_new = 1'b0;
        endcase
    end
//----------------------------------------------------------------
// Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
//----------------------------------------------------------------
always @*
    begin : one_process
        one_data = 32'h0;
        if (residue_ctrl_reg == CTRL_INIT)
            if (word_index_reg == length_m1_reg)
                one_data = {{(OPW - 1){1'b0}}, 1'b1};
    end
//----------------------------------------------------------------
// residue_ctrl
//
// Control FSM for residue
//----------------------------------------------------------------
always @*
    begin : residue_ctrl
        ready_new        = 1'b0;
        ready_we         = 1'b0;
        reset_word_index = 1'b0;
        reset_n_counter  = 1'b0;
        length_m1_new    = length - 1'b1;
        length_m1_we     = 1'b0;
        nn_we            = 1'b0;
        residue_ctrl_new = CTRL_IDLE;
        residue_ctrl_we  = 1'b0;
        case (residue_ctrl_reg)
            CTRL_IDLE:
                if (calculate)
                    begin
                        ready_new        = 1'b0;
                        ready_we         = 1'b1;
                        reset_word_index = 1'b1;
                        length_m1_we     = 1'b1;
                        nn_we            = 1'b1;
                        residue_ctrl_new = CTRL_INIT;
                        residue_ctrl_we  = 1'b1;
                    end
            // Nr = 00...01 ; Nr = 1 == 2**(2N-2N)
            CTRL_INIT:
                if (word_index_reg == 0)
                    begin
                        residue_ctrl_new = CTRL_INIT_STALL;
                        residue_ctrl_we  = 1'b1;
                    end
            CTRL_INIT_STALL:
                begin
                    reset_word_index = 1'b1;
                    reset_n_counter  = 1'b1;
                    residue_ctrl_new = CTRL_SHL;
                    residue_ctrl_we  = 1'b1;
                end
            // Nr = Nr shift left 1
            CTRL_SHL:
                begin
                    if (word_index_reg == 0)
                        begin
                            residue_ctrl_new = CTRL_SHL_STALL;
                            residue_ctrl_we  = 1'b1;
                        end
                end
            CTRL_SHL_STALL:
                begin
                    reset_word_index = 1'b1;
                    residue_ctrl_new = CTRL_COMPARE;
                    residue_ctrl_we  = 1'b1;
                end
            //if (Nr less than M) continue
            CTRL_COMPARE:
                if (word_index_reg == 0)
                    begin
                        residue_ctrl_new = CTRL_COMPARE_STALL;
                        residue_ctrl_we  = 1'b1;
                    end
            CTRL_COMPARE_STALL:
                begin
                    reset_word_index = 1'b1;
                    residue_ctrl_we  = 1'b1;
                    if (sub_carry_in_reg == 1'b1)
                        //TODO: Bug! detect CF to detect less than, but no detect ZF to detect equal to.
                        residue_ctrl_new = CTRL_SUB;
                    else
                        residue_ctrl_new = CTRL_LOOP;
                end
            //Nr = Nr - M
            CTRL_SUB:
                if (word_index_reg == 0)
                    begin
                        residue_ctrl_new = CTRL_SUB_STALL;
                        residue_ctrl_we  = 1'b1;
                    end
            CTRL_SUB_STALL:
                begin
                    residue_ctrl_new = CTRL_LOOP;
                    residue_ctrl_we  = 1'b1;
                end
            //for (int i = 0; i < 2 * N; i++)
            CTRL_LOOP:
                begin
                    if (loop_counter_1_to_nn_reg == nn_reg)
                        begin
                            ready_new = 1'b1;
                            ready_we  = 1'b1;
                            residue_ctrl_new = CTRL_IDLE;
                            residue_ctrl_we  = 1'b1;
                        end
                    else
                        begin
                            reset_word_index = 1'b1;
                            residue_ctrl_new = CTRL_SHL;
                            residue_ctrl_we  = 1'b1;
                        end
                end
            default:
                begin
                end
        endcase
    end
endmodule // residue
          //======================================================================
          // EOF residue.v
          //======================================================================
 | 
| 
	//======================================================================
//
// shl.v
// -----
// One bit left shift of words with carry in and carry out. Used in
// the residue module of the modexp core.
//
//
// Author: Peter Magnusson, Joachim Strömbergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module shl #(parameter OPW = 32)
       (
           input  wire [(OPW - 1) : 0] a,
           input  wire                 carry_in,
           output wire [(OPW - 1) : 0] amul2,
           output wire                 carry_out
       );
assign amul2     = {a[(OPW - 2) : 0], carry_in};
assign carry_out = a[(OPW - 1)];
endmodule // shl
          //======================================================================
          // EOF shl.v
          //======================================================================
 | 
| 
	//======================================================================
//
// shr32.v
// -------
// One bit right shift with carry in and carry out.
// Used in the montprod module of the modexp core.
//
//
// Author: Peter Magnusson, Joachim Strömbergson
// Copyright (c) 2015, NORDUnet A/S All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// - Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// - Neither the name of the NORDUnet nor the names of its contributors may
//   be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module shr #(parameter OPW = 32)
       (
           input wire  [(OPW - 1) : 0] a,
           input wire                  carry_in,
           output wire [(OPW - 1) : 0] adiv2,
           output wire                 carry_out
       );
assign adiv2      = {carry_in, a[(OPW - 1) : 1]};
assign carry_out = a[0];
endmodule // shr
          //======================================================================
          // EOF shr.v
          //======================================================================
 | 
| 
	//======================================================================
//
// sha256_core.v
// -------------
// Verilog 2001 implementation of the SHA-256 hash function.
// This is the internal core with wide interfaces.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2013, Secworks Sweden AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following
// conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
// Modified by Matthew Hicks:
//   Convert to synchronous, positive level reset
//   Fix at 256-bit mode
module sha256(
           input wire            clk,
           input wire            rst,
           input wire            init,
           input wire            next,
           input wire [511 : 0]  block,
           output wire           ready,
           output wire [255 : 0] digest,
           output wire           digest_valid
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
parameter SHA256_H0_0 = 32'h6a09e667;
parameter SHA256_H0_1 = 32'hbb67ae85;
parameter SHA256_H0_2 = 32'h3c6ef372;
parameter SHA256_H0_3 = 32'ha54ff53a;
parameter SHA256_H0_4 = 32'h510e527f;
parameter SHA256_H0_5 = 32'h9b05688c;
parameter SHA256_H0_6 = 32'h1f83d9ab;
parameter SHA256_H0_7 = 32'h5be0cd19;
parameter SHA256_ROUNDS = 63;
parameter CTRL_IDLE   = 0;
parameter CTRL_ROUNDS = 1;
parameter CTRL_DONE   = 2;
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg [31 : 0] a_reg;
reg [31 : 0] a_new;
reg [31 : 0] b_reg;
reg [31 : 0] b_new;
reg [31 : 0] c_reg;
reg [31 : 0] c_new;
reg [31 : 0] d_reg;
reg [31 : 0] d_new;
reg [31 : 0] e_reg;
reg [31 : 0] e_new;
reg [31 : 0] f_reg;
reg [31 : 0] f_new;
reg [31 : 0] g_reg;
reg [31 : 0] g_new;
reg [31 : 0] h_reg;
reg [31 : 0] h_new;
reg          a_h_we;
reg [31 : 0] H0_reg;
reg [31 : 0] H0_new;
reg [31 : 0] H1_reg;
reg [31 : 0] H1_new;
reg [31 : 0] H2_reg;
reg [31 : 0] H2_new;
reg [31 : 0] H3_reg;
reg [31 : 0] H3_new;
reg [31 : 0] H4_reg;
reg [31 : 0] H4_new;
reg [31 : 0] H5_reg;
reg [31 : 0] H5_new;
reg [31 : 0] H6_reg;
reg [31 : 0] H6_new;
reg [31 : 0] H7_reg;
reg [31 : 0] H7_new;
reg          H_we;
reg [5 : 0] t_ctr_reg;
reg [5 : 0] t_ctr_new;
reg         t_ctr_we;
reg         t_ctr_inc;
reg         t_ctr_rst;
reg digest_valid_reg;
reg digest_valid_new;
reg digest_valid_we;
reg [1 : 0] sha256_ctrl_reg;
reg [1 : 0] sha256_ctrl_new;
reg         sha256_ctrl_we;
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
reg digest_init;
reg digest_update;
reg state_init;
reg state_update;
reg first_block;
reg ready_flag;
reg [31 : 0] t1;
reg [31 : 0] t2;
wire [31 : 0] k_data;
reg           w_init;
reg           w_next;
wire [31 : 0] w_data;
//----------------------------------------------------------------
// Module instantiantions.
//----------------------------------------------------------------
sha256_k_constants k_constants_inst(
                       .addr(t_ctr_reg),
                       .K(k_data)
                   );
sha256_w_mem w_mem_inst(
                 .clk(clk),
                 .rst(rst),
                 .block(block),
                 .init(w_init),
                 .next(w_next),
                 .w(w_data)
             );
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign ready = ready_flag;
assign digest = {H0_reg, H1_reg, H2_reg, H3_reg,
                 H4_reg, H5_reg, H6_reg, H7_reg};
assign digest_valid = digest_valid_reg;
//----------------------------------------------------------------
// reg_update
// Update functionality for all registers in the core.
// All registers are positive edge triggered with synchronous
// reset. All registers have write enable.
//----------------------------------------------------------------
always @ (posedge clk)
    begin : reg_update
        if (rst)
            begin
                a_reg            <= 32'h0;
                b_reg            <= 32'h0;
                c_reg            <= 32'h0;
                d_reg            <= 32'h0;
                e_reg            <= 32'h0;
                f_reg            <= 32'h0;
                g_reg            <= 32'h0;
                h_reg            <= 32'h0;
                H0_reg           <= 32'h0;
                H1_reg           <= 32'h0;
                H2_reg           <= 32'h0;
                H3_reg           <= 32'h0;
                H4_reg           <= 32'h0;
                H5_reg           <= 32'h0;
                H6_reg           <= 32'h0;
                H7_reg           <= 32'h0;
                digest_valid_reg <= 0;
                t_ctr_reg        <= 6'h0;
                sha256_ctrl_reg  <= CTRL_IDLE;
            end
        else
            begin
                if (a_h_we)
                    begin
                        a_reg <= a_new;
                        b_reg <= b_new;
                        c_reg <= c_new;
                        d_reg <= d_new;
                        e_reg <= e_new;
                        f_reg <= f_new;
                        g_reg <= g_new;
                        h_reg <= h_new;
                    end
                if (H_we)
                    begin
                        H0_reg <= H0_new;
                        H1_reg <= H1_new;
                        H2_reg <= H2_new;
                        H3_reg <= H3_new;
                        H4_reg <= H4_new;
                        H5_reg <= H5_new;
                        H6_reg <= H6_new;
                        H7_reg <= H7_new;
                    end
                if (t_ctr_we)
                    t_ctr_reg <= t_ctr_new;
                if (digest_valid_we)
                    digest_valid_reg <= digest_valid_new;
                if (sha256_ctrl_we)
                    sha256_ctrl_reg <= sha256_ctrl_new;
            end
    end // reg_update
//----------------------------------------------------------------
// digest_logic
//
// The logic needed to init as well as update the digest.
//----------------------------------------------------------------
always @*
    begin : digest_logic
        H0_new = 32'h0;
        H1_new = 32'h0;
        H2_new = 32'h0;
        H3_new = 32'h0;
        H4_new = 32'h0;
        H5_new = 32'h0;
        H6_new = 32'h0;
        H7_new = 32'h0;
        H_we = 0;
        if (digest_init)
            begin
                H_we = 1;
                H0_new = SHA256_H0_0;
                H1_new = SHA256_H0_1;
                H2_new = SHA256_H0_2;
                H3_new = SHA256_H0_3;
                H4_new = SHA256_H0_4;
                H5_new = SHA256_H0_5;
                H6_new = SHA256_H0_6;
                H7_new = SHA256_H0_7;
            end
        if (digest_update)
            begin
                H0_new = H0_reg + a_reg;
                H1_new = H1_reg + b_reg;
                H2_new = H2_reg + c_reg;
                H3_new = H3_reg + d_reg;
                H4_new = H4_reg + e_reg;
                H5_new = H5_reg + f_reg;
                H6_new = H6_reg + g_reg;
                H7_new = H7_reg + h_reg;
                H_we = 1;
            end
    end // digest_logic
//----------------------------------------------------------------
// t1_logic
//
// The logic for the T1 function.
//----------------------------------------------------------------
always @*
    begin : t1_logic
        reg [31 : 0] sum1;
        reg [31 : 0] ch;
        sum1 = {e_reg[5  : 0], e_reg[31 :  6]} ^
             {e_reg[10 : 0], e_reg[31 : 11]} ^
             {e_reg[24 : 0], e_reg[31 : 25]};
        ch = (e_reg & f_reg) ^ ((~e_reg) & g_reg);
        t1 = h_reg + sum1 + ch + w_data + k_data;
    end // t1_logic
//----------------------------------------------------------------
// t2_logic
//
// The logic for the T2 function
//----------------------------------------------------------------
always @*
    begin : t2_logic
        reg [31 : 0] sum0;
        reg [31 : 0] maj;
        sum0 = {a_reg[1  : 0], a_reg[31 :  2]} ^
             {a_reg[12 : 0], a_reg[31 : 13]} ^
             {a_reg[21 : 0], a_reg[31 : 22]};
        maj = (a_reg & b_reg) ^ (a_reg & c_reg) ^ (b_reg & c_reg);
        t2 = sum0 + maj;
    end // t2_logic
//----------------------------------------------------------------
// state_logic
//
// The logic needed to init as well as update the state during
// round processing.
//----------------------------------------------------------------
always @*
    begin : state_logic
        a_new  = 32'h0;
        b_new  = 32'h0;
        c_new  = 32'h0;
        d_new  = 32'h0;
        e_new  = 32'h0;
        f_new  = 32'h0;
        g_new  = 32'h0;
        h_new  = 32'h0;
        a_h_we = 0;
        if (state_init)
            begin
                a_h_we = 1;
                if (first_block)
                    begin
                        a_new  = SHA256_H0_0;
                        b_new  = SHA256_H0_1;
                        c_new  = SHA256_H0_2;
                        d_new  = SHA256_H0_3;
                        e_new  = SHA256_H0_4;
                        f_new  = SHA256_H0_5;
                        g_new  = SHA256_H0_6;
                        h_new  = SHA256_H0_7;
                    end
                else
                    begin
                        a_new  = H0_reg;
                        b_new  = H1_reg;
                        c_new  = H2_reg;
                        d_new  = H3_reg;
                        e_new  = H4_reg;
                        f_new  = H5_reg;
                        g_new  = H6_reg;
                        h_new  = H7_reg;
                    end
            end
        if (state_update)
            begin
                a_new  = t1 + t2;
                b_new  = a_reg;
                c_new  = b_reg;
                d_new  = c_reg;
                e_new  = d_reg + t1;
                f_new  = e_reg;
                g_new  = f_reg;
                h_new  = g_reg;
                a_h_we = 1;
            end
    end // state_logic
//----------------------------------------------------------------
// t_ctr
//
// Update logic for the round counter, a monotonically
// increasing counter with reset.
//----------------------------------------------------------------
always @*
    begin : t_ctr
        t_ctr_new = 0;
        t_ctr_we  = 0;
        if (t_ctr_rst)
            begin
                t_ctr_new = 0;
                t_ctr_we  = 1;
            end
        if (t_ctr_inc)
            begin
                t_ctr_new = t_ctr_reg + 1'b1;
                t_ctr_we  = 1;
            end
    end // t_ctr
//----------------------------------------------------------------
// sha256_ctrl_fsm
//
// Logic for the state machine controlling the core behaviour.
//----------------------------------------------------------------
always @*
    begin : sha256_ctrl_fsm
        digest_init      = 0;
        digest_update    = 0;
        state_init       = 0;
        state_update     = 0;
        first_block      = 0;
        ready_flag       = 0;
        w_init           = 0;
        w_next           = 0;
        t_ctr_inc        = 0;
        t_ctr_rst        = 0;
        digest_valid_new = 0;
        digest_valid_we  = 0;
        sha256_ctrl_new  = CTRL_IDLE;
        sha256_ctrl_we   = 0;
        case (sha256_ctrl_reg)
            CTRL_IDLE:
                begin
                    ready_flag = 1;
                    if (init)
                        begin
                            digest_init      = 1;
                            w_init           = 1;
                            state_init       = 1;
                            first_block      = 1;
                            t_ctr_rst        = 1;
                            digest_valid_new = 0;
                            digest_valid_we  = 1;
                            sha256_ctrl_new  = CTRL_ROUNDS;
                            sha256_ctrl_we   = 1;
                        end
                    if (next)
                        begin
                            t_ctr_rst        = 1;
                            w_init           = 1;
                            state_init       = 1;
                            digest_valid_new = 0;
                            digest_valid_we  = 1;
                            sha256_ctrl_new  = CTRL_ROUNDS;
                            sha256_ctrl_we   = 1;
                        end
                end
            CTRL_ROUNDS:
                begin
                    w_next       = 1;
                    state_update = 1;
                    t_ctr_inc    = 1;
                    if (t_ctr_reg == SHA256_ROUNDS)
                        begin
                            sha256_ctrl_new = CTRL_DONE;
                            sha256_ctrl_we  = 1;
                        end
                end
            CTRL_DONE:
                begin
                    digest_update    = 1;
                    digest_valid_new = 1;
                    digest_valid_we  = 1;
                    sha256_ctrl_new  = CTRL_IDLE;
                    sha256_ctrl_we   = 1;
                end
        endcase // case (sha256_ctrl_reg)
    end // sha256_ctrl_fsm
endmodule // sha256_core
          //======================================================================
          // EOF sha256_core.v
          //======================================================================
 | 
| 
	//======================================================================
//
// sha256_k_constants.v
// --------------------
// The table K with constants in the SHA-256 hash function.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2013, Secworks Sweden AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following
// conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module sha256_k_constants(
           input wire  [5 : 0] addr,
           output wire [31 : 0] K
       );
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
reg [31 : 0] tmp_K;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign K = tmp_K;
//----------------------------------------------------------------
// addr_mux
//----------------------------------------------------------------
always @*
    begin : addr_mux
        case(addr)
            00:
                tmp_K = 32'h428a2f98;
            01:
                tmp_K = 32'h71374491;
            02:
                tmp_K = 32'hb5c0fbcf;
            03:
                tmp_K = 32'he9b5dba5;
            04:
                tmp_K = 32'h3956c25b;
            05:
                tmp_K = 32'h59f111f1;
            06:
                tmp_K = 32'h923f82a4;
            07:
                tmp_K = 32'hab1c5ed5;
            08:
                tmp_K = 32'hd807aa98;
            09:
                tmp_K = 32'h12835b01;
            10:
                tmp_K = 32'h243185be;
            11:
                tmp_K = 32'h550c7dc3;
            12:
                tmp_K = 32'h72be5d74;
            13:
                tmp_K = 32'h80deb1fe;
            14:
                tmp_K = 32'h9bdc06a7;
            15:
                tmp_K = 32'hc19bf174;
            16:
                tmp_K = 32'he49b69c1;
            17:
                tmp_K = 32'hefbe4786;
            18:
                tmp_K = 32'h0fc19dc6;
            19:
                tmp_K = 32'h240ca1cc;
            20:
                tmp_K = 32'h2de92c6f;
            21:
                tmp_K = 32'h4a7484aa;
            22:
                tmp_K = 32'h5cb0a9dc;
            23:
                tmp_K = 32'h76f988da;
            24:
                tmp_K = 32'h983e5152;
            25:
                tmp_K = 32'ha831c66d;
            26:
                tmp_K = 32'hb00327c8;
            27:
                tmp_K = 32'hbf597fc7;
            28:
                tmp_K = 32'hc6e00bf3;
            29:
                tmp_K = 32'hd5a79147;
            30:
                tmp_K = 32'h06ca6351;
            31:
                tmp_K = 32'h14292967;
            32:
                tmp_K = 32'h27b70a85;
            33:
                tmp_K = 32'h2e1b2138;
            34:
                tmp_K = 32'h4d2c6dfc;
            35:
                tmp_K = 32'h53380d13;
            36:
                tmp_K = 32'h650a7354;
            37:
                tmp_K = 32'h766a0abb;
            38:
                tmp_K = 32'h81c2c92e;
            39:
                tmp_K = 32'h92722c85;
            40:
                tmp_K = 32'ha2bfe8a1;
            41:
                tmp_K = 32'ha81a664b;
            42:
                tmp_K = 32'hc24b8b70;
            43:
                tmp_K = 32'hc76c51a3;
            44:
                tmp_K = 32'hd192e819;
            45:
                tmp_K = 32'hd6990624;
            46:
                tmp_K = 32'hf40e3585;
            47:
                tmp_K = 32'h106aa070;
            48:
                tmp_K = 32'h19a4c116;
            49:
                tmp_K = 32'h1e376c08;
            50:
                tmp_K = 32'h2748774c;
            51:
                tmp_K = 32'h34b0bcb5;
            52:
                tmp_K = 32'h391c0cb3;
            53:
                tmp_K = 32'h4ed8aa4a;
            54:
                tmp_K = 32'h5b9cca4f;
            55:
                tmp_K = 32'h682e6ff3;
            56:
                tmp_K = 32'h748f82ee;
            57:
                tmp_K = 32'h78a5636f;
            58:
                tmp_K = 32'h84c87814;
            59:
                tmp_K = 32'h8cc70208;
            60:
                tmp_K = 32'h90befffa;
            61:
                tmp_K = 32'ha4506ceb;
            62:
                tmp_K = 32'hbef9a3f7;
            63:
                tmp_K = 32'hc67178f2;
        endcase // case (addr)
    end // block: addr_mux
endmodule // sha256_k_constants
          //======================================================================
          // sha256_k_constants.v
          //======================================================================
 | 
| 
	//************************************************************************
// Copyright 2022 Massachusets Institute of Technology
// SPDX License Identifier: BSD-2-Clause
//
// File Name:       sha256_mock_tss.sv
// Program:         Common Evaluation Platform (CEP)
// Description:     
// Notes:           
//************************************************************************
`timescale 1ns/1ns
module sha256_mock_tss import llki_pkg::*; (
    // Clock and Reset
    input wire            clk,
    input wire            rst,
    // Core I/O
    input wire            init,
    input wire            next,
    input wire [511 : 0]  block,
    output wire           ready,
    output wire [255 : 0] digest,
    output wire           digest_valid,
    // LLKI Discrete I/O
    input [63:0]          llkid_key_data,
    input                 llkid_key_valid,
    output reg            llkid_key_ready,
    output reg            llkid_key_complete,
    input                 llkid_clear_key,
    output reg            llkid_clear_key_ack
);
  // Internal signals & localparams
  localparam KEY_WORDS          = SHA256_MOCK_TSS_NUM_KEY_WORDS;
  reg [(64*KEY_WORDS) - 1:0]    llkid_key_register;
  wire [(64*KEY_WORDS) - 1:0]   mock_tss_block;
  //------------------------------------------------------------------
  // Instantiate the Mock TSS Finite State Machine
  //------------------------------------------------------------------
  mock_tss_fsm #(
    .KEY_WORDS            (KEY_WORDS)
  ) mock_tss_fsm_inst (
    .clk                  (clk),
    .rst                  (rst),
    .llkid_key_data       (llkid_key_data),
    .llkid_key_valid      (llkid_key_valid),
    .llkid_key_ready      (llkid_key_ready),
    .llkid_key_complete   (llkid_key_complete),
    .llkid_clear_key      (llkid_clear_key),
    .llkid_clear_key_ack  (llkid_clear_key_ack),
    .llkid_key_register   (llkid_key_register)
  );
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Create the Mock TSS input into the original core
  //------------------------------------------------------------------
  genvar i;
  generate
    for (i = 0; i < KEY_WORDS; i = i + 1) begin
      assign mock_tss_block[64*i +: 64] = SHA256_MOCK_TSS_KEY_WORDS[i] ^
                                          llkid_key_register[64*i +: 64] ^
                                          block[64*i +: 64];
    end
  endgenerate
  //------------------------------------------------------------------
  //------------------------------------------------------------------
  // Instantiate the original core
  //------------------------------------------------------------------
  sha256 sha256_inst (
    .clk          (clk),
    .rst          (rst),
    .init         (init),
    .next         (next),
    .block        (mock_tss_block),
    .ready        (ready),
    .digest       (digest),
    .digest_valid (digest_valid)
  );
  //------------------------------------------------------------------
endmodule
 | 
| 
	//======================================================================
//
// sha256_w_mem_regs.v
// -------------------
// The W memory. This version uses 16 32-bit registers as a sliding
// window to generate the 64 words.
//
//
// Author: Joachim Strombergson
// Copyright (c) 2013, Secworks Sweden AB
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following
// conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materials provided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//======================================================================
module sha256_w_mem(
           input wire           clk,
           input wire           rst,
           input wire [511 : 0] block,
           input wire           init,
           input wire           next,
           output wire [31 : 0] w
       );
//----------------------------------------------------------------
// Internal constant and parameter definitions.
//----------------------------------------------------------------
parameter CTRL_IDLE   = 0;
parameter CTRL_UPDATE = 1;
//----------------------------------------------------------------
// Registers including update variables and write enable.
//----------------------------------------------------------------
reg [31 : 0] w_mem [0 : 15];
reg [31 : 0] w_mem00_new;
reg [31 : 0] w_mem01_new;
reg [31 : 0] w_mem02_new;
reg [31 : 0] w_mem03_new;
reg [31 : 0] w_mem04_new;
reg [31 : 0] w_mem05_new;
reg [31 : 0] w_mem06_new;
reg [31 : 0] w_mem07_new;
reg [31 : 0] w_mem08_new;
reg [31 : 0] w_mem09_new;
reg [31 : 0] w_mem10_new;
reg [31 : 0] w_mem11_new;
reg [31 : 0] w_mem12_new;
reg [31 : 0] w_mem13_new;
reg [31 : 0] w_mem14_new;
reg [31 : 0] w_mem15_new;
reg          w_mem_we;
reg [5 : 0] w_ctr_reg;
reg [5 : 0] w_ctr_new;
reg         w_ctr_we;
reg         w_ctr_inc;
reg         w_ctr_rst;
reg [1 : 0]  sha256_w_mem_ctrl_reg;
reg [1 : 0]  sha256_w_mem_ctrl_new;
reg          sha256_w_mem_ctrl_we;
//----------------------------------------------------------------
// Wires.
//----------------------------------------------------------------
reg [31 : 0] w_tmp;
reg [31 : 0] w_new;
//----------------------------------------------------------------
// Concurrent connectivity for ports etc.
//----------------------------------------------------------------
assign w = w_tmp;
//----------------------------------------------------------------
// reg_update
// Update functionality for all registers in the core.
// All registers are positive edge triggered with synchronous
// reset. All registers have write enable.
//----------------------------------------------------------------
always @ (posedge clk)
    begin : reg_update
        if (rst)
            begin
                w_mem[00]             <= 32'h0;
                w_mem[01]             <= 32'h0;
                w_mem[02]             <= 32'h0;
                w_mem[03]             <= 32'h0;
                w_mem[04]             <= 32'h0;
                w_mem[05]             <= 32'h0;
                w_mem[06]             <= 32'h0;
                w_mem[07]             <= 32'h0;
                w_mem[08]             <= 32'h0;
                w_mem[09]             <= 32'h0;
                w_mem[10]             <= 32'h0;
                w_mem[11]             <= 32'h0;
                w_mem[12]             <= 32'h0;
                w_mem[13]             <= 32'h0;
                w_mem[14]             <= 32'h0;
                w_mem[15]             <= 32'h0;
                w_ctr_reg             <= 6'h00;
                sha256_w_mem_ctrl_reg <= CTRL_IDLE;
            end
        else
            begin
                if (w_mem_we)
                    begin
                        w_mem[00] <= w_mem00_new;
                        w_mem[01] <= w_mem01_new;
                        w_mem[02] <= w_mem02_new;
                        w_mem[03] <= w_mem03_new;
                        w_mem[04] <= w_mem04_new;
                        w_mem[05] <= w_mem05_new;
                        w_mem[06] <= w_mem06_new;
                        w_mem[07] <= w_mem07_new;
                        w_mem[08] <= w_mem08_new;
                        w_mem[09] <= w_mem09_new;
                        w_mem[10] <= w_mem10_new;
                        w_mem[11] <= w_mem11_new;
                        w_mem[12] <= w_mem12_new;
                        w_mem[13] <= w_mem13_new;
                        w_mem[14] <= w_mem14_new;
                        w_mem[15] <= w_mem15_new;
                    end
                if (w_ctr_we)
                    w_ctr_reg <= w_ctr_new;
                if (sha256_w_mem_ctrl_we)
                    sha256_w_mem_ctrl_reg <= sha256_w_mem_ctrl_new;
            end
    end // reg_update
//----------------------------------------------------------------
// select_w
//
// Mux for the external read operation. This is where we exract
// the W variable.
//----------------------------------------------------------------
always @*
    begin : select_w
        if (w_ctr_reg < 16)
            begin
                w_tmp = w_mem[w_ctr_reg[3 : 0]];
            end
        else
            begin
                w_tmp = w_new;
            end
    end // select_w
//----------------------------------------------------------------
// w_new_logic
//
// Logic that calculates the next value to be inserted into
// the sliding window of the memory.
//----------------------------------------------------------------
always @*
    begin : w_mem_update_logic
        reg [31 : 0] w_0;
        reg [31 : 0] w_1;
        reg [31 : 0] w_9;
        reg [31 : 0] w_14;
        reg [31 : 0] d0;
        reg [31 : 0] d1;
        w_mem00_new = 32'h0;
        w_mem01_new = 32'h0;
        w_mem02_new = 32'h0;
        w_mem03_new = 32'h0;
        w_mem04_new = 32'h0;
        w_mem05_new = 32'h0;
        w_mem06_new = 32'h0;
        w_mem07_new = 32'h0;
        w_mem08_new = 32'h0;
        w_mem09_new = 32'h0;
        w_mem10_new = 32'h0;
        w_mem11_new = 32'h0;
        w_mem12_new = 32'h0;
        w_mem13_new = 32'h0;
        w_mem14_new = 32'h0;
        w_mem15_new = 32'h0;
        w_mem_we    = 0;
        w_0  = w_mem[0];
        w_1  = w_mem[1];
        w_9  = w_mem[9];
        w_14 = w_mem[14];
        d0 = {w_1[6  : 0], w_1[31 :  7]} ^
           {w_1[17 : 0], w_1[31 : 18]} ^
           {3'b000, w_1[31 : 3]};
        d1 = {w_14[16 : 0], w_14[31 : 17]} ^
           {w_14[18 : 0], w_14[31 : 19]} ^
           {10'b0000000000, w_14[31 : 10]};
        w_new = d1 + w_9 + d0 + w_0;
        if (init)
            begin
                w_mem00_new = block[511 : 480];
                w_mem01_new = block[479 : 448];
                w_mem02_new = block[447 : 416];
                w_mem03_new = block[415 : 384];
                w_mem04_new = block[383 : 352];
                w_mem05_new = block[351 : 320];
                w_mem06_new = block[319 : 288];
                w_mem07_new = block[287 : 256];
                w_mem08_new = block[255 : 224];
                w_mem09_new = block[223 : 192];
                w_mem10_new = block[191 : 160];
                w_mem11_new = block[159 : 128];
                w_mem12_new = block[127 :  96];
                w_mem13_new = block[95  :  64];
                w_mem14_new = block[63  :  32];
                w_mem15_new = block[31  :   0];
                w_mem_we    = 1;
            end
        else if (w_ctr_reg > 15)
            begin
                w_mem00_new = w_mem[01];
                w_mem01_new = w_mem[02];
                w_mem02_new = w_mem[03];
                w_mem03_new = w_mem[04];
                w_mem04_new = w_mem[05];
                w_mem05_new = w_mem[06];
                w_mem06_new = w_mem[07];
                w_mem07_new = w_mem[08];
                w_mem08_new = w_mem[09];
                w_mem09_new = w_mem[10];
                w_mem10_new = w_mem[11];
                w_mem11_new = w_mem[12];
                w_mem12_new = w_mem[13];
                w_mem13_new = w_mem[14];
                w_mem14_new = w_mem[15];
                w_mem15_new = w_new;
                w_mem_we    = 1;
            end
    end // w_mem_update_logic
//----------------------------------------------------------------
// w_ctr
// W schedule adress counter. Counts from 0x10 to 0x3f and
// is used to expand the block into words.
//----------------------------------------------------------------
always @*
    begin : w_ctr
        w_ctr_new = 0;
        w_ctr_we  = 0;
        if (w_ctr_rst)
            begin
                w_ctr_new = 6'h00;
                w_ctr_we  = 1;
            end
        if (w_ctr_inc)
            begin
                w_ctr_new = w_ctr_reg + 6'h01;
                w_ctr_we  = 1;
            end
    end // w_ctr
//----------------------------------------------------------------
// sha256_w_mem_fsm
// Logic for the w shedule FSM.
//----------------------------------------------------------------
always @*
    begin : sha256_w_mem_fsm
        w_ctr_rst = 0;
        w_ctr_inc = 0;
        sha256_w_mem_ctrl_new = CTRL_IDLE;
        sha256_w_mem_ctrl_we  = 0;
        case (sha256_w_mem_ctrl_reg)
            CTRL_IDLE:
                begin
                    if (init)
                        begin
                            w_ctr_rst             = 1;
                            sha256_w_mem_ctrl_new = CTRL_UPDATE;
                            sha256_w_mem_ctrl_we  = 1;
                        end
                end
            CTRL_UPDATE:
                begin
                    if (next)
                        begin
                            w_ctr_inc = 1;
                        end
                    if (w_ctr_reg == 6'h3f)
                        begin
                            sha256_w_mem_ctrl_new = CTRL_IDLE;
                            sha256_w_mem_ctrl_we  = 1;
                        end
                end
        endcase // case (sha256_ctrl_reg)
    end // sha256_ctrl_fsm
endmodule // sha256_w_mem
          //======================================================================
          // sha256_w_mem.v
          //======================================================================
 | 
| 
	[//]: # (Copyright 2022 Massachusets Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   Copyright 2022 Massachusets Institute of Technology
</p>
## SHAAA - Secure Hash Algorithm, Arbitrarily Augmented
The shaaa_verilog_generator.py script generates randomized variants of SHA2 algorithms.
Executing `shaaa_verilog_generator.py -h` will print a complete list of script options.
Example usage:
```
    ./shaaa_verilog_gen.py --random256 -o gen_256_a
        ^   Generate a 256 bit output SHAAA module, save in the gen_256_a folder. All 
            constants are randomly selected, and the IO are the same size as standard 
            SHA256.
    
    ./shaaa_verilog_gen.py --config config.json 
        ^   Generate a SHAAA module based on the specification in config.json
```
Generated outputs:
```
    .gitignore           - Automatically ignore the entire output directory. Only
                           generated if it doesn't already exist.
    config.json          - Copy of the configuration used to generate the verilog, 
                           can be used as the --config input.
    shaaa_k_constants.v  - K constants
    shaaa_stimulus.v     - Stimulus for shaaa_tb.sv
    shaaa_tb.sv          - Main testbench, not LLKI enabled.
    shaaa_w_mem.v        - Rolling W memory
    shaaa.v              - Top level SHAAA module
```
### SHAAA Configuration
SHAAA is based on the SHA2 family, and supports the following configuration parameters:
| Name                  | Range                         | Description                              |
|-----------------------|-------------------------------|------------------------------------------|
| WORDSIZE              | 32,64                         | Size of each word, in bits               |
| BLOCKSIZE             | 512,1024 (Must be 16*WORDSIZE)| Size of each hash block, in bits         |
| DIGESTBITS            | 1 <= DIGESTBITS <= 8*WORDSIZE | Cropped output size. 256 for SHA256, etc.|
| ITERATIONS            | >=1                           | Number of iterations for each block. Randomizer picks value in range [64, 127] |
| H0                    | [WORD]x8                      | Initial H register values.               |
| K                     | [WORD]xITERATIONS             | K constants to use for each round.       |
| W_SUMS                | [1<=z<=16]xRANDOM             | Random sampling of integers from 1 to 16. Used as the "sum" terms for W generation. The randomizer selects 2-4 values, but the number used is arbitrary. |
| P_SIGMA_LOW_<0,1>     | 1<=z<=WORDSIZE                | Select which W words are used as parameters in SIGMA_LOW functions. |
| SIGMA_<LOW,CAP>_<0,1> | [1<=z<=WORDSIZE]x3            | Tuple of 3 ints (max WORDSIZE) selecting which W words are used for SIGMA functions. |
#### Return to the root CEP [README](../../README.md)
 | 
| 
	[//]: # (Copyright 2022 Massachusetts Institute of Technology)
[//]: # (SPDX short identifier: BSD-2-Clause)
# Common Evaluation Platform - Co-Simulation Environment
[](https://zenodo.org/badge/latestdoi/108179132)
[](https://opensource.org/licenses/BSD-2-Clause)
<p align="center">
   <img src="../../cep_docs/cep_architecture.jpg" width="1114" height="450">
</p>
The CEP Co-Simulation environment supports "chip-level" simulation of the CEP.
The following provides highlights of the cosim directory structure.
```
<CEP_ROOT/sims/cep_cosim>
|- bin - Supporting scripts for cosim
|- bootrom - Source and support files for the CEP Bootrom (which replaces the default Chipyard Bootrom)
|- drivers
|  |- bare - Baremetal support files
|  |- cep_tests - Files (Classes) supporting testing of the CEP cores
|  |- diag - Supporting files used in defining some test cases
|  |- vectors - Recorded tilelink bus vectors for the CEP cores that are used with the bareMetal macroMix tests 
|  |            and unit-level simulations (not currently supported)
|  |- virtual - Virtual Mode supporting files (currently not supported)
|- dvt - Verilog and supporting files used by the cosim testbench
|- generated-src - Output of the Chipyard build
|- lib - CEP cosim build directory
|- pli - Files related to the PLI interface used by the cosim testbench
|- share - Files related to the IPC mailboxes used by the cosim testbench
|- simDiag - Additional supporting files
|- src - Logging and thread supporting files
|- testSuites
|  |- bfmTests - Tests that run in Bus Functional Model Mode
|  |- bareMetalTests - Tests that run in Bare Meta Mode
|  |- isaTests - Once generated, contains the modified RISC-V ISA tests for use in the cosim
```
These instructions assume you are running an environment as described in the pre-requisites section [here](../../README.md).
Prior to executing any simulation, the appropriate Chipyard *SUB_PROJECT* must be built.  The `cep_cosim` *SUB_PROJECT* It is selected by default when you run the following commands:
```
cd <CEP_ROOT>/sims/cep_cosim
make -f Makefile.chipyard
```
This command will generate and copy all of the necessary SystemVerilog/Verilog into the `<CEP_ROOT>/sims/cep_cosim/generated-src` directory.
## Building ISA tests for simulation ## 
The cosim supports bare metal execution of the RISC-V ISA tests which are included as submodule.  Additional information about these tests can be found [here](https://github.com/riscv-software-src/riscv-tests/tree/1ce128fa78c24bb0ed399c647e7139322b5353a7).
In the event that submodule initialization did not include the riscv-tests, one can manually initialize the submodule:
```
cd <CEP_ROOT>
git submodule update --init --recursive ./toolchains/riscv-tools/riscv-tests
```
There are a few know issues with running the ISA tests on the CEP.  Some manual changes are required before incorporating these tests into the cosim.
**Issue with TVM='p' & 'pm'**: These 2 modes are setup to run in physical address only condition. Even though the riscv-tests [README.md](https://github.com/riscv-software-src/riscv-tests/tree/1ce128fa78c24bb0ed399c647e7139322b5353a7) mentions TVM='pm' mode is supported but the make infrastructure NOT really set up the build for it. In order to improve coverage, we need to be able to run tests on 4 cores. Therefore, we need to do a minor edit to change TVM='p' (virtual memory is disabled, only core 0 boots up) to 'pm' (virtual memory is disabled, all cores boot up)
Edit the file `<CEP_ROOT>/toolchains/riscv-tools/riscv-tests/env/p/riscv_test.h` and look for the lines below:
```
#define RISCV_MULTICORE_DISABLE                                         \
  csrr a0, mhartid;                                                     \
  1: bnez a0, 1b  
```
This define is used to basically do a check and only allow core0 run the test. Other cores will fail if they run. We need to disable this check by removing the **bnez** line  as such:
```
#define RISCV_MULTICORE_DISABLE                                         \
  csrr a0, mhartid;                                                     \
// Remove/comment out this line
//  1: bnez a0, 1b
```
Save the file.
**Issue with TVM='v'**: Similar problem here, the tests are setup for core0 only, others cores's jobs just do interference to cause cache misses. For simulation, we need to allow any cores to run the same tests. Also, we dont need to run all the rv64*-v-* tests, since, they are the same as when TVM='p' but one run in virtual address mode and the other in strickly physical address mode. The goals for TVM='v' tests are to improve the coverages for page tables (page faults), cache hits/misses.
Edit the file `<CEP_ROOT>/toolchains/riscv-tools/riscv-tests/env/v/vm.c` and look for the lines below:
```
  if (read_csr(mhartid) > 0)
    coherence_torture();
```
Remove/comment out these 2 lines and save the file.
**Issue with TVM='pt'**: Not supported for now.
Next edit is **OPTIONAL** (only do it if you know what you are doing :-): this edit is to add switches to the build process to including source information in the object dump file for PC's tracing. It is helpful in debugging failed test(s). Be aware, the ELF/dump files will be much bigger!! Only do this if you intend to include the source codes in the object dump file. In addition, RISCV-core will behave differently due to GDB is not supported in simulation when it taking a page fault (dud!). So only do this **edit**  to obtain the object dump file for tracing.
Edit file `<CEP_ROOT>/toolchains/riscv-tools/riscv-tests/isa/Makefile`, look for the lines as such:
```
RISCV_GCC_OPTS ?= -static -mcmodel=medany -fvisibility=hidden -nostdlib -nostartfiles
RISCV_OBJDUMP ?= $(RISCV_PREFIX)objdump  --disassemble-all --disassemble-zeroes --section=.text --section=.text.startup --section=.text.init --section=.data
```
And change them to match the below:
```
RISCV_GCC_OPTS ?= -static -mcmodel=medany -fvisibility=hidden -nostdlib -nostartfiles -g
RISCV_OBJDUMP ?= $(RISCV_PREFIX)objdump  -S -C -d -l -x --disassemble-all --disassemble-zeroes --section=.text --section=.text.startup --section=.text.init --section=.data
```
Save the Makefile.
And now you are ready to do the build as follows
```
  cd <CEP_ROOT>/toolchains/riscv-tools/riscv-tests
  autoconf
  ./configure 
  make isa      <-- only need to make ISA, without argument benchmark tests will also be included (benchmarks have NOT been ported)
```
The make command above will compile **mostly** assembly tests in the directory **isa** under it. These are the ones will be re-used to run in our simulation. **NOTE**: only RV64*-p/v-* tests are used since the cores are 64-bit cores. 
**Note2**: As mentioned earlier, the purpose of this is to allow all cores to be able to run simulation to improve coverages. However, some tests are explicitely written to run on core0 only, some tests MUST be run as single thread (only 1 core active at a time), some tests will allow all cores to run in parallel. With that in mind, Makefile under **<CEP_ROOT>/sims/cep_cosim/testSuites/isaTests** is setup to take that into account by seperating them into 3 categories and simulate them accordingly.
Next step is to port and prepare those ISA tests above for simulation.
```
  cd <CEP_ROOT>/sims/cep_cosim/testSuites/isaTests
  make createISATests  <-- clean old (if any) and prepare all new ISA tests for simulation (take a while.. Be patient)
```
**Finally**: There are a lots of magic happen under-the-hood for this type of tests since they are originally written such that their output are used to compare against golden output (from Spike/Verilator). We don't do that here. Therefore, in simulation, hooks are put in place to check the **core's PC** (Program Counter) to see if they enter **pass** or **fail** section. In order to do this, during test preparation, a perl script is called to look into the deassembled code (`<test>.dump` file) for given test to find where the **pass/fail** locations are, respectively. These locations are needed by the testbench during runtime to determine if the given test is passing or failing.
### OpenOCD / Debug / GDB Support
Currently, this is not supported with the Chipyard-based CEP.  We'll look to restore this functionality as soon as possible.
### Running the cosim
The cosim uses a hierarchical makefile structure.  Tests can be run individually, as a group (i.e.; testSuite), or as a complete set.
Makefile usage can be obtained by running `make usage` in any of the test, testSuite, or root cosim directories.
Default environment settings can be obtained by running `make sim_info`.
When a test is run, many files are generated.  Some are highlighted below:
  - c_module.o, c_dispatch.o, c_dispatch - Objects and executables for threads supporting the cosim
  - If a baremetal test, `riscv_wrapper[.dump, .elf, .hex, .img, .o]` - Files associated with the RISC-V executable
  - `<test_name>_<simulator>_compile.log`, `<test_name>_<simulator>_opt.log`, `<test_name>_<simulator>_sim.log` - Log files related to different phases of the simulation process
  - status - Indicates pass/fail status of the test run..  used by higher-level (testSuite, whole cosim) test runs to aggregate results
  - testHistory.txt - Contains status summary for all test runs since the last `make clean`
  - vsim.do - Automatically generated TCL script for controlling waveform captured and coverage generation.  A default one is generated by the Makefiles that captures all ports in thle design.  This can be modified post-generation to capture other signals. 
    An example follows:
    ```
    proc wave_on {} {
      echo "vsim.do: Enable logging";  
      log -ports -r /* ;
      log -r /*/aesmodule/* ;
    }
    ```
    In addition to all the ports in the design, the above example captures all the signals in the aesmodule and below.
### Tool Locations 
The following variables can be overwritten (or changed in cep_buildHW.make).  They need to match the tool locations in your system.
  XCELIUM_VERSION  ?= XCELIUMAGILE20.09.001
  XCELIUM_INSTALL  ?= /brewhouse/cad4/x86_64/Cadence/${XCELIUM_VERSION}
  QUESTASIM_PATH   ?= /opt/questa-2019.1/questasim/bin
### Return to the Root CEP [readme](../../README.md).
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      cep_tb.v
// Program:        Common Evaluation Platform (CEP)
// Description:    CEP Co-Simulation Top Level Testbench 
// Notes:          
//
//--------------------------------------------------------------------------------------
`ifndef COSIM_TB_TOP_MODULE
  `define COSIM_TB_TOP_MODULE       cep_tb
`endif
`ifndef CHIPYARD_TOP_MODULE
  `define CHIPYARD_TOP_MODULE       ChipTop
`endif 
`include "suite_config.v"
`include "cep_hierMap.incl"
`include "cep_adrMap.incl"
`include "v2c_cmds.incl"
`include "v2c_top.incl"
`ifndef CLOCK_PERIOD
  `define CLOCK_PERIOD          10
`endif
`ifndef RESET_DELAY
  `define RESET_DELAY           100
`endif
// JTAG related DPI imports
import "DPI-C" function int jtag_getSocketPortId();
import "DPI-C" function int jtag_cmd(input int tdo_in, output int encode);   
import "DPI-C" function int jtag_init();
import "DPI-C" function int jtag_quit();   
// Top Level Testbench Module
module `COSIM_TB_TOP_MODULE;
  //--------------------------------------------------------------------------------------
  // Wire & Reg Declarations
  //--------------------------------------------------------------------------------------
  reg                 sys_rst_n;
  wire                sys_rst;
  reg                 sys_clk;
  wire                sys_clk_pad;
    
  wire                jtag_TCK; pullup (weak1) (jtag_TCK);
  wire                jtag_TMS; pullup (weak1) (jtag_TMS);
  wire                jtag_TDI; pullup (weak1) (jtag_TDI);
  wire                jtag_TRSTn; pullup (weak1) (jtag_TRSTn);
  wire                jtag_TDO;   
  wire                uart_rxd; pullup (weak1) (uart_rxd);
  wire                uart_tb_rxd; pullup (weak1) (uart_tb_rxd);
  wire                uart_txd; 
  wire                uart_model_en;
  wire                gpio_0_0; pullup (weak1) (gpio_0_0);
  wire                gpio_0_1; pullup (weak1) (gpio_0_1);
  wire                gpio_0_2; pullup (weak1) (gpio_0_2);
  wire                gpio_0_3; pullup (weak1) (gpio_0_3);
  wire                gpio_0_4; pullup (weak1) (gpio_0_4);
  wire                gpio_0_5; pullup (weak1) (gpio_0_5);
  wire                gpio_0_6; pullup (weak1) (gpio_0_6);
  wire                gpio_0_7; pullup (weak1) (gpio_0_7);
  wire                spi_0_sck; 
  wire                spi_0_cs_0;    
  wire                spi_0_dq_0; pullup (weak1) (spi_0_dq_0);
  wire                spi_0_dq_1; pullup (weak1) (spi_0_dq_1);
  wire                spi_0_dq_2; pullup (weak1) (spi_0_dq_2);
  wire                spi_0_dq_3; pullup (weak1) (spi_0_dq_3);
  wire                spi_loopback_SCK;
  wire                spi_loopback_CS_n;
  wire                spi_loopback_MOSI;
  wire                spi_loopback_MISO;
  wire                spi_sd_model_rstn;
  wire                spi_sd_model_ncs;
  wire                spi_sd_model_sclk;
  wire                spi_sd_model_mosi;
  wire                spi_sd_model_miso;
  reg                 pll_bypass;
  wire                pll_bypass_pad;
  wire                pll_observe;
  //-------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // Reset Generation
  //--------------------------------------------------------------------------------------
  initial begin
    sys_rst_n = 1'b0;
    #`RESET_DELAY
    sys_rst_n = 1'b1;
  end
  assign sys_rst = ~sys_rst_n;
  //--------------------------------------------------------------------------------------
  
  //--------------------------------------------------------------------------------------
  // Clock Generation
  //--------------------------------------------------------------------------------------
  initial
    sys_clk = 1'b0;
  always
    sys_clk = #(`CLOCK_PERIOD/2.0) ~sys_clk;
  assign sys_clk_pad = sys_clk;
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // Either the UART is in loopback mode OR it is fed to a testbench UART receiver
  //--------------------------------------------------------------------------------------  
  assign uart_rxd       = (`UART_LOOPBACK_ENABLED) ? uart_txd : 1'b1;
  assign uart_model_en  = ~`UART_LOOPBACK_ENABLED;
  // Testbench UART receiver
  uart_model #(
  `ifdef ASIC_MODE
  `ifdef CADENCE
      .BIT_RATE(6_250_000),	  // CEP UART DIV = 32, internal clock = 200MHz
  `endif
  `ifdef MODELSIM
      .BIT_RATE(5_208_333), 	// CEP UART Div = 32, internal clock = 166.66MHz (should be 200MHz in Modelsim as well)
   `endif
`else
  .BIT_RATE(3_125_000),       // CEP UART DIV = 32, internal clock = 100MHz
`endif
    .CLK_HZ(100_000_000),
    .PAYLOAD_BITS(8),
    .STOP_BITS(2)
  ) uart_model_inst (
    .clk              (sys_clk),
    .resetn           (sys_rst_n),
    .uart_rxd         (uart_txd),
    .uart_rx_en       (~`UART_LOOPBACK_ENABLED)
  );  
  //--------------------------------------------------------------------------------------
  
  //--------------------------------------------------------------------------------------
  // The SPI either operates in loopback mode OR connects to the SPI SD Model
  //--------------------------------------------------------------------------------------
  
  assign spi_loopback_SCK   = spi_0_sck; 
  assign spi_loopback_CS_n  = `SPI_LOOPBACK_ENABLED ? spi_0_cs_0  : 1'b1;
  assign spi_loopback_MOSI  = spi_0_dq_0;
  assign spi_0_dq_1         = spi_loopback_MISO;
  assign spi_0_dq_1         = spi_sd_model_miso;
  assign spi_sd_model_rstn  = sys_rst_n;
  assign spi_sd_model_sclk  = spi_0_sck;
  assign spi_sd_model_ncs   = `SPI_LOOPBACK_ENABLED ? 1'b1        : spi_0_cs_0;
  assign spi_sd_model_mosi  = spi_0_dq_0;
  // SPI loopback instantiation
  spi_loopback spi_loopback_inst (
    .SCK    (spi_loopback_SCK   ),
    .CS_n   (spi_loopback_CS_n  ),
    .MOSI   (spi_loopback_MOSI  ),
    .MISO   (spi_loopback_MISO  )
  );
  
  // SPI / SD Model Instiation
  spi_sd_model spi_sd_model_inst (
    .rstn   (spi_sd_model_rstn  ),
    .ncs    (spi_sd_model_ncs   ),
    .sclk   (spi_sd_model_sclk  ),
    .mosi   (spi_sd_model_mosi  ),
    .miso   (spi_sd_model_miso  )
  ); 
  //--------------------------------------------------------------------------------------   
 
  //--------------------------------------------------------------------------------------
  // Device Under Test
  //
  // I/O manually copied from Chisel generated verilog
  //--------------------------------------------------------------------------------------
  // Force CHIP_ID's when operating in BFM_MODE (otherwise these parameters don't exist)
  `ifdef BFM_MODE
    defparam `TILE0_TL_PATH.CHIP_ID = 0;
    defparam `TILE1_TL_PATH.CHIP_ID = 1;
    defparam `TILE2_TL_PATH.CHIP_ID = 2;
    defparam `TILE3_TL_PATH.CHIP_ID = 3;
  `endif
  initial begin
  `ifdef ASIC_MODE
  `ifdef BYPASS_PLL
    `logI("PLL is set to bypass mode");
    pll_bypass = 1'b1;
  `else
    `logI("PLL is set to normal mode");
    pll_bypass = 1'b0;
  `endif
  `endif
  end
  assign  pll_bypass_pad  = pll_bypass;
  // Pinouts for the ASIC and FPGA differ
`ifdef ASIC_MODE
  `CHIPYARD_TOP_MODULE `DUT_INST ( 
    .jtag_TCK           (jtag_TCK),
    .jtag_TMS           (jtag_TMS),
    .jtag_TDI           (jtag_TDI),
    .jtag_TDO           (jtag_TDO),
    .spi_0_sck          (spi_0_sck),
    .spi_0_cs_0         (spi_0_cs_0),
    .spi_0_dq_0         (spi_0_dq_0),
    .spi_0_dq_1         (spi_0_dq_1),
    .spi_0_dq_2         (spi_0_dq_2),
    .spi_0_dq_3         (spi_0_dq_3),
    .test_mode_0        (),
    .test_mode_1        (),
    .test_mode_2        (),
    .test_mode_3        (),
    .test_io_0          (),
    .test_io_1          (),
    .test_io_2          (),
    .test_io_3          (),
    .test_io_4          (),
    .test_io_5          (),
    .test_io_6          (),
    .test_io_7          (),
    .test_io_8          (),
    .test_io_9          (),
    .test_io_10         (),
    .test_io_11         (),
    .test_io_12         (),
    .test_io_13         (),
    .test_io_14         (),
    .test_io_15         (),
    .socjtag_TCK        (),
    .socjtag_TMS        (),
    .socjtag_TDI        (),
    .socjtag_TRSTn      (),
    .socjtag_TDO        (),
    .gpio_0_0           (gpio_0_0),
    .gpio_0_1           (gpio_0_1),
    .gpio_0_2           (gpio_0_2),
    .gpio_0_3           (gpio_0_3),
    .gpio_0_4           (gpio_0_4),
    .gpio_0_5           (gpio_0_5),
    .gpio_0_6           (gpio_0_6),
    .gpio_0_7           (gpio_0_7),
    .uart_0_txd         (uart_txd),
    .uart_0_rxd         (uart_rxd),
    .reset              (sys_rst),
    .refclk             (sys_clk_pad),
    .pll_bypass         (pll_bypass_pad),
    .pll_observe        (pll_observe)
  );
  `else 
  `CHIPYARD_TOP_MODULE `DUT_INST ( 
    .jtag_TCK           (jtag_TCK),
    .jtag_TMS           (jtag_TMS),
    .jtag_TDI           (jtag_TDI),
    .jtag_TDO           (jtag_TDO),
    .spi_0_sck          (spi_0_sck),
    .spi_0_cs_0         (spi_0_cs_0),
    .spi_0_dq_0         (spi_0_dq_0),
    .spi_0_dq_1         (spi_0_dq_1),
    .spi_0_dq_2         (spi_0_dq_2),
    .spi_0_dq_3         (spi_0_dq_3),
    .gpio_0_0           (gpio_0_0),
    .gpio_0_1           (gpio_0_1),
    .gpio_0_2           (gpio_0_2),
    .gpio_0_3           (gpio_0_3),
    .gpio_0_4           (gpio_0_4),
    .gpio_0_5           (gpio_0_5),
    .gpio_0_6           (gpio_0_6),
    .gpio_0_7           (gpio_0_7),
    .uart_0_txd         (uart_txd),
    .uart_0_rxd         (uart_rxd),
    .reset              (sys_rst),
    .clock_clock        (sys_clk_pad)
  );
  `endif
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // Instantiation of the System and CPU Drivers
  //--------------------------------------------------------------------------------------
  reg [3:0]   enableMask = 0;
  wire [3:0]  passMask;
  // Enable all the CPU Drivers
  initial begin
    #1 enableMask = 'hF;
  end
  
 genvar c;
  generate
    for (c = 0; c < `MAX_CORES; c++) begin : cpuId
      cpu_driver #(
        .MY_SLOT_ID   (0),
        .MY_CPU_ID    (c)
      ) driver (
        .clk          (sys_clk        ),
        .enableMe     (enableMask[c]  )
      );
      assign passMask[c] = driver.pcPass;
    end // end for
  endgenerate
  // Instantiate the "System" driver (which is ALWAYS enabled)
  system_driver #(
        .MY_SLOT_ID   (`SYSTEM_SLOT_ID),
        .MY_CPU_ID    (`SYSTEM_CPU_ID)
  ) system_driver (
    .clk        (sys_clk),
    .enableMe   (1'b1)
  );
  //--------------------------------------------------------------------------------------
  
  //--------------------------------------------------------------------------------------
  // OpenOCD interface to drive JTAG via DPI
  //--------------------------------------------------------------------------------------
  reg         enable_jtag     = 0;
  reg         quit_jtag       = 0;  
  reg         enableDel       = 0;
  reg [15:0]  clkCnt;
  int         junk;
  int         jtag_encode;
  wire        dpi_jtag_tdo    = jtag_TDO;
   
  always @(posedge `DVT_FLAG[`DVTF_ENABLE_REMOTE_BITBANG_BIT]) begin
    enable_jtag = 1;
    @(negedge `DVT_FLAG[`DVTF_ENABLE_REMOTE_BITBANG_BIT]);
    quit_jtag = 1;
  end
  `ifdef OPENOCD_ENABLE
    always @(posedge passMask[3]) begin
      repeat (40000) @(posedge sys_clk);
      `logI("Initialting QUIT to close socket...");
      junk = jtag_quit();
    end
    initial begin
      junk = jtag_init();
      jtag_TRSTn = 0;
      repeat (20) @(posedge sys_clk);
      jtag_TRSTn = 1;
      repeat (20) @(posedge sys_clk);
      jtag_TRSTn = 0;
    end
    always @(posedge sys_clk) begin
      if (sys_rst) begin
        enableDel   <= 0;
        clkCnt      <= 5;
      end else begin
        enableDel   <= enable_jtag;
        if (enableDel) begin
          clkCnt    <= clkCnt - 1;
        
          if (clkCnt == 0) begin
            clkCnt    <= 5;
        
            if (!quit_jtag) begin
              junk                                    = jtag_cmd(dpi_jtag_tdo, jtag_encode);
              {jtag_TRSTn,jtag_TCK,jtag_TMS,jtag_TDI} = jtag_encode ^ 'h8; // flip the TRSN
            end  // if (!quit_jtag)
          end // if (clkCnt == 0)
        end // if (enable && init_done_sticky)
      end // else: !if(reset || r_reset)
    end // always @ (posedge clock)
  `endif   
  //--------------------------------------------------------------------------------------
  
  //--------------------------------------------------------------------------------------
  // When operating in Bare Metal mode, instantiate the Rocket Tile Tilelink Monitors
  // They can be individually enabled from softwware and are disabled by default
  //--------------------------------------------------------------------------------------
  `ifdef BARE_MODE
    tile_monitor tile0_monitor_inst (
      .clock                                        (`TILE0_PATH.clock                                    ),
      .reset                                        (`TILE0_PATH.reset                                    ),
      .enable                                       (`CPU0_DRIVER.tl_monitor_enable                       ),
      .auto_wfi_out_0                               (`TILE0_PATH.auto_wfi_out_0                           ),
      .auto_int_local_in_3_0                        (`TILE0_PATH.auto_int_local_in_3_0                    ),
      .auto_int_local_in_2_0                        (`TILE0_PATH.auto_int_local_in_2_0                    ),
      .auto_int_local_in_1_0                        (`TILE0_PATH.auto_int_local_in_1_0                    ),
      .auto_int_local_in_1_1                        (`TILE0_PATH.auto_int_local_in_1_1                    ),
      .auto_int_local_in_0_0                        (`TILE0_PATH.auto_int_local_in_0_0                    ),
      .auto_hartid_in                               (`TILE0_PATH.auto_hartid_in                           ),
      .a_ready                                      (`TILE0_PATH.auto_tl_other_masters_out_a_ready        ),
      .a_valid                                      (`TILE0_PATH.auto_tl_other_masters_out_a_valid        ),
      .a_bits_opcode                                (`TILE0_PATH.auto_tl_other_masters_out_a_bits_opcode  ),
      .a_bits_param                                 (`TILE0_PATH.auto_tl_other_masters_out_a_bits_param   ),
      .a_bits_size                                  (`TILE0_PATH.auto_tl_other_masters_out_a_bits_size    ),
      .a_bits_source                                (`TILE0_PATH.auto_tl_other_masters_out_a_bits_source  ),
      .a_bits_address                               (`TILE0_PATH.auto_tl_other_masters_out_a_bits_address ),
      .a_bits_mask                                  (`TILE0_PATH.auto_tl_other_masters_out_a_bits_mask    ),
      .a_bits_data                                  (`TILE0_PATH.auto_tl_other_masters_out_a_bits_data    ),
      .b_ready                                      (`TILE0_PATH.auto_tl_other_masters_out_b_ready        ),
      .b_valid                                      (`TILE0_PATH.auto_tl_other_masters_out_b_valid        ),
      .b_bits_param                                 (`TILE0_PATH.auto_tl_other_masters_out_b_bits_param   ),
      .b_bits_size                                  (`TILE0_PATH.auto_tl_other_masters_out_b_bits_size    ),
      .b_bits_source                                (`TILE0_PATH.auto_tl_other_masters_out_b_bits_source  ),
      .b_bits_address                               (`TILE0_PATH.auto_tl_other_masters_out_b_bits_address ),
      .c_ready                                      (`TILE0_PATH.auto_tl_other_masters_out_c_ready        ),
      .c_valid                                      (`TILE0_PATH.auto_tl_other_masters_out_c_valid        ),
      .c_bits_opcode                                (`TILE0_PATH.auto_tl_other_masters_out_c_bits_opcode  ),
      .c_bits_param                                 (`TILE0_PATH.auto_tl_other_masters_out_c_bits_param   ),
      .c_bits_size                                  (`TILE0_PATH.auto_tl_other_masters_out_c_bits_size    ),
      .c_bits_source                                (`TILE0_PATH.auto_tl_other_masters_out_c_bits_source  ),
      .c_bits_address                               (`TILE0_PATH.auto_tl_other_masters_out_c_bits_address ),
      .c_bits_data                                  (`TILE0_PATH.auto_tl_other_masters_out_c_bits_data    ),
      .d_ready                                      (`TILE0_PATH.auto_tl_other_masters_out_d_ready        ),
      .d_valid                                      (`TILE0_PATH.auto_tl_other_masters_out_d_valid        ),
      .d_bits_opcode                                (`TILE0_PATH.auto_tl_other_masters_out_d_bits_opcode  ),
      .d_bits_param                                 (`TILE0_PATH.auto_tl_other_masters_out_d_bits_param   ),
      .d_bits_size                                  (`TILE0_PATH.auto_tl_other_masters_out_d_bits_size    ),
      .d_bits_source                                (`TILE0_PATH.auto_tl_other_masters_out_d_bits_source  ),
      .d_bits_sink                                  (`TILE0_PATH.auto_tl_other_masters_out_d_bits_sink    ),
      .d_bits_denied                                (`TILE0_PATH.auto_tl_other_masters_out_d_bits_denied  ),
      .d_bits_data                                  (`TILE0_PATH.auto_tl_other_masters_out_d_bits_data    ),
      .d_bits_corrupt                               (`TILE0_PATH.auto_tl_other_masters_out_d_bits_corrupt ),
      .e_ready                                      (`TILE0_PATH.auto_tl_other_masters_out_e_ready        ),
      .e_valid                                      (`TILE0_PATH.auto_tl_other_masters_out_e_valid        ),
      .e_bits_sink                                  (`TILE0_PATH.auto_tl_other_masters_out_e_bits_sink    )
    );
    tile_monitor tile1_monitor_inst (
      .clock                                        (`TILE1_PATH.clock                                    ),
      .reset                                        (`TILE1_PATH.reset                                    ),
      .enable                                       (`CPU1_DRIVER.tl_monitor_enable                       ),
      .auto_wfi_out_0                               (`TILE1_PATH.auto_wfi_out_0                           ),
      .auto_int_local_in_3_0                        (`TILE1_PATH.auto_int_local_in_3_0                    ),
      .auto_int_local_in_2_0                        (`TILE1_PATH.auto_int_local_in_2_0                    ),
      .auto_int_local_in_1_0                        (`TILE1_PATH.auto_int_local_in_1_0                    ),
      .auto_int_local_in_1_1                        (`TILE1_PATH.auto_int_local_in_1_1                    ),
      .auto_int_local_in_0_0                        (`TILE1_PATH.auto_int_local_in_0_0                    ),
      .auto_hartid_in                               (`TILE1_PATH.auto_hartid_in                           ),
      .a_ready                                      (`TILE1_PATH.auto_tl_other_masters_out_a_ready        ),
      .a_valid                                      (`TILE1_PATH.auto_tl_other_masters_out_a_valid        ),
      .a_bits_opcode                                (`TILE1_PATH.auto_tl_other_masters_out_a_bits_opcode  ),
      .a_bits_param                                 (`TILE1_PATH.auto_tl_other_masters_out_a_bits_param   ),
      .a_bits_size                                  (`TILE1_PATH.auto_tl_other_masters_out_a_bits_size    ),
      .a_bits_source                                (`TILE1_PATH.auto_tl_other_masters_out_a_bits_source  ),
      .a_bits_address                               (`TILE1_PATH.auto_tl_other_masters_out_a_bits_address ),
      .a_bits_mask                                  (`TILE1_PATH.auto_tl_other_masters_out_a_bits_mask    ),
      .a_bits_data                                  (`TILE1_PATH.auto_tl_other_masters_out_a_bits_data    ),
      .b_ready                                      (`TILE1_PATH.auto_tl_other_masters_out_b_ready        ),
      .b_valid                                      (`TILE1_PATH.auto_tl_other_masters_out_b_valid        ),
      .b_bits_param                                 (`TILE1_PATH.auto_tl_other_masters_out_b_bits_param   ),
      .b_bits_size                                  (`TILE1_PATH.auto_tl_other_masters_out_b_bits_size    ),
      .b_bits_source                                (`TILE1_PATH.auto_tl_other_masters_out_b_bits_source  ),
      .b_bits_address                               (`TILE1_PATH.auto_tl_other_masters_out_b_bits_address ),
      .c_ready                                      (`TILE1_PATH.auto_tl_other_masters_out_c_ready        ),
      .c_valid                                      (`TILE1_PATH.auto_tl_other_masters_out_c_valid        ),
      .c_bits_opcode                                (`TILE1_PATH.auto_tl_other_masters_out_c_bits_opcode  ),
      .c_bits_param                                 (`TILE1_PATH.auto_tl_other_masters_out_c_bits_param   ),
      .c_bits_size                                  (`TILE1_PATH.auto_tl_other_masters_out_c_bits_size    ),
      .c_bits_source                                (`TILE1_PATH.auto_tl_other_masters_out_c_bits_source  ),
      .c_bits_address                               (`TILE1_PATH.auto_tl_other_masters_out_c_bits_address ),
      .c_bits_data                                  (`TILE1_PATH.auto_tl_other_masters_out_c_bits_data    ),
      .d_ready                                      (`TILE1_PATH.auto_tl_other_masters_out_d_ready        ),
      .d_valid                                      (`TILE1_PATH.auto_tl_other_masters_out_d_valid        ),
      .d_bits_opcode                                (`TILE1_PATH.auto_tl_other_masters_out_d_bits_opcode  ),
      .d_bits_param                                 (`TILE1_PATH.auto_tl_other_masters_out_d_bits_param   ),
      .d_bits_size                                  (`TILE1_PATH.auto_tl_other_masters_out_d_bits_size    ),
      .d_bits_source                                (`TILE1_PATH.auto_tl_other_masters_out_d_bits_source  ),
      .d_bits_sink                                  (`TILE1_PATH.auto_tl_other_masters_out_d_bits_sink    ),
      .d_bits_denied                                (`TILE1_PATH.auto_tl_other_masters_out_d_bits_denied  ),
      .d_bits_data                                  (`TILE1_PATH.auto_tl_other_masters_out_d_bits_data    ),
      .d_bits_corrupt                               (`TILE1_PATH.auto_tl_other_masters_out_d_bits_corrupt ),
      .e_ready                                      (`TILE1_PATH.auto_tl_other_masters_out_e_ready        ),
      .e_valid                                      (`TILE1_PATH.auto_tl_other_masters_out_e_valid        ),
      .e_bits_sink                                  (`TILE1_PATH.auto_tl_other_masters_out_e_bits_sink    )
    );
    tile_monitor tile2_monitor_inst (
      .clock                                        (`TILE2_PATH.clock                                    ),
      .reset                                        (`TILE2_PATH.reset                                    ),
      .enable                                       (`CPU2_DRIVER.tl_monitor_enable                       ),
      .auto_wfi_out_0                               (`TILE2_PATH.auto_wfi_out_0                           ),
      .auto_int_local_in_3_0                        (`TILE2_PATH.auto_int_local_in_3_0                    ),
      .auto_int_local_in_2_0                        (`TILE2_PATH.auto_int_local_in_2_0                    ),
      .auto_int_local_in_1_0                        (`TILE2_PATH.auto_int_local_in_1_0                    ),
      .auto_int_local_in_1_1                        (`TILE2_PATH.auto_int_local_in_1_1                    ),
      .auto_int_local_in_0_0                        (`TILE2_PATH.auto_int_local_in_0_0                    ),
      .auto_hartid_in                               (`TILE2_PATH.auto_hartid_in                           ),
      .a_ready                                      (`TILE2_PATH.auto_tl_other_masters_out_a_ready        ),
      .a_valid                                      (`TILE2_PATH.auto_tl_other_masters_out_a_valid        ),
      .a_bits_opcode                                (`TILE2_PATH.auto_tl_other_masters_out_a_bits_opcode  ),
      .a_bits_param                                 (`TILE2_PATH.auto_tl_other_masters_out_a_bits_param   ),
      .a_bits_size                                  (`TILE2_PATH.auto_tl_other_masters_out_a_bits_size    ),
      .a_bits_source                                (`TILE2_PATH.auto_tl_other_masters_out_a_bits_source  ),
      .a_bits_address                               (`TILE2_PATH.auto_tl_other_masters_out_a_bits_address ),
      .a_bits_mask                                  (`TILE2_PATH.auto_tl_other_masters_out_a_bits_mask    ),
      .a_bits_data                                  (`TILE2_PATH.auto_tl_other_masters_out_a_bits_data    ),
      .b_ready                                      (`TILE2_PATH.auto_tl_other_masters_out_b_ready        ),
      .b_valid                                      (`TILE2_PATH.auto_tl_other_masters_out_b_valid        ),
      .b_bits_param                                 (`TILE2_PATH.auto_tl_other_masters_out_b_bits_param   ),
      .b_bits_size                                  (`TILE2_PATH.auto_tl_other_masters_out_b_bits_size    ),
      .b_bits_source                                (`TILE2_PATH.auto_tl_other_masters_out_b_bits_source  ),
      .b_bits_address                               (`TILE2_PATH.auto_tl_other_masters_out_b_bits_address ),
      .c_ready                                      (`TILE2_PATH.auto_tl_other_masters_out_c_ready        ),
      .c_valid                                      (`TILE2_PATH.auto_tl_other_masters_out_c_valid        ),
      .c_bits_opcode                                (`TILE2_PATH.auto_tl_other_masters_out_c_bits_opcode  ),
      .c_bits_param                                 (`TILE2_PATH.auto_tl_other_masters_out_c_bits_param   ),
      .c_bits_size                                  (`TILE2_PATH.auto_tl_other_masters_out_c_bits_size    ),
      .c_bits_source                                (`TILE2_PATH.auto_tl_other_masters_out_c_bits_source  ),
      .c_bits_address                               (`TILE2_PATH.auto_tl_other_masters_out_c_bits_address ),
      .c_bits_data                                  (`TILE2_PATH.auto_tl_other_masters_out_c_bits_data    ),
      .d_ready                                      (`TILE2_PATH.auto_tl_other_masters_out_d_ready        ),
      .d_valid                                      (`TILE2_PATH.auto_tl_other_masters_out_d_valid        ),
      .d_bits_opcode                                (`TILE2_PATH.auto_tl_other_masters_out_d_bits_opcode  ),
      .d_bits_param                                 (`TILE2_PATH.auto_tl_other_masters_out_d_bits_param   ),
      .d_bits_size                                  (`TILE2_PATH.auto_tl_other_masters_out_d_bits_size    ),
      .d_bits_source                                (`TILE2_PATH.auto_tl_other_masters_out_d_bits_source  ),
      .d_bits_sink                                  (`TILE2_PATH.auto_tl_other_masters_out_d_bits_sink    ),
      .d_bits_denied                                (`TILE2_PATH.auto_tl_other_masters_out_d_bits_denied  ),
      .d_bits_data                                  (`TILE2_PATH.auto_tl_other_masters_out_d_bits_data    ),
      .d_bits_corrupt                               (`TILE2_PATH.auto_tl_other_masters_out_d_bits_corrupt ),
      .e_ready                                      (`TILE2_PATH.auto_tl_other_masters_out_e_ready        ),
      .e_valid                                      (`TILE2_PATH.auto_tl_other_masters_out_e_valid        ),
      .e_bits_sink                                  (`TILE2_PATH.auto_tl_other_masters_out_e_bits_sink    )
    );
    tile_monitor tile3_monitor_inst (
      .clock                                        (`TILE3_PATH.clock                                    ),
      .reset                                        (`TILE3_PATH.reset                                    ),
      .enable                                       (`CPU3_DRIVER.tl_monitor_enable                       ),
      .auto_wfi_out_0                               (`TILE3_PATH.auto_wfi_out_0                           ),
      .auto_int_local_in_3_0                        (`TILE3_PATH.auto_int_local_in_3_0                    ),
      .auto_int_local_in_2_0                        (`TILE3_PATH.auto_int_local_in_2_0                    ),
      .auto_int_local_in_1_0                        (`TILE3_PATH.auto_int_local_in_1_0                    ),
      .auto_int_local_in_1_1                        (`TILE3_PATH.auto_int_local_in_1_1                    ),
      .auto_int_local_in_0_0                        (`TILE3_PATH.auto_int_local_in_0_0                    ),
      .auto_hartid_in                               (`TILE3_PATH.auto_hartid_in                           ),
      .a_ready                                      (`TILE3_PATH.auto_tl_other_masters_out_a_ready        ),
      .a_valid                                      (`TILE3_PATH.auto_tl_other_masters_out_a_valid        ),
      .a_bits_opcode                                (`TILE3_PATH.auto_tl_other_masters_out_a_bits_opcode  ),
      .a_bits_param                                 (`TILE3_PATH.auto_tl_other_masters_out_a_bits_param   ),
      .a_bits_size                                  (`TILE3_PATH.auto_tl_other_masters_out_a_bits_size    ),
      .a_bits_source                                (`TILE3_PATH.auto_tl_other_masters_out_a_bits_source  ),
      .a_bits_address                               (`TILE3_PATH.auto_tl_other_masters_out_a_bits_address ),
      .a_bits_mask                                  (`TILE3_PATH.auto_tl_other_masters_out_a_bits_mask    ),
      .a_bits_data                                  (`TILE3_PATH.auto_tl_other_masters_out_a_bits_data    ),
      .b_ready                                      (`TILE3_PATH.auto_tl_other_masters_out_b_ready        ),
      .b_valid                                      (`TILE3_PATH.auto_tl_other_masters_out_b_valid        ),
      .b_bits_param                                 (`TILE3_PATH.auto_tl_other_masters_out_b_bits_param   ),
      .b_bits_size                                  (`TILE3_PATH.auto_tl_other_masters_out_b_bits_size    ),
      .b_bits_source                                (`TILE3_PATH.auto_tl_other_masters_out_b_bits_source  ),
      .b_bits_address                               (`TILE3_PATH.auto_tl_other_masters_out_b_bits_address ),
      .c_ready                                      (`TILE3_PATH.auto_tl_other_masters_out_c_ready        ),
      .c_valid                                      (`TILE3_PATH.auto_tl_other_masters_out_c_valid        ),
      .c_bits_opcode                                (`TILE3_PATH.auto_tl_other_masters_out_c_bits_opcode  ),
      .c_bits_param                                 (`TILE3_PATH.auto_tl_other_masters_out_c_bits_param   ),
      .c_bits_size                                  (`TILE3_PATH.auto_tl_other_masters_out_c_bits_size    ),
      .c_bits_source                                (`TILE3_PATH.auto_tl_other_masters_out_c_bits_source  ),
      .c_bits_address                               (`TILE3_PATH.auto_tl_other_masters_out_c_bits_address ),
      .c_bits_data                                  (`TILE3_PATH.auto_tl_other_masters_out_c_bits_data    ),
      .d_ready                                      (`TILE3_PATH.auto_tl_other_masters_out_d_ready        ),
      .d_valid                                      (`TILE3_PATH.auto_tl_other_masters_out_d_valid        ),
      .d_bits_opcode                                (`TILE3_PATH.auto_tl_other_masters_out_d_bits_opcode  ),
      .d_bits_param                                 (`TILE3_PATH.auto_tl_other_masters_out_d_bits_param   ),
      .d_bits_size                                  (`TILE3_PATH.auto_tl_other_masters_out_d_bits_size    ),
      .d_bits_source                                (`TILE3_PATH.auto_tl_other_masters_out_d_bits_source  ),
      .d_bits_sink                                  (`TILE3_PATH.auto_tl_other_masters_out_d_bits_sink    ),
      .d_bits_denied                                (`TILE3_PATH.auto_tl_other_masters_out_d_bits_denied  ),
      .d_bits_data                                  (`TILE3_PATH.auto_tl_other_masters_out_d_bits_data    ),
      .d_bits_corrupt                               (`TILE3_PATH.auto_tl_other_masters_out_d_bits_corrupt ),
      .e_ready                                      (`TILE3_PATH.auto_tl_other_masters_out_e_ready        ),
      .e_valid                                      (`TILE3_PATH.auto_tl_other_masters_out_e_valid        ),
      .e_bits_sink                                  (`TILE3_PATH.auto_tl_other_masters_out_e_bits_sink    )
    );
    `endif // `ifdef BARE_MODE 
    //--------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------
    // When operating in Virtual mode, instantiate the page table walker monitor modules
    //--------------------------------------------------------------------------------------
    `ifdef VIRTUAL_MODE
    ptw_monitor ptwC0R0 (
      .clk                                  (`TILE0_PATH.ptw.clock                              ),
      .trace_valid                          (`TILE0_PATH.core.csr_io_trace_0_valid              ),
      .pc_valid                             (`TILE0_PATH.core.coreMonitorBundle_valid           ),
      .pc                                   (`TILE0_PATH.core.coreMonitorBundle_pc              ),
      .io_requestor_x_req_ready             (`TILE0_PATH.ptw.io_requestor_0_req_ready           ),
      .io_requestor_x_req_valid             (`TILE0_PATH.ptw.io_requestor_0_req_valid           ),
      .io_requestor_x_req_bits_bits_addr    (`TILE0_PATH.ptw.io_requestor_0_req_bits_bits_addr  ),
      .io_requestor_x_resp_valid            (`TILE0_PATH.ptw.io_requestor_0_resp_valid          ),
      .io_requestor_x_resp_bits_ae          (`TILE0_PATH.ptw.io_requestor_0_resp_bits_ae        ),
      .io_requestor_x_resp_bits_pte_ppn     (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_ppn   ),
      .io_requestor_x_resp_bits_pte_d       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_d     ),
      .io_requestor_x_resp_bits_pte_a       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_a     ),
      .io_requestor_x_resp_bits_pte_g       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_g     ),
      .io_requestor_x_resp_bits_pte_u       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_u     ),
      .io_requestor_x_resp_bits_pte_x       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_x     ),
      .io_requestor_x_resp_bits_pte_w       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_w     ),
      .io_requestor_x_resp_bits_pte_r       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_r     ),
      .io_requestor_x_resp_bits_pte_v       (`TILE0_PATH.ptw.io_requestor_0_resp_bits_pte_v     )
    );
    ptw_monitor ptwC0R1 (
      .clk                                  (`TILE0_PATH.ptw.clock                              ),
      .trace_valid                          (1'b0                                               ),
      .pc_valid                             (1'b0                                               ),
      .pc                                   (64'h0                                              ),
      .io_requestor_x_req_ready             (`TILE0_PATH.ptw.io_requestor_1_req_ready           ),
      .io_requestor_x_req_valid             (`TILE0_PATH.ptw.io_requestor_1_req_valid           ),
      .io_requestor_x_req_bits_bits_addr    (`TILE0_PATH.ptw.io_requestor_1_req_bits_bits_addr  ),
      .io_requestor_x_resp_valid            (`TILE0_PATH.ptw.io_requestor_1_resp_valid          ),
      .io_requestor_x_resp_bits_ae          (`TILE0_PATH.ptw.io_requestor_1_resp_bits_ae        ),
      .io_requestor_x_resp_bits_pte_ppn     (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_ppn   ),
      .io_requestor_x_resp_bits_pte_d       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_d     ),
      .io_requestor_x_resp_bits_pte_a       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_a     ),
      .io_requestor_x_resp_bits_pte_g       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_g     ),
      .io_requestor_x_resp_bits_pte_u       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_u     ),
      .io_requestor_x_resp_bits_pte_x       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_x     ),
      .io_requestor_x_resp_bits_pte_w       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_w     ),
      .io_requestor_x_resp_bits_pte_r       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_r     ),
      .io_requestor_x_resp_bits_pte_v       (`TILE0_PATH.ptw.io_requestor_1_resp_bits_pte_v     )
    );
    `endif
    //--------------------------------------------------------------------------------------   
endmodule  // `COSIM_TB_TOP_MODULE | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      cpu_driver.sv
// Program:        Common Evaluation Platform (CEP)
// Description:    Provides the BFM_MODE connections between
//                 the Tilelink masters and DPI mailboxes
//
//                 Also provides some monitoring functions when
//                 the RISCV_TESTS are enabled (in BARE_MODE)
// Notes:          Backdoor memory access is no longer supported
//                 from the individual core drivers and is thus only
//                 accessible from the system thread.
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "cep_hierMap.incl"
`include "cep_adrMap.incl"
`include "v2c_cmds.incl"
`include "v2c_top.incl"
module cpu_driver
(
  input               clk,
  input               enableMe
);
  // Overriden at instantiation
  parameter MY_SLOT_ID            = 4'h0;
  parameter MY_CPU_ID             = 4'h0;
  reg [255:0]         dvtFlags          = 0;
  reg [255:0]         r_data;
  reg [31:0]          printf_addr;
  reg [1:0]           printf_coreId;
  reg [(128*8)-1:0]   printf_buf;
  reg [(128*8)-1:0]   tmp;
  reg                 clear             = 0;
  integer             cnt;
  string              str;
  reg                 program_loaded    = 0;
  
  //--------------------------------------------------------------------------------------
  // Define system driver supported DPI tasks prior to the inclusion of sys/driver_common.incl
  //--------------------------------------------------------------------------------------    
  // READ_STATUS_TASK
  `define SHIPC_READ_STATUS_TASK READ_STATUS_TASK(__shIpc_p0)
  task READ_STATUS_TASK;
    output [31:0] r_data;
    begin
      inBox.mPar[0] = 0;
      @(posedge clk);
    end
  endtask // READ_STATUS_TASK;
  // WRITE_DVT_FLAG_TASK
  `define SHIPC_WRITE_DVT_FLAG_TASK WRITE_DVT_FLAG_TASK(__shIpc_p0,__shIpc_p1,__shIpc_p2)
  task WRITE_DVT_FLAG_TASK;
    input [31:0] msb;
    input [31:0] lsb;
    input [31:0] value; 
    begin
      for (int s = inBox.mPar[1]; s <= inBox.mPar[0]; s++) begin 
        dvtFlags[s]   = inBox.mPar[2] & 1'b1; 
        inBox.mPar[2] = inBox.mPar[2] >> 1; 
      end      
      
      @(posedge clk);  
    end
  endtask // WRITE_DVT_FLAG_TASK;
  // READ_DVT_FLAG_TASK
  `define SHIPC_READ_DVT_FLAG_TASK READ_DVT_FLAG_TASK(__shIpc_p0,__shIpc_p1,{__shIpc_p0[31:0],__shIpc_p1[31:0]})
  task READ_DVT_FLAG_TASK;
    input [31:0]    msb;
    input [31:0]    lsb;
    output [63:0]   r_data;
    integer         m;
    integer         l;
    reg [63:0]      tmp;
    begin
      tmp = 0;
    
      m = inBox.mPar[0];
      l = inBox.mPar[1];
      for (int s = m; s >= l; s--) begin       
        tmp = {tmp[62:0], dvtFlags[s]};
      end
      
      inBox.mPar[0] = tmp;
   
      @(posedge clk);   
    end
  endtask // READ_DVT_FLAG_TASK;
  // READ_ERROR_CNT_TASK
  `define SHIPC_READ_ERROR_CNT_TASK READ_ERROR_CNT_TASK(__shIpc_p0)
  task READ_ERROR_CNT_TASK;
    output [31:0]   r_data;
    begin
      $vpp_getErrorCount(inBox.mPar[0]);
    end
  endtask // READ_ERROR_CNT_TASK;
  // The following support task are only valid in BFM mode
  `ifdef BFM_MODE
    // WRITE64_BURST
    `define SHIPC_WRITE64_BURST_TASK WRITE64_BURST_DPI()
    task WRITE64_BURST_DPI;
      reg [3:0]   bits_size;
      begin
        bits_size = $clog2(inBox.mAdrHi << 3); // unit of 8 bytes
   
        case (MY_CPU_ID)
          0: begin
            for (int i=0;i<inBox.mAdrHi;i++) `TILE0_TL_PATH.tl_buf[i] = inBox.mPar[i];
            `TILE0_TL_PATH.tl_a_ul_write_burst(MY_CPU_ID & 'h1, inBox.mAdr,'hFF,bits_size);
          end
          1: begin
            for (int i=0;i<inBox.mAdrHi;i++) `TILE1_TL_PATH.tl_buf[i] = inBox.mPar[i];
            `TILE1_TL_PATH.tl_a_ul_write_burst(MY_CPU_ID & 'h1, inBox.mAdr,'hFF,bits_size);
          end
          2: begin
            for (int i=0;i<inBox.mAdrHi;i++) `TILE2_TL_PATH.tl_buf[i] = inBox.mPar[i];
            `TILE2_TL_PATH.tl_a_ul_write_burst(MY_CPU_ID & 'h1, inBox.mAdr,'hFF,bits_size);
          end
          3: begin
            for (int i=0;i<inBox.mAdrHi;i++) `TILE3_TL_PATH.tl_buf[i] = inBox.mPar[i];
            `TILE3_TL_PATH.tl_a_ul_write_burst(MY_CPU_ID & 'h1, inBox.mAdr,'hFF,bits_size);
          end     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE64_BURST_TASK
    // ATOMIC_RDW64
    `define SHIPC_ATOMIC_RDW64_TASK ATOMIC_RDW64_DPI()
    task ATOMIC_RDW64_DPI;
      reg [3:0]   bits_size;
      begin
        bits_size = 3;
   
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_a_ul_logical_data(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mAdrHi,inBox.mPar[0],inBox.mPar[1],bits_size);
          1: `TILE1_TL_PATH.tl_a_ul_logical_data(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mAdrHi,inBox.mPar[0],inBox.mPar[1],bits_size);
          2: `TILE2_TL_PATH.tl_a_ul_logical_data(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mAdrHi,inBox.mPar[0],inBox.mPar[1],bits_size);
          3: `TILE3_TL_PATH.tl_a_ul_logical_data(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mAdrHi,inBox.mPar[0],inBox.mPar[1],bits_size);
        endcase
      end
    endtask // ATOMIC_RDW64_TASK
    // WRITE64_64
    `define SHIPC_WRITE64_64_TASK WRITE64_64_DPI()
    task WRITE64_64_DPI;
      begin
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mPar[0]);
          1: `TILE1_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mPar[0]);
          2: `TILE2_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mPar[0]);
          3: `TILE3_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,inBox.mPar[0]);     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE64_64_TASK
    // READ64_BURST
    `define SHIPC_READ64_BURST_TASK READ64_BURST_DPI()
    task READ64_BURST_DPI;
      reg [3:0] bits_size;
      begin
        bits_size = $clog2(inBox.mAdrHi << 3); // unit of 8 bytes
  
        case (MY_CPU_ID)
          0: begin
            `TILE0_TL_PATH.tl_a_ul_read_burst(MY_CPU_ID & 'h1, inBox.mAdr,bits_size);
            for (int i=0;i<inBox.mAdrHi;i++) inBox.mPar[i] = `TILE0_TL_PATH.tl_buf[i];
          end
          1: begin
            `TILE1_TL_PATH.tl_a_ul_read_burst(MY_CPU_ID & 'h1, inBox.mAdr,bits_size);
            for (int i=0;i<inBox.mAdrHi;i++) inBox.mPar[i] = `TILE1_TL_PATH.tl_buf[i];  
          end
          2: begin
            `TILE2_TL_PATH.tl_a_ul_read_burst(MY_CPU_ID & 'h1, inBox.mAdr,bits_size);
            for (int i=0;i<inBox.mAdrHi;i++) inBox.mPar[i] = `TILE2_TL_PATH.tl_buf[i];  
          end
          3: begin
            `TILE3_TL_PATH.tl_a_ul_read_burst(MY_CPU_ID & 'h1, inBox.mAdr,bits_size);
            for (int i=0;i<inBox.mAdrHi;i++) inBox.mPar[i] = `TILE3_TL_PATH.tl_buf[i];  
          end     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE64_BURST_TASK
   
    // READ64_64
    `define SHIPC_READ64_64_TASK READ64_64_DPI()
    task READ64_64_DPI;
      begin
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, inBox.mPar[0]);
          1: `TILE1_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, inBox.mPar[0]);
          2: `TILE2_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, inBox.mPar[0]);
          3: `TILE3_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, inBox.mPar[0]);     
        endcase // case (MY_CPU_ID)
      end
    endtask // READ64_64_TASK
   
    // WRITE32_64
    `define SHIPC_WRITE32_64_TASK WRITE32_64_DPI()
    task WRITE32_64_DPI;
      reg [63:0] d;
      begin
        d[63:32] = inBox.mPar[0];
        d[31:0]  = inBox.mPar[1];
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,d);
          1: `TILE1_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,d);
          2: `TILE2_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,d);
          3: `TILE3_TL_PATH.tl_x_ul_write(MY_CPU_ID & 'h1, inBox.mAdr,d);     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE32_64_TASK
    // WRITE32_8_DPI
    `define SHIPC_WRITE32_8_TASK WRITE32_8_DPI()
    task WRITE32_8_DPI;
      reg [63:0] d;
      reg [7:0]  mask, byte8;
      begin
        mask  = 1 << inBox.mAdr[2:0];
        byte8 = inBox.mPar[0] & 'hff;
   
        d = {8{byte8}};
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,0);
          1: `TILE1_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,0);
          2: `TILE2_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,0);
          3: `TILE3_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,0);     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE32_8_DPI
    // WRITE32_16_DPI
    `define SHIPC_WRITE32_16_TASK WRITE32_16_DPI()
    task WRITE32_16_DPI;
      reg [63:0] d;
      reg [7:0]  mask;
      reg [15:0] word;
      begin
        mask = 3 << (inBox.mAdr[2:1]*2);
        word = inBox.mPar[0] & 'hffff;
          
        d = {4{word}};
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,1);
          1: `TILE1_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,1);
          2: `TILE2_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,1);
          3: `TILE3_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,1);     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE32_16_DPI
    // WRITE32_32_DPI
    `define SHIPC_WRITE32_32_TASK WRITE32_32_DPI()
    task WRITE32_32_DPI;
      reg [63:0] d;
      reg [7:0]  mask;
      begin
        if (inBox.mAdr[2]) 
          mask = 'hF0;
        else 
          mask = 'h0F;
        d[63:32] = inBox.mPar[0];
        d[31:0] = inBox.mPar[0];   
      
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,2);
          1: `TILE1_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,2);
          2: `TILE2_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,2);
          3: `TILE3_TL_PATH.tl_a_ul_write_generic(MY_CPU_ID & 'h1, inBox.mAdr,d,mask,2);     
        endcase // case (MY_CPU_ID)
      end
    endtask // WRITE32_32_DPI
  
    // READ32_64
    `define SHIPC_READ32_64_TASK READ32_64_DPI()
    task READ32_64_DPI;
      reg [63:0] d;
      begin
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, d);
          1: `TILE1_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, d);
          2: `TILE2_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, d);
          3: `TILE3_TL_PATH.tl_x_ul_read(MY_CPU_ID & 'h1, inBox.mAdr, d);     
        endcase // case (MY_CPU_ID)
        inBox.mPar[0] = d[63:32];
        inBox.mPar[1] = d[31:0];      
      end
    endtask // READ32_64_DPI
    // READ32_8_DPI
    `define SHIPC_READ32_8_TASK READ32_8_DPI()
    task READ32_8_DPI;
      reg [63:0] d;
      reg [7:0]  mask;
      begin
        mask = 1 << inBox.mAdr[2:0];
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 0, d);
          1: `TILE1_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 0, d);
          2: `TILE2_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 0, d);
          3: `TILE3_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 0, d);     
        endcase // case (MY_CPU_ID)
      
        case (inBox.mAdr[2:0])
          0 : inBox.mPar[0] = d[(8*0)+7:(8*0)];
          1 : inBox.mPar[0] = d[(8*1)+7:(8*1)];
          2 : inBox.mPar[0] = d[(8*2)+7:(8*2)];
          3 : inBox.mPar[0] = d[(8*3)+7:(8*3)];
          4 : inBox.mPar[0] = d[(8*4)+7:(8*4)];
          5 : inBox.mPar[0] = d[(8*5)+7:(8*5)];
          6 : inBox.mPar[0] = d[(8*6)+7:(8*6)];
          7 : inBox.mPar[0] = d[(8*7)+7:(8*7)];
        endcase
      end
    endtask // READ32_8_DPI
    // READ32_16_DPI
    `define SHIPC_READ32_16_TASK READ32_16_DPI()
    task READ32_16_DPI;
      reg [63:0] d;
      reg [7:0]  mask;
      begin
        mask = 3 << (inBox.mAdr[2:1]*2);      
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 1, d);
          1: `TILE1_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 1, d);
          2: `TILE2_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 1, d);
          3: `TILE3_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 1, d);     
        endcase // case (MY_CPU_ID)
      
        case (inBox.mAdr[2:1])
          0 : inBox.mPar[0] = d[(16*0)+15:(16*0)];
          1 : inBox.mPar[0] = d[(16*1)+15:(16*1)];
          2 : inBox.mPar[0] = d[(16*2)+15:(16*2)];
          3 : inBox.mPar[0] = d[(16*3)+15:(16*3)];
        endcase
      end
    endtask // READ32_16_DPI
    // READ32_32_DPI
    `define SHIPC_READ32_32_TASK READ32_32_DPI()
    task READ32_32_DPI;
      reg [63:0] d;
      reg [7:0]  mask;
      begin
        if 
          (inBox.mAdr[2]) mask = 'hF0;
        else 
          mask = 'h0F;      
        case (MY_CPU_ID)
          0: `TILE0_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 2, d);
          1: `TILE1_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 2, d);
          2: `TILE2_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 2, d);
          3: `TILE3_TL_PATH.tl_x_ul_read_generic(MY_CPU_ID & 'h1, inBox.mAdr, mask, 2, d);     
        endcase // case (MY_CPU_ID)
        
        inBox.mPar[0] = inBox.mAdr[2] ? d[63:32] : d[31:0];
      end
    endtask // READ32_32_DPI
  `endif // ifdef BFM_MODE
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // SHIPC Support Common Codes
  //--------------------------------------------------------------------------------------
  `define     SHIPC_XACTOR_ID     MY_CPU_ID
  `define     SHIPC_CLK           clk
  `include    "dpi_common.incl"
  `undef      SHIPC_CLK
  `undef      SHIPC_XACTOR_ID      
 //--------------------------------------------------------------------------------------
 
  //--------------------------------------------------------------------------------------
  // DVT Flag Processing
  //--------------------------------------------------------------------------------------
  // Core reset only makes sense in Bare Metal Mode
  `ifdef BARE_MODE
    reg tl_monitor_enable = 0;
    wire uart_busy;
    assign uart_busy      = `DUT_UART_BUSY;
    always @(posedge dvtFlags[`DVTF_UART_BUSY]) begin
      dvtFlags[`DVTF_PAT_LO]          = uart_busy;
      dvtFlags[`DVTF_UART_BUSY]       = 0; // self-clear
    end // end always
    always @(posedge dvtFlags[`DVTF_FORCE_CORE_RESET]) begin
      if (dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] == MY_CPU_ID) begin
        force_core_reset();
      end
      dvtFlags[`DVTF_FORCE_CORE_RESET] = 0;  
    end // end always
    always @(posedge dvtFlags[`DVTF_RELEASE_CORE_RESET]) begin
      if (dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] == MY_CPU_ID) begin
        release_core_reset();
      end
      dvtFlags[`DVTF_RELEASE_CORE_RESET] = 0;  
    end // end always
    // Enable the Tilelink monitor for the specified core
    always @(posedge dvtFlags[`DVTF_ENABLE_TL_MONITORS]) begin
      if (dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] == MY_CPU_ID) begin
        tl_monitor_enable = 1;
      end
      dvtFlags[`DVTF_ENABLE_TL_MONITORS] = 0;
    end // end always
    always @(posedge dvtFlags[`DVTF_GET_CORE_RESET_STATUS]) begin
      case (MY_CPU_ID)      
        0: dvtFlags[`DVTF_PAT_LO] = `CORE0_RESET;
        1: dvtFlags[`DVTF_PAT_LO] = `CORE1_RESET;
        2: dvtFlags[`DVTF_PAT_LO] = `CORE2_RESET;
        3: dvtFlags[`DVTF_PAT_LO] = `CORE3_RESET;
      endcase
      dvtFlags[`DVTF_GET_CORE_RESET_STATUS] = 0; // self-clear
    end // end always
  `endif
  always @(*) dvtFlags[`DVTF_GET_PROGRAM_LOADED]    = `PROGRAM_LOADED;
  always @(posedge dvtFlags[`DVTF_FORCE_TILE_RESET]) begin
    if (dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] == MY_CPU_ID) begin
      force_tile_reset();
    end
    dvtFlags[`DVTF_FORCE_TILE_RESET] = 0;  
  end // end always
  always @(posedge dvtFlags[`DVTF_RELEASE_TILE_RESET]) begin
    if (dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] == MY_CPU_ID) begin
      release_tile_reset();
    end
    dvtFlags[`DVTF_RELEASE_TILE_RESET] = 0;
  end // end always
  always @(posedge dvtFlags[`DVTF_GET_CORE_STATUS]) begin
    if      (dvtFlags[1:0] == 0) dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] = `CEPREGS_PATH.core0_status;
    else if (dvtFlags[1:0] == 1) dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] = `CEPREGS_PATH.core1_status;
    else if (dvtFlags[1:0] == 2) dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] = `CEPREGS_PATH.core2_status;
    else if (dvtFlags[1:0] == 3) dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO] = `CEPREGS_PATH.core3_status;
    dvtFlags[`DVTF_GET_CORE_STATUS] = 0;
  end
  //--------------------------------------------------------------------------------------
   
  //--------------------------------------------------------------------------------------
  // Per core reset control
  //-------------------------------------------------------------------------------------- 
  // Put the core in reset that is not active
  initial begin
    // In bare metal mode, the cores will default to reset to allow
    // for backdoor loading of the executable to main memory.
    `ifdef BARE_MODE;
      force_tile_reset();
    `endif
    // In BFM mode,  we'll allow for a few cycles for the C side to come
    // up, otherwise we'll hold the TL master in reset
    `ifdef BFM_MODE
      repeat(10) @(posedge clk);
      if (!myIsActive) begin
        force_tile_reset();  
      end // if (!myIsActive)
    `endif
  end // initial begin
  // Task to force the current drivers tile to reset
  task force_tile_reset;
    begin
      case (MY_CPU_ID)
        0: begin
          `logI("Forcing Tile #0 in reset...");
          force `TILE0_RESET = 1;
        end
        1: begin
          `logI("Forcing Tile #1 in reset...");
          force `TILE1_RESET = 1;
        end
        2: begin
          `logI("Forcing Tile #2 in reset...");
          force `TILE2_RESET = 1;
        end
        3: begin
          `logI("Forcing Tile #3 in reset...");
          force `TILE3_RESET = 1;
        end     
      endcase // case (MY_CPU_ID)
    end
  endtask
  // Task to release the current drivers tile from reset
  task release_tile_reset;
    begin
      case (MY_CPU_ID)
        0: begin
          `logI("Releasing Tile #0 reset...");
          release `TILE0_RESET;
        end
        1: begin
          `logI("Releasing Tile #1 reset...");
          release `TILE1_RESET;
        end
        2: begin
          `logI("Releasing Tile #2 reset...");
          release `TILE2_RESET;
        end
        3: begin
          `logI("Releasing Tile #3 reset...");
          release `TILE3_RESET;
        end     
      endcase // case (MY_CPU_ID)
    end
  endtask
  // The following tasks allow for stimulation of the Core (within the Tile) reset
  `ifdef BARE_MODE
    // Task to force the current drivers core into reset
    task force_core_reset;
      begin
        case (MY_CPU_ID)
          0: begin
            `logI("Forcing Core #0 in reset...");
            force `CORE0_RESET = 1;
          end
          1: begin
            `logI("Forcing Core #1 in reset...");
            force `CORE1_RESET = 1;
          end
          2: begin
            `logI("Forcing Core #2 in reset...");
            force `CORE2_RESET = 1;
          end
          3: begin
            `logI("Forcing Core #3 in reset...");
            force `CORE3_RESET = 1;
          end     
        endcase // case (MY_CPU_ID)
      end
    endtask
    // Task to release the current drivers core from reset
    task release_core_reset;
      begin
        case (MY_CPU_ID)
          0: begin
            `logI("Releasing Core #0 reset...");
            release `CORE0_RESET;
          end
          1: begin
            `logI("Releasing Core #1 reset...");
            release `CORE1_RESET;
          end
          2: begin
            `logI("Releasing Core #2 reset...");
            release `CORE2_RESET;
          end
          3: begin
            `logI("Releasing Core #3 reset...");
            release `CORE3_RESET;
          end     
        endcase // case (MY_CPU_ID)
      end
    endtask
  
  `endif
  //-------------------------------------------------------------------------------------- 
  //--------------------------------------------------------------------------------------
  // Support functions for the RISC-V ISA Tests (which WILL require BARE_MODE)
  //--------------------------------------------------------------------------------------
  reg             pcPass              = 0;
  reg             pcFail              = 0;
  `ifdef RISCV_TESTS
    wire [63:0]   curPC;
    wire          curPCValid;
    wire          curPCReset;
    reg           DisableStuckChecker = 0;
    reg           SingleCoreOnly      = 0;
    int           stuckCnt            = 0;
    reg [63:0]    lastPc              = 0;
    wire          pcStuck             = (stuckCnt >= 500);
    // Get Pass / Fail Status
    always @(posedge dvtFlags[`DVTF_GET_PASS_FAIL_STATUS]) begin
      dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO]   = {pcFail, pcPass};
      dvtFlags[`DVTF_GET_PASS_FAIL_STATUS]  = 0; // self-clear
    end
    
    // Disable Stuck Checker
    always @(posedge dvtFlags[`DVTF_DISABLE_STUCKCHECKER]) begin
      `logI("DisableStuckChecker = 1");
      DisableStuckChecker                   = 1;
      dvtFlags[`DVTF_DISABLE_STUCKCHECKER]  = 0; // self-clear
    end   
    always @(posedge dvtFlags[`DVTF_SINGLE_CORE_ONLY]) begin
      `logI("SingleCoreOnly = 1");
      SingleCoreOnly                    = 1;
      DisableStuckChecker               = 1;
      dvtFlags[`DVTF_SINGLE_CORE_ONLY]  = 0; // self-clear
    end   
    // Generate per-CPU items
    generate
      case (MY_CPU_ID)
        0: begin
          assign curPC          = `CORE0_PC;
          assign curPCValid     = `CORE0_VALID;
          assign curPCReset     = `CORE0_RESET;
        end
        1: begin
          assign curPC          = `CORE1_PC;
          assign curPCValid     = `CORE1_VALID;
          assign curPCReset     = `CORE1_RESET;
        end
        2: begin
          assign curPC          = `CORE2_PC;
          assign curPCValid     = `CORE2_VALID;
          assign curPCReset     = `CORE2_RESET;
        end
        default: begin
          assign curPC          = `CORE3_PC;
          assign curPCValid     = `CORE3_VALID;
          assign curPCReset     = `CORE3_RESET;
        end
      endcase
    endgenerate
    // Take some action when a pass or failure is detected
    always @(posedge pcPass or posedge pcFail) begin
      if (~curPCReset) begin
        `logI("C%0d Pass/Fail Detected!!!... Put it to sleep", MY_CPU_ID);
        
        repeat (20) @(posedge clk);
        case (MY_CPU_ID)
          0       : force `CORE0_RESET = 1;
          1       : force `CORE1_RESET = 1;
          2       : force `CORE2_RESET = 1;
          default : force `CORE3_RESET = 1;
        endcase          
      end
    end // end always
   
    // Pass / Fail based on program counting reaching a particular location in the test 
    // Pass Condition - <test_pass> || <pass> || <finish> || <write_tohost>
    // Fail Condition - pcStuck || <test_fail> || <fail> || <hangme>
    always @(*) begin
      // A PC Stuck condition has been detected
      if (pcStuck && ~DisableStuckChecker) begin
        `logE("PC seems to be stuck!!!! Terminating...");
        pcFail = 1;
      end else if (curPCValid) begin
        // Did the PassFail.hex load correctly?
        if (`RISCV_PASSFAILVALID) begin
          case (curPC)
            `RISCV_PASSFAIL[0]  : pcPass = 1;
            `RISCV_PASSFAIL[2]  : pcPass = 1;
            `RISCV_PASSFAIL[3]  : pcPass = 1;
            `RISCV_PASSFAIL[4]  : pcFail = 1;
            `RISCV_PASSFAIL[1]  : pcFail = 1;
            default             : if (SingleCoreOnly && (MY_CPU_ID != 0)) pcPass = 1;
          endcase
        end else begin
          pcFail = 1;
        end // if (`RISCV_PASSFAILVALID)
      end // if (curPCValid)
    end   // end always @(*)
    // A running counter to indicate how many times the current PC has been "stuck" at the same value
    always @(posedge clk) begin
      if (curPCValid) begin
        lastPc <= curPC;
        if (curPC == lastPc) 
          stuckCnt <= stuckCnt + 1;
        else 
          stuckCnt <= 0;
      end
    end // end always
  
  `endif //  `ifdef RISCV_TESTS
  //--------------------------------------------------------------------------------------
endmodule // cpu_driver
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      ptw_monitor.v
// Program:        Common Evaluation Platform (CEP)
// Description:    
// Notes:          
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "v2c_top.incl"
module ptw_monitor
  (
   input 	clk,
   input trace_valid,
   input 	pc_valid,
   input [63:0] pc,
   // requestor 0=Dcache, 1=Icache
   input 	io_requestor_x_req_ready,
   input 	io_requestor_x_req_valid,
   input [26:0] io_requestor_x_req_bits_bits_addr,
   input 	io_requestor_x_resp_valid,
   input 	io_requestor_x_resp_bits_ae,
   input [53:0] io_requestor_x_resp_bits_pte_ppn,
   input 	io_requestor_x_resp_bits_pte_d,
   input 	io_requestor_x_resp_bits_pte_a,
   input 	io_requestor_x_resp_bits_pte_g,
   input 	io_requestor_x_resp_bits_pte_u,
   input 	io_requestor_x_resp_bits_pte_x,
   input 	io_requestor_x_resp_bits_pte_w,
   input 	io_requestor_x_resp_bits_pte_r,
   input 	io_requestor_x_resp_bits_pte_v
   );
   //
   always @(posedge clk) begin
      if (io_requestor_x_resp_valid) begin
	 if (!io_requestor_x_resp_bits_pte_v) begin
	    `logI("-->PTW miss: VPN=0x%08x",io_requestor_x_req_bits_bits_addr);
	 end
	 else begin
	    `logI("-->PTW hit: VPN=0x%08x PPN=0x%05x d/a/g/u/x/w/r=%b_%b_%b_%b_%b_%b_%b",
		  io_requestor_x_req_bits_bits_addr,
		  io_requestor_x_resp_bits_pte_ppn[19:0],
		  io_requestor_x_resp_bits_pte_d,
		  io_requestor_x_resp_bits_pte_a,
		  io_requestor_x_resp_bits_pte_g,
		  io_requestor_x_resp_bits_pte_u,
		  io_requestor_x_resp_bits_pte_x,
		  io_requestor_x_resp_bits_pte_w,
		  io_requestor_x_resp_bits_pte_r);
	 end
      end // if (io_requestor_x_resp_valid)
   end // always @ (posedge clk)
endmodule // ptw_monitor
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      RocketTile_beh.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Behavioral replacement of all instances of RocketTile
//                 in the generated verilog
// Notes:          Updated for Chipyard-based CEP
//
//--------------------------------------------------------------------------------------
module RocketTile_beh(
  input         clock,
  input         reset,
  output        auto_wfi_out_0,
  input         auto_int_local_in_3_0,  // unused
  input         auto_int_local_in_2_0,  // unused
  input         auto_int_local_in_1_0,  // unused
  input         auto_int_local_in_1_1,  // unused
  input         auto_int_local_in_0_0,  // unused
  input  [1:0]  auto_hartid_in,         // unused
  input         auto_tl_other_masters_out_a_ready,
  output        auto_tl_other_masters_out_a_valid,
  output [2:0]  auto_tl_other_masters_out_a_bits_opcode,
  output [2:0]  auto_tl_other_masters_out_a_bits_param,
  output [3:0]  auto_tl_other_masters_out_a_bits_size,
  output [1:0]  auto_tl_other_masters_out_a_bits_source,
  output [31:0] auto_tl_other_masters_out_a_bits_address,
  output [7:0]  auto_tl_other_masters_out_a_bits_mask,
  output [63:0] auto_tl_other_masters_out_a_bits_data,
  output        auto_tl_other_masters_out_b_ready,
  input         auto_tl_other_masters_out_b_valid,
  input  [1:0]  auto_tl_other_masters_out_b_bits_param,
  input  [3:0]  auto_tl_other_masters_out_b_bits_size,
  input  [1:0]  auto_tl_other_masters_out_b_bits_source,
  input  [31:0] auto_tl_other_masters_out_b_bits_address,
  input         auto_tl_other_masters_out_c_ready,
  output        auto_tl_other_masters_out_c_valid,
  output [2:0]  auto_tl_other_masters_out_c_bits_opcode,
  output [2:0]  auto_tl_other_masters_out_c_bits_param,
  output [3:0]  auto_tl_other_masters_out_c_bits_size,
  output [1:0]  auto_tl_other_masters_out_c_bits_source,
  output [31:0] auto_tl_other_masters_out_c_bits_address,
  output [63:0] auto_tl_other_masters_out_c_bits_data,
  output        auto_tl_other_masters_out_d_ready,
  input         auto_tl_other_masters_out_d_valid,
  input  [2:0]  auto_tl_other_masters_out_d_bits_opcode,
  input  [1:0]  auto_tl_other_masters_out_d_bits_param,
  input  [3:0]  auto_tl_other_masters_out_d_bits_size,
  input  [1:0]  auto_tl_other_masters_out_d_bits_source,
  input  [1:0]  auto_tl_other_masters_out_d_bits_sink,
  input         auto_tl_other_masters_out_d_bits_denied,
  input  [63:0] auto_tl_other_masters_out_d_bits_data,
  input         auto_tl_other_masters_out_d_bits_corrupt,
  input         auto_tl_other_masters_out_e_ready,
  output        auto_tl_other_masters_out_e_valid,
  output [1:0]  auto_tl_other_masters_out_e_bits_sink
);
 
  // Tie-off unused outputs
  assign auto_wfi_out_0 = 0;
  // Instantiate the Tilelink Master Behavioral Model
  tl_master_beh #(
    .CHIP_ID    (0),  // Will be overwritten by the testbench for each core and thus
                      // the auto_hartid_in is unused
    .SRC_SIZE   (2),  // Equivalent to OpenTitan's TL_AIW
    .SINK_SIZE  (2),  // Equivalent to OpenTitan's TL_DIW
    .BUS_SIZE   (8),  // Equivalent to OpenTitan's TL_DBW
    .ADR_WIDTH  (32)  // Equivalent to OpenTitan's TL_DW
  ) tl_master (
    .clock                        (clock),
    .reset                        (reset),
    .tl_master_a_ready            (auto_tl_other_masters_out_a_ready),
    .tl_master_a_valid            (auto_tl_other_masters_out_a_valid),
    .tl_master_a_bits_opcode      (auto_tl_other_masters_out_a_bits_opcode),
    .tl_master_a_bits_param       (auto_tl_other_masters_out_a_bits_param),
    .tl_master_a_bits_size        (auto_tl_other_masters_out_a_bits_size),
    .tl_master_a_bits_source      (auto_tl_other_masters_out_a_bits_source),
    .tl_master_a_bits_address     (auto_tl_other_masters_out_a_bits_address),
    .tl_master_a_bits_mask        (auto_tl_other_masters_out_a_bits_mask),
    .tl_master_a_bits_data        (auto_tl_other_masters_out_a_bits_data),
    .tl_master_a_bits_corrupt     (auto_tl_other_masters_out_a_bits_corrupt),
    .tl_master_b_ready            (auto_tl_other_masters_out_b_ready),
    .tl_master_b_valid            (auto_tl_other_masters_out_b_valid),
    .tl_master_b_bits_opcode      (3'h6),
    .tl_master_b_bits_size        (4'h6),
    .tl_master_b_bits_mask        (8'hff),
    .tl_master_b_bits_corrupt     (1'b0),
    .tl_master_b_bits_param       (auto_tl_other_masters_out_b_bits_param),
    .tl_master_b_bits_source      (auto_tl_other_masters_out_b_bits_source),
    .tl_master_b_bits_address     (auto_tl_other_masters_out_b_bits_address),
    .tl_master_c_ready            (auto_tl_other_masters_out_c_ready),
    .tl_master_c_valid            (auto_tl_other_masters_out_c_valid),
    .tl_master_c_bits_opcode      (auto_tl_other_masters_out_c_bits_opcode),
    .tl_master_c_bits_param       (auto_tl_other_masters_out_c_bits_param),
    .tl_master_c_bits_size        (auto_tl_other_masters_out_c_bits_size),
    .tl_master_c_bits_source      (auto_tl_other_masters_out_c_bits_source),
    .tl_master_c_bits_address     (auto_tl_other_masters_out_c_bits_address),
    .tl_master_c_bits_data        (auto_tl_other_masters_out_c_bits_data),
    .tl_master_c_bits_corrupt     (auto_tl_other_masters_out_c_bits_corrupt),
    .tl_master_d_ready            (auto_tl_other_masters_out_d_ready),
    .tl_master_d_valid            (auto_tl_other_masters_out_d_valid),
    .tl_master_d_bits_opcode      (auto_tl_other_masters_out_d_bits_opcode),
    .tl_master_d_bits_param       (auto_tl_other_masters_out_d_bits_param),
    .tl_master_d_bits_size        (auto_tl_other_masters_out_d_bits_size),
    .tl_master_d_bits_source      (auto_tl_other_masters_out_d_bits_source),
    .tl_master_d_bits_sink        (auto_tl_other_masters_out_d_bits_sink),
    .tl_master_d_bits_denied      (auto_tl_other_masters_out_d_bits_denied),
    .tl_master_d_bits_data        (auto_tl_other_masters_out_d_bits_data),
    .tl_master_d_bits_corrupt     (auto_tl_other_masters_out_d_bits_corrupt),
    .tl_master_e_ready            (auto_tl_other_masters_out_e_ready),
    .tl_master_e_valid            (auto_tl_other_masters_out_e_valid),
    .tl_master_e_bits_sink        (auto_tl_other_masters_out_e_bits_sink)
   );
endmodule // RocketTile_beh
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:     sd_spi_model.v
// Program:       Common Evaluation Platform (CEP)
// Description:   SD SPI Simulation Model originally released by [email protected] and
//                subsequented extracted from "Warke, Tejas Pravin, "Verification of 
//                SD/MMC Controller IP Using UVM" (2018). Thesis. Rochester Institute
//                of Technology"
//
// Notes:         Specification referenced is:
//                "SD Specifications Part 1 Physical Layer Simplified Specification 8.00, September 23, 2020"
//
//                - CARD_VHS changed to 4'b0001 (indicating support for 2.7-3.6V)
//                - CMD8 R7 response updated to be compliant with specification.  As we are operating in SPI
//                  mode, the R7 response is taken from Section 7.3.2.6 of the specification
//                - Changed CSD_VER to v2.0 (2'b01) given the bootrom assumes v2.0 or later
//                - Modified ist (initialization logic) to be compatible with Figure 7-2 in the specification
//                - Modified ACMD41 response per specification (in SPI mode it generates a R1 response, not R3)
//                - All commands that have not been EXPLICITLY verified have been removed
//                - Restored processing/setting of the block len (was commented out)
//                - OCR bit-width/mapping corrected per spec
//                - STM coding updated to properly sequence through the PowerOff -> PowerOn -> Idle states
//                - @(posedge sclk) removed from CardResponse state given that it caused a bit alignment
//                  issue when reading data
//--------------------------------------------------------------------------------------
// Version history :
// 1.0 2016.06.13 1st released by [email protected] 
//
// Most of the Card information is referenced from Toshiba 2G and 256MB SD card 
// 
// Memory size of this model should be 2GB, however only 2MB is implemented to reduce system memory required during simulation
// The initial value of all internal memory is word_address + 3. 
//
`include "suite_config.v"
`include "v2c_top.incl"
`include "cep_hierMap.incl"
`define UD 1 
module spi_sd_model ( rstn , ncs, sclk, miso, mosi);
input rstn; 
input ncs; 
input sclk; 
input mosi; 
output miso; 
parameter tNCS = 1;
parameter tNCR = 1;
parameter tNCX = 0;
parameter tNAC = 1;
parameter tNWR = 1;
parameter tNBR = 0;
parameter tNDS = 0;
parameter tNEC = 0;
parameter tNRC = 1;
parameter MEM_SIZE = 2048*1024; //2M 
// State Machine state definitions
parameter PowerOff      = 0; 
parameter PowerOn       = 1; 
parameter IDLE          = 2; 
parameter CmdBit47      = 3; 
parameter CmdBit46      = 4; 
parameter CommandIn     = 5; 
parameter CardResponse  = 6; 
parameter ReadCycle     = 7; 
parameter WriteCycle    = 8; 
parameter DataResponse  = 9; 
parameter CsdCidScr     = 10; 
parameter WriteStop     = 11; 
parameter WriteCRC      = 12; 
integer i = 0; // counter index 
integer j = 0; // counter index 
integer k = 0; // /for MISO (bit count of a byte) 
integer m = 0; // for MOSI ( bit count during CMD12) 
reg miso; 
reg [7:0] flash_mem [0:MEM_SIZE - 1]; 
reg [7:0] read_data;
reg [7:0] token; //captured token during CMD24, CMD25 
reg  [15:0] crc16_in;  
reg  [6:0]  crc7_in;
reg [15:0]  crc16_out;
reg  [7:0]  sck_cnt; // 74 sclk after power on
reg  [31:0] csd_reg = 0;  
reg  init_done; // must  be  defined  before  ocr .v  
reg  [3:0] st; //SD Card  internal  state  
reg  app_cmd; //  
reg  [511:0]  ascii_command_state;  
reg  [2:0]  ist ; // initialization stage  
reg  [45:0] cmd_in;  
reg  [45:0] serial_in;
wire [5:0] cmd_index = cmd_in[45:40]; 
wire [31:0] argument = cmd_in[39:8]; 
wire [6:0] crc = cmd_in[7:1]; 
wire read_single = (cmd_index == 17); 
wire read_multi = (cmd_index == 18); 
wire write_single = (cmd_index == 24); 
wire write_multi = (cmd_index == 25); 
wire pgm_csd = (cmd_index == 27); 
wire send_csd = (cmd_index == 9); 
wire send_cid = (cmd_index == 10); 
wire send_scr = (cmd_index == 51) && app_cmd; 
wire read_cmd = read_single | read_multi; 
wire write_cmd = write_single | write_multi; 
wire mem_rw = read_cmd | write_cmd; 
reg [31:0] start_addr; 
reg [31:0] block_len; 
reg [7:0] capture_data; // for debugging 
reg [3:0] VHS; // Input VHS through MOSI 
reg [7:0] check_pattern = 0; // for CMD8
wire [3:0] CARD_VHS     = 4'b0001; // SD card accept voltage range
wire VHS_match = (VHS == CARD_VHS);
reg [1:0] multi_st ; // for CMD25 
reg [45:0] serial_in1 ; // for CMD25
wire [5:0] cmd_in1 = serial_in1 [45:40]; // for CMD25
wire stop_transmission = (cmd_in1 == 12); //for CMD25 
//Do not change the positions of these include files 
// Also, ocr .v must be included before csd.v 
wire CCS        = 1'b0;
wire CARD_UHSII = 1'b0;
wire CARD_S18A  = 1'b0;
wire [31:0] OCR = {init_done , CCS, CARD_UHSII, 4'b0000, CARD_S18A, 6'b111111, 18'd0}; //3.0~3.6V, no S18A 
wire [1:0] DAT_BUS_WIDTH = 2'b00; //1bit 
wire SECURE_MODE = 1'b0; // not in secure mode 
wire [15:0] SD_CARD_TYPE = 16'h0000; // regular SD 
wire [31:0] SIZE_OF_PROTECTED_AREA = 32'd2048; // 
// protected area = SIZE_OF_PROTECTED_AREA * MULT * BLOCK_LEN 
wire [7:0] SPEED_CLASS = 8'h4; // class 10 
wire  [7:0] PERFORMANCE_MOVE  =  8'd100 ; // 100MB/ sec  
wire  [3:0]  AU_SIZE  =  7; // 1MB  
wire  [15:0]  ERASE_SIZE  =  16'd100 ; // Erase  100 AU  
wire  [5:0] ERASE_TIMEOUT  =  16'd50 ; // 50  sec  
wire  [1:0]  ERASE_OFFSET  =  0; // 0  sec  
wire [511:0] SSR = {DAT_BUS_WIDTH, SECURE_MODE, 6'b0, 6'b0, SD_CARD_TYPE, SIZE_OF_PROTECTED_AREA, SPEED_CLASS, 
                    PERFORMANCE_MOVE, AU_SIZE,  4'b0 , ERASE_SIZE,  ERASE_TIMEOUT, ERASE_OFFSET,  400'b0};
wire [7:0] MID = 8'd02; 
wire [15:0] OID = 16'h544D; 
wire [39:0] PNM = "SD02G"; 
wire [7:0] PRV = 8'h00; 
wire [31:0] PSN = 32'h6543a238; 
wire [11:0] MDT = {4'd15, 8'h12}; 
wire [6:0] CID_CRC = 7'b1100001; //dummy 
wire [127:0] CID = {MID, OID, PNM, PRV, PSN, 4'b0, MDT, CID_CRC ,1'b1}; 
wire [1:0] CSD_VER = 2'b01; // Ver 2.0 
wire [7:0] TAAC = {1'b0, 4'd7, 3'd2}; //3.0*100ns 
wire [7:0] NSAC = 8'd101; 
wire [7:0] TRAN_SPEED = 8'h32; 
wire [3:0] READ_BL_LEN = 4'd11; //2^READ_BL_LEN, 2048bytes 
wire READ_BL_PARTIAL = 1'b1; // always 1 in SD card 
wire WRITE_BLK_MISALIGN = 1'b0; // crossing physical blocak boundaries is invalid 
wire READ_BLK_MISALIGN = 1'b0; // crossing physical blocak boundaries is invalid 
wire DSR_IMP = 1'b0; //no DSR implemented 
wire [11:0] C_SIZE = 2047; 
wire [2:0] VDD_R_CURR_MIN = 3'd1; //1mA 
wire [2:0] VDD_R_CURR_MAX = 3'd2; //10mA 
wire [2:0] VDD_W_CURR_MIN = 3'd1; //1mA 
wire [2:0] VDD_W_CURR_MAX = 3'd2; //10mA 
wire [2:0] C_SIZE_MULT = 3'd7; //MULT=512 
wire ERASE_BLK_EN = 1'b0; // Erase in unit of SECTOR_SIZE 
wire [6:0] SECTOR_SIZE = 7'd127; //128 WRITE BLOCK 
wire [6:0] WP_GRP_SIZE = 7'd127; //128 
wire WP_GRP_ENABLE = 1'b0; //no GROUP WP 
wire [2:0] R2W_FACTOR = 3'd0; 
wire [3:0] WRITE_BL_LEN = READ_BL_LEN; 
wire WRITE_BL_PARTIAL = 1'b0; // 
wire iFILE_FORMAT_GRP = 1'b0; 
wire iCOPY = 1'b0; 
wire iPERM_WRITE_PROTECT = 1'b0; // DISABLE PERMENTAL WRITE PROTECT 
wire iTMP_WRITE_PROTECT = 1'b0; // 
wire [1:0] iFILE_FORMAT = 1'b0; //
wire [6:0] iCSD_CRC = 7'b1010001; // dummy 
reg FILE_FORMAT_GRP; 
reg COPY; 
reg PERM_WRITE_PROTECT; 
reg TMP_WRITE_PROTECT; 
reg [1:0] FILE_FORMAT; 
reg [6:0] CSD_CRC; 
wire v1sdsc = (CSD_VER == 0) & ~CCS; // Ver 1, SDSC 
wire v2sdsc = (CSD_VER == 1) & ~CCS; // Ver 2, SDSC 
wire v2sdhc = (CSD_VER == 1) & CCS; // Ver 2, SDHC 
wire sdsc = ~CCS; 
wire [127:0] CSD = {CSD_VER, 6'b0, TAAC, NSAC, TRAN_SPEED, 12'b0101_1011_0101 , READ_BL_LEN, 
                    READ_BL_PARTIAL, WRITE_BLK_MISALIGN, READ_BLK_MISALIGN, DSR_IMP,  
                    2'b0 , C_SIZE , VDD_R_CURR_MIN, VDD_R_CURR_MAX, VDD_W_CURR_MIN,  
                    VDD_W_CURR_MAX, C_SIZE_MULT, ERASE_BLK_EN, SECTOR_SIZE, WP_GRP_SIZE, 
                    WP_GRP_ENABLE, 2'b00, R2W_FACTOR, WRITE_BL_LEN, WRITE_BL_PARTIAL, 5'b0, 
                    FILE_FORMAT_GRP, COPY, PERM_WRITE_PROTECT, TMP_WRITE_PROTECT, FILE_FORMAT, 
                    2'b0, CSD_CRC, 1'b1} ;  
wire  OUT_OF_RANGE = 1'b0 ;  
wire  ADDRESS_ERROR = 1'b0 ;  
wire  BLOCK_LEN_ERROR = 1'b0 ;  
wire  ERASE_SEQ_ERROR = 1'b0 ;  
wire  ERASE_PARAM = 1'b0 ;  
wire  WP_VIOLATION = 1'b0 ;  
wire  CARD_IS_LOCKED = 1'b0 ;  
wire  LOCK_UNLOCK_FAILED = 1'b0 ;  
wire  COM_CRC_ERROR = 1'b0 ;  
wire  ILLEGAL_COMMAND = 1'b0 ;  
wire CARD_ECC_FAILED = 1'b0; 
wire CC_ERROR = 1'b0; 
wire ERROR = 1'b0; 
wire CSD_OVERWRITE = 1'b0; 
wire WP_ERASE_SKIP = 1'b0; 
wire CARD_ECC_DISABLE = 1'b0; 
wire ERASE_RESET = 1'b0; 
wire [3:0] CURRENT_ST = 1; // ready 
wire READY_FOR_DATA = 1'b1; 
wire APP_CMD = 1'b0; 
wire AKE_SEQ_ERROR = 1'b0; 
wire IN_IDLE_ST = (CURRENT_ST == 4'b1); 
wire [15:0] CSR = {OUT_OF_RANGE, ADDRESS_ERROR, BLOCK_LEN_ERROR , ERASE_SEQ_ERROR , ERASE_PARAM, WP_VIOLATION, CARD_IS_LOCKED, 
                   LOCK_UNLOCK_FAILED, COM_CRC_ERROR, ILLEGAL_COMMAND, CARD_ECC_FAILED, CC_ERROR, ERROR, 2'b0 , CSD_OVERWRITE, 
                    WP_ERASE_SKIP, CARD_ECC_DISABLE , ERASE_RESET, CURRENT_ST, READY_FOR_DATA, 2'b0 , APP_CMD, 1'b0, AKE_SEQ_ERROR, 3'b0}; 
wire [3:0] SCR_STRUCTURE = 4'd0; // Ver1.0 
wire  [3:0]  SD_SPEC = 4'd2; // Ver2.0 or 3.0  
wire  DATA_STAT_AFTER_ERASE = 1'b1 ;  
wire  [2:0]  SD_SECURITY = 3'd4 ; // Ver3.0  
wire  [3:0]  SD_BUS_WIDTHS = 4'b0001 ; // 1 bit  
wire  SD_SPEC3 = 1'b1 ; // Ver3.0  
wire  [13:0]  CMD_SUPPORT = 14'b0 ; //  
wire [63:0] SCR = {SCR_STRUCTURE, SD_SPEC, DATA_STAT_AFTER_ERASE, SD_SECURITY, SD_BUS_WIDTHS, SD_SPEC3 , 13'b0, CMD_SUPPORT, 32'b0}; 
task write_flash_byte (input[31:0] addr, input [7:0] data); begin
  `logI("SD_MODEL: Backdoor Write 0x%02x to address 0x%08x", data, addr);
  flash_mem[addr] = data;
  #1;
end
endtask
task R1; input [7:0] data ; begin 
  `logI("SD_MODEL: SD R1: 0x%02x at %0d ns ", data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 8; k = k + 1) begin 
    @(negedge sclk); miso = data[7 - k]; 
  end 
end 
endtask 
task R1b; input [7:0] data ; begin 
  `logI("SD_MODEL: SD R1B: 0x%02x at %0d ns", data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 8; k = k + 1) begin 
    @(negedge sclk); miso = data[7 - k]; 
  end 
end 
endtask 
task R2; input [15:0] data ; begin 
  `logI("SD_MODEL: SD R2: 0x%04x at %0d ns", data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 16; k = k + 1) begin 
    @(negedge sclk); miso = data[15 - k]; 
  end 
end 
endtask
task R3; input [39:0] data ; begin 
  `logI("SD_MODEL: SD R3: 0x%10x at %0d ns", data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 40; k = k + 1) begin 
    @(negedge sclk); miso = data[39 - k]; 
  end 
end 
endtask 
task R7; input [39:0] data ; begin 
  `logI("SD_MODEL: SD R7: 0x%10x at %0d ns", data,`SYSTEM_SIM_TIME); 
  for (k = 0; k < 40; k = k + 1) begin 
    @(negedge sclk); miso = data[39 - k]; 
  end 
end
endtask 
task DataOut; input [7:0] data ; begin 
  `logI("SD_MODEL:  SD DataOut 0x%02x at %0d ns", data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 8; k = k + 1) begin 
    @(negedge sclk); miso = data[7 - k]; 
  end 
end 
endtask 
task DataIn ; begin 
  for (k = 7; k >= 0; k = k - 1) begin 
    @(posedge sclk) capture_data[k] = mosi; 
  end 
  `logI("SD_MODEL: SD DataIn : %2h at %0d ns", capture_data, `SYSTEM_SIM_TIME ) ; 
end 
endtask 
always @(*) begin 
  if (pgm_csd) csd_reg = argument; 
end 
task CRCOut; input [15:0] data ; begin 
  `logI("SD_MODEL:  SD CRC Out 0x%04x at %0d ns" ,data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 16; k = k + 1) begin 
    @(negedge sclk); miso = data[15 - k]; 
  end 
end 
endtask 
task TokenOut; input [7:0] data ; begin 
  `logI("SD_MODEL:  SD TokenOut 0x%02x at %0d ns" ,data, `SYSTEM_SIM_TIME); 
  for (k = 0; k < 8; k = k + 1) begin 
    @(negedge sclk); miso = data[7 - k]; 
  end 
end 
endtask
function [15:0] crc16_round(input [15:0] crc, [7:0] data); begin
  crc = (crc >> 8) | (crc << 8);
  crc ^= data;
  crc ^= (crc >> 4) & 4'hF;
  crc ^= crc << 12;
  crc ^= (crc & 8'hFF) << 5;
  crc16_round = crc;
end
endfunction
always @(*) begin 
  if (~pgm_csd) begin 
    FILE_FORMAT_GRP = iFILE_FORMAT_GRP; 
    COPY = iCOPY; 
    PERM_WRITE_PROTECT = iPERM_WRITE_PROTECT; 
    TMP_WRITE_PROTECT = iTMP_WRITE_PROTECT; 
    FILE_FORMAT = iFILE_FORMAT; 
    CSD_CRC = iCSD_CRC ; 
  end else begin 
    FILE_FORMAT_GRP = argument [15]; 
    COPY = argument [14]; 
    PERM_WRITE_PROTECT = argument [13]; 
    TMP_WRITE_PROTECT = argument [12]; 
    FILE_FORMAT = argument [11:10]; 
    CSD_CRC = argument [7:1]; 
  end 
end 
always @( * )  begin  
  if (~ rstn ) app_cmd = 1'b0;  
  else if ( cmd_index == 55 && st == IDLE ) app_cmd = 1;  
  else if ( cmd_index != 55 && st == IDLE ) app_cmd = 0;  
end 
always @(*) begin 
  if (sdsc && mem_rw) 
    start_addr = argument; 
  else if (v2sdhc && mem_rw) 
    start_addr = argument * block_len; 
end 
// Set the Block Length
always @(*) begin 
  if (v2sdhc) 
    block_len = 512; 
  else if (sdsc && cmd_index == 0) block_len = (READ_BL_LEN == 9) ? 512 : (READ_BL_LEN == 10) ? 1024 : 2048; 
  else if (sdsc && cmd_index == 16) block_len = argument [31:0]; 
end 
always @(*) begin 
  if (cmd_index == 8) VHS = argument[11:8]; 
  if (cmd_index == 8) check_pattern = argument[7:0]; 
end 
// Logic for controlling the "initialization" of the SD Card model
always @(*) begin 
  if (ist == 0 && cmd_index == 0) begin 
    ist = 1;
    `logI("SD_MODEL: Moving to InitStage %d/3 at %0d ns" , ist, `SYSTEM_SIM_TIME); 
  end 
  if (ist == 1 && cmd_index == 8) begin 
    ist = 2;
    `logI("SD_MODEL: Moving to InitStage %d/3 at %0d ns" , ist, `SYSTEM_SIM_TIME); 
  end 
  if (ist == 2 && cmd_index == 41) begin 
    ist = 3;
    `logI("SD_MODEL: Moving to InitStage %d/3 at %0d ns" , ist, `SYSTEM_SIM_TIME); 
  end 
  if ( ist == 3 && st == IDLE) begin 
    ist = 4; 
    `logI("SD_MODEL: Init Done at %0d ns" ,`SYSTEM_SIM_TIME); 
    if (v2sdhc) `logI("SD_MODEL: Init Done at %0d ns, Ver 2, SDHC detected" ,`SYSTEM_SIM_TIME);
    else if (v2sdsc) `logI("SD_MODEL: Init Done at %0d ns, Ver 2, SDSC detected" ,`SYSTEM_SIM_TIME);
    else if (v1sdsc) `logI("SD_MODEL: Init Done at %0d ns, Ver 1, SDSC detected" ,`SYSTEM_SIM_TIME);
    init_done = 1; 
  end 
end 
always @(*) begin 
  if (st == ReadCycle) begin 
    // `logI (" readcycle ") ; 
    case ( multi_st ) 
      0: begin  
        @( posedge sclk ) if (~ncs && ~mosi) multi_st  =  1; else multi_st = 0;  
      end  
      1: begin  
        @( posedge sclk ) ; if (mosi) multi_st  =  2; else  multi_st = 1;  
      end  
      2: begin  
        m = 0;  
        while (m < 46) begin  
          @(posedge sclk ) serial_in1[45 - m] = mosi ;  
          #1 m = m + 1;  
        end  
        multi_st = 0;  
      end  
    endcase  
  end  
end  
always @(*) begin 
  case (st) 
    PowerOff : begin 
      @( posedge rstn) st <= PowerOn; 
    end 
    PowerOn : begin 
      for (i = 0; i < 75; i++) begin
        @ ( posedge sclk);
        sck_cnt = sck_cnt + 1;
      end
      st <= IDLE; 
    end 
    IDLE : begin 
      @( posedge sclk) if (~ ncs && ~mosi) st <= CmdBit46; else st <= IDLE; 
    end 
    CmdBit46 : begin 
      @( posedge sclk); if (mosi) st <= CommandIn; else st <= CmdBit46;       
    end 
    CommandIn : begin // capture command input -> NCR 
      for (i = 0; i < 46; i = i + 1) begin 
        @(posedge sclk);
        serial_in[45- i] = mosi; 
      end 
      cmd_in = serial_in; 
      repeat (tNCR * 8) @( posedge sclk ); 
      
      st <= CardResponse; 
    end 
    CardResponse : begin // CardResponse -> delay 
      `logI("SD_MODEL: Card Response app_cmd/read_multi/cmd_index/read_cmd = %0d/%0d/%0d/%0d", app_cmd, read_multi, cmd_index, read_cmd);
      // Not an application specific command
      if (~app_cmd) begin 
        case (cmd_index) 
          6'd0    : R1({7'b000_0000, init_done ? 1'b0 : 1'b1});
          6'd16,
          6'd18,
          6'd55   : R1({7'b000_0000, init_done ? 1'b0 : 1'b1});
          6'd8    : begin
                      if (VHS_match)
                        `logI ("SD_MODEL: VHS match");
                      else
                        `logI ("SD_MODEL: VHS not match");
                      // Per spec Section 7.3.2.1: bit 40 of the R7 response (which is bit 0 of the embedded
                      // R1 response is "in idle state: the card is in the idle state and running the initializing process)
                      R7({init_done ? 8'h00 : 8'h01, 20'h00000, VHS_match ? VHS : 4'b0, check_pattern});
                    end
          6'd58   : R3({8'b0000_0000, OCR}); 
          default : R1(8'b0000_0100); //illegal command 
        endcase 
      // Application specific commands
      end else if (~read_multi) begin
        case (cmd_index)
          6'd41   : R1({7'b000_0000, init_done ? 1'b0 : 1'b1});
          default : R1(8'b0000_0100); //illegal command 
        endcase 
      end // if (~read_multi)
      // Deassert miso after any response is sent, but it should only transition on the negedge of sclk
      @(negedge sclk);
      miso = 1;
      if (read_cmd && init_done /*&& ~stop_transmission*/) begin 
        repeat (tNAC * 8) @(posedge sclk); 
        st <= ReadCycle; 
      end else if (read_cmd && init_done && stop_transmission) begin 
        repeat (tNEC * 8) @(posedge sclk ); 
        st <= IDLE; 
      end else if ((send_csd || send_cid || send_scr) && init_done) begin 
        repeat (tNCX * 8) @(posedge sclk ); st <= CsdCidScr;
      end else if (write_cmd && init_done) begin 
        repeat (tNWR*8) @( posedge sclk ); 
        st <= WriteCycle ; 
      end else begin 
        repeat (tNEC*8) @(posedge sclk ); 
        st <= IDLE; 
      end 
    end // CardResponse
    CsdCidScr : begin
      if (send_csd) begin 
        DataOut(CSD[127:120]); 
        DataOut(CSD[119:112]); 
        DataOut(CSD[111:104]); 
        DataOut(CSD[103:96]); 
        DataOut(CSD[95:88]); 
        DataOut(CSD[87:80]); 
        DataOut(CSD[79:72]); 
        DataOut(CSD[71:64]); 
        DataOut(CSD[63:56]); 
        DataOut(CSD[55:48]); 
        DataOut(CSD[47:40]); 
        DataOut(CSD[39:32]); 
        DataOut(CSD[31:24]); 
        DataOut(CSD[23:16]); 
        DataOut(CSD[15:8]); 
        DataOut(CSD[7:0]); 
      end else if (send_cid) begin 
        DataOut(CID[127:120]); 
        DataOut(CID[119:112]); 
        DataOut(CID[111:104]); 
        DataOut(CID[103:96]); 
        DataOut(CID[95:88]); 
        DataOut(CID[87:80]); 
        DataOut(CID[79:72]); 
        DataOut(CID[71:64]); 
        DataOut(CID[63:56]); 
        DataOut(CID[55:48]); 
        DataOut(CID[47:40]); 
        DataOut(CID[39:32]); 
        DataOut(CID[31:24]); 
        DataOut(CID[23:16]); 
        DataOut(CID[15:8]); 
        DataOut(CID[7:0]); 
      end else if (send_scr) begin 
        DataOut(SCR[63:56]); 
        DataOut(SCR[55:48]); 
        DataOut(SCR[47:40]); 
        DataOut(SCR[39:32]); 
        DataOut(SCR[31:24]); 
        DataOut(SCR[23:16]); 
        DataOut(SCR[15:8]); 
        DataOut(SCR[7:0]); 
      end 
      @(posedge sclk); 
      repeat (tNEC*8) @(posedge sclk ) ; 
      st <= IDLE; 
    end 
    ReadCycle: begin //Start Token -> Data -> CRC(stucked at 16'hAAAA) -> NEC( or NAC) 
      // Perform a single block read
      if ( read_single ) begin 
      
        // Read Token
        TokenOut(8'hFE);
        // Reset the CRC
        crc16_out = 0;
        // Read from main memory
        for (i = 0; i < block_len; i = i + 1) begin
          read_data = flash_mem[start_addr + i];
          DataOut(read_data);
          crc16_out = crc16_round(crc16_out, read_data);
        end 
        // Send CRC
        CRCOut(crc16_out);
        @(posedge sclk); 
        // Wait some cycles, return to IDLE
        repeat (tNEC*8) @(negedge sclk); 
        st <= IDLE;
      // Perform a multiple block read
      end else if (read_multi) begin
        // Initialize block index
        j = 0;
        do begin
          // Start Token
          TokenOut(8'hFE);
          // Reset the CRC
          crc16_out = 0;
          // Read from main memory
          for (i = 0; i < block_len; i = i + 1) begin
            read_data = flash_mem[start_addr + block_len * j + i];
            DataOut(read_data);
            crc16_out = crc16_round(crc16_out, read_data);
          end 
          // Send CRC
          CRCOut(crc16_out);
          `logI("SD_MODEL: Multi-block read, block count = %d", j + 1);
          // Check stop tranmission after every block
          if (stop_transmission) begin
            
            repeat (tNEC*8) @( posedge sclk ) ; 
            `logI("SD_MODEL: STOP transmission"); 
            
            @(posedge sclk);
            // Tranmit stop acknowledgemtn           
            R1(8'b0000_0000) ; 
            // Break from the do loop
          end else 
            repeat (tNAC*8) @( negedge sclk ) ; 
          // increment the block index
          j++;
        end while (1); // end do
        // Wait some cycles, return to IDLE
        repeat (tNEC*8) @( posedge sclk ) ; 
        st <= IDLE; 
      end // if (read_multi)
    end // ReadCycle 
    WriteCycle: begin // Start Token -> Data 
      i = 0; 
      while (i < 8) begin 
        @(posedge sclk) token[7- i] = mosi; 
        i = i + 1; 
      end 
      if (token == 8'hfe && write_single) `logI("SD_MODEL: Single Write Start Token OK"); 
      else if (token != 8'hfe && write_single) `logI("SD_MODEL:  Single Write Start Token NG"); 
      if (token == 8'hfc && write_multi) `logI("SD_MODEL: Multiblock Write Start Token OK"); 
      else if ((token != 8'hfc && token != 8'hfd) && write_multi) `logI("SD_MODEL: Multiblock Write Start Token NG"); 
      if (token == 8'hfd && write_multi) begin 
        `logI("SD_MODEL: Multiblock Write Stop Token"); 
        st <= WriteStop; 
      end 
      i = 0; 
      while ( i < block_len ) begin 
        DataIn ; flash_mem[start_addr + i] = capture_data; 
        i = i + 1; 
      end 
      st <= WriteCRC; 
    end 
    WriteCRC : begin // Capture incoming CRC of data 
      i = 0; 
      while ( i < 16) begin 
        @(posedge sclk) crc16_in[15 - i] = mosi; 
        i = i + 1; 
      end 
      st <= DataResponse; 
    end 
    DataResponse: begin //All clock after data response CRC 
      DataOut(8'b00000101); 
      @(negedge sclk); 
      miso = 0; 
      repeat (tNEC*8) @( negedge sclk ) ; 
      repeat (tNDS*8) @( negedge sclk ) ; 
      miso = 1'bz; 
      @(negedge sclk); miso = 1'b0; 
      repeat (100) @(negedge sclk); 
      miso = 1; 
      @(negedge sclk); 
      miso = 1; 
      repeat (5) @( posedge sclk ); 
      if ( write_single ) st <= IDLE; 
      else if (write_multi) st <= WriteCycle; 
    end 
    WriteStop : begin 
      repeat (tNBR*8) @( posedge sclk ) ; 
      miso = 0; 
      repeat (tNEC*8) @( posedge sclk ) ; 
      repeat (tNDS*8) @( posedge sclk) miso = 1'bz; 
      @( posedge sclk) miso = 1'b0; #1000000;//1ms processing time for each block programming 
      @( posedge sclk) miso = 1'b1; 
      repeat (tNEC*8) @( posedge sclk ) ; 
      @( posedge sclk); 
      st <= IDLE; 
    end 
    // Trap state
    default : begin
      ;
    end
  endcase 
end 
always @(st) begin 
  case (st) 
    PowerOff      : ascii_command_state = "PowerOff"; 
    PowerOn       : ascii_command_state = "PowerOn";  
    IDLE          : ascii_command_state = "IDLE"; 
    CmdBit47      : ascii_command_state = "CmdBit47"; 
    CmdBit46      : ascii_command_state = "CmdBit46"; 
    CommandIn     : ascii_command_state = "CommandIn";
    CardResponse  : ascii_command_state = "CardResponse" ; 
    ReadCycle     : ascii_command_state = "ReadCycle"; 
    WriteCycle    : ascii_command_state = "WriteCycle"; 
    DataResponse  : ascii_command_state = "DataResponse"; 
    CsdCidScr     : ascii_command_state = "CsdCidScr";  
    WriteStop     : ascii_command_state = "WriteStop";  
    WriteCRC      : ascii_command_state = "WriteCRC";  
    default       : ascii_command_state = "ERROR";  
  endcase
end
initial begin 
  sck_cnt       = 0;   
  cmd_in        = 46'h3fffffffffff; 
  serial_in     = 46'h0; 
  crc16_in      = 16'h0; 
  crc7_in       = 7'h0;
  crc16_out     = 16'h0;
  token         = 8'h0;
  st            <= PowerOff; 
  miso          = 1'b1; 
  init_done     = 0; 
  ist           = 0; 
  capture_data  = 8'h0; 
  start_addr    = 32'h0; 
  VHS           = 4'h0; 
  serial_in1    = 46'h0; 
  multi_st      = 0; 
  block_len     = 512; 
  
  read_data     = 0;
  for (i = 0; i < MEM_SIZE - 1; i=i+1) begin 
    flash_mem[i] = 0; 
  end 
end 
endmodule 
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      spi_loopback.v
// Program:        Common Evaluation Platform (CEP)
// Description:   
// Notes:          
//
//--------------------------------------------------------------------------------------
module spi_loopback
  (
   // SPI Interface
   input      SCK,
   output reg MISO,
   input      MOSI,
   input      CS_n
   );
   initial MISO = 1'b1;
   always @(posedge  SCK) begin
      if (!CS_n) MISO <= MOSI;
      else MISO <= 1'bz;
   end
   
endmodule // spi_loopback
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      system_driver.sv
// Program:        Common Evaluation Platform (CEP)
// Description:    System Level testbench driver
// Notes:          
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "cep_hierMap.incl"
`include "cep_adrMap.incl"
`include "v2c_cmds.incl"
`include "v2c_top.incl"
module system_driver (
  input               clk,
  input               enableMe
);
  parameter MY_SLOT_ID                = 4'h0;
  parameter MY_CPU_ID                 = 4'h0;
  reg [255:0]         dvtFlags        = 0;
  reg [255:0]         r_data;
  reg [31:0]          printf_addr;
  reg [1:0]           printf_coreId;
  reg [(128*8)-1:0]   printf_buf;
  reg [(128*8)-1:0]   tmp;
  reg                 clear           = 0;
  integer             cnt;
  string              str;
  reg                 program_loaded  = 0;
  // The following bit, which can be controlled via a V2C command, determines
  // where a DUT_WRITE32_64/DUT_READ32_64 will be sent
  //
  // 0 - Main Memory
  // 1 - SD FLash Memory
  //
  reg                 backdoor_select = 0;
  //--------------------------------------------------------------------------------------
  // Define system driver supported DPI tasks prior to the inclusion of sys/driver_common.incl
  //--------------------------------------------------------------------------------------    
  // WRITE32_64
  `define SHIPC_WRITE32_64_TASK WRITE32_64_DPI()
  task WRITE32_64_DPI;
    reg [63:0] d;
    begin
      d[63:32] = inBox.mPar[0];
      d[31:0]  = inBox.mPar[1];
      if (backdoor_select)
        write_sdflash_backdoor(inBox.mAdr, d);
      else
        write_mainmem_backdoor(inBox.mAdr, d);
    end
  endtask // WRITE32_64_DPI
  // READ32_64
  `define SHIPC_READ32_64_TASK READ32_64_DPI()
  task READ32_64_DPI;
    reg [63:0] d;
    begin
      if (backdoor_select)
        read_sdflash_backdoor(inBox.mAdr, d);
      else
        read_mainmem_backdoor(inBox.mAdr, d);
      
      inBox.mPar[0] = d[63:32];
      inBox.mPar[1] = d[31:0];      
    end
  endtask // READ32_64_DPI
  
  // WRITE_DVT_FLAG_TASK
  `define SHIPC_WRITE_DVT_FLAG_TASK WRITE_DVT_FLAG_TASK(__shIpc_p0,__shIpc_p1,__shIpc_p2)
  task WRITE_DVT_FLAG_TASK;
    input [31:0] msb;
    input [31:0] lsb;
    input [31:0] value; 
    begin
      for (int s = inBox.mPar[1]; s <= inBox.mPar[0]; s++) begin 
        dvtFlags[s]   = inBox.mPar[2] & 1'b1; 
        inBox.mPar[2] = inBox.mPar[2] >> 1; 
      end      
      
      @(posedge clk);  
    end
  endtask // WRITE_DVT_FLAG_TASK;
  // READ_DVT_FLAG_TASK
  `define SHIPC_READ_DVT_FLAG_TASK READ_DVT_FLAG_TASK(__shIpc_p0,__shIpc_p1,{__shIpc_p0[31:0],__shIpc_p1[31:0]})
  task READ_DVT_FLAG_TASK;
    input [31:0]    msb;
    input [31:0]    lsb;
    output [63:0]   r_data;
    integer         m;
    integer         l;
    reg [63:0]      tmp;
    begin
      tmp = 0;
    
      m = inBox.mPar[0];
      l = inBox.mPar[1];
      for (int s = m; s >= l; s--) begin       
        tmp = {tmp[62:0], dvtFlags[s]};
      end
      
      inBox.mPar[0] = tmp;
   
      @(posedge clk);   
    end
  endtask // READ_DVT_FLAG_TASK;
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // SHIPC Support Common Codes
  //
  // These includes must remain within the verilog module and
  // is dependent on the SHIPC_CLK macro.
  //--------------------------------------------------------------------------------------
  `define     SHIPC_XACTOR_ID     MY_CPU_ID
  `define     SHIPC_CLK           clk
  `include    "dpi_common.incl"
  `include    "dump_control.incl"      
  `undef      SHIPC_CLK
  `undef      SHIPC_XACTOR_ID      
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // The following functionality allows for selective control of the UART and SD during
  // the booting process.  By default (given that scratch_word0 resets to zero), UART
  // and SD Boot are enabled in the bootrom.  This needs to be the default behavior
  // for tapeout.
  //
  // When booting bare metal in the CEP CoSim, the default behavior is to bypass
  // SD boot and the UART.... and thus the scratch_word0 will be forced to the appropriate
  // value UNTIL core0 indicates a running status.
  //
  // If bits 1 and 0 are set, the UART Welcome message will be disabled
  // If bits 2 and 3 are set, SD Boot will be disabled
  //
  // This is only applicable in bare metal mode.  The RISC-V ISA tests don't use
  // the CEP Registers, so no changes should be needed there.
  //--------------------------------------------------------------------------------------
  `ifdef BARE_MODE
    initial begin
      #1;
      `logI("BARE_MODE: Forcing scratch_word0[3:0], thus Disabling UART and SD Boot in the BootROM...");
      force `CEPREGS_PATH.scratch_word0[3:0] = 4'hF;
    end
    // Automatically release the register when the core indicates it is running
    always @(`CEPREGS_PATH.core0_status) begin
      if (`CEPREGS_PATH.core0_status == `CEP_RUNNING_STATUS)
        `logI("CEP_RUNNING_STATUS detected.  Releasing scratch_wor0[3:0]...");
        release `CEPREGS_PATH.scratch_word0[3:0];
    end
    // The UART has been enabled in the bootrom, release the appropriate
    // bits of the scratchpad register AND force the divider to a FAST speed 
    // for the remainder of the simulation
    always @(posedge `DVT_FLAG[`DVTF_BOOTROM_ENABLE_UART]) begin
      force `CEPREGS_PATH.scratch_word0[1:0] = 0;
      release `CEPREGS_PATH.scratch_word0[1:0];
      `logI("BOOTROM: Enabling the UART");
      `DVT_FLAG[`DVTF_BOOTROM_ENABLE_UART] = 0;
      // A divider of 16 does not seem to simulate properly in xcellium      
      force `DUT_UART_DIVIDER = 16'h0020;
    end // always @(posedge `DVT_FLAG[`DVTF_BOOTROM_ENABLE_UART])
    // The SPI interface has been enabled in the bootrom, release the
    // appropriate bits of the scratchpad register AND force the divder to
    // a FAST speed for the remainder of the simulation
    //
    // Additional, the payload size in bootrom will be forced to a
    // managable size.
    always @(posedge `DVT_FLAG[`DVTF_BOOTROM_ENABLE_SDBOOT]) begin
      force `CEPREGS_PATH.scratch_word0[3:2] = 0;
      release `CEPREGS_PATH.scratch_word0[3:2];
      `logI("BOOTROM: Enabling the SD Boot");
      `DVT_FLAG[`DVTF_BOOTROM_ENABLE_SDBOOT] = 0;
      // Force divider to a manageable size
      force `DUT_SPI_SCKDIV = 12'h010;
      // Force one of the scratch registers to a payload size that
      // will override the bootrom default (the fullboot test executable
      // is loaded is <16k bytes or 32 512-byte blocks)
      force `CEPREGS_PATH.scratch_word7 = 64'h0000_0000_0000_0020;
      
    end // always @(posedge `DVT_FLAG[`DVTF_BOOTROM_ENABLE_SDBOOT])
  
  `endif
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // DVT Flag Processing
  //--------------------------------------------------------------------------------------
  always @(posedge `DVT_FLAG[`DVTF_SET_BACKDOOR_SELECT]) begin
    backdoor_select = `DVT_FLAG[`DVTF_PAT_LO];
    `logI("Setting Backdoor Select to %d", backdoor_select);
    `DVT_FLAG[`DVTF_SET_BACKDOOR_SELECT] = 0;
  end // always @(posedge `DVT_FLAG[`DVTF_SET_BACKDOOR_SELECT])
  always @(posedge `DVT_FLAG[`DVTF_GET_BACKDOOR_SELECT]) begin
      dvtFlags[`DVTF_PAT_HI:`DVTF_PAT_LO]   = backdoor_select;
      dvtFlags[`DVTF_GET_BACKDOOR_SELECT]  = 0; // self-clear
  end // always @(posedge `DVT_FLAG[`DVTF_GET_BACKDOOR_SELECT])
  always @(posedge `DVT_FLAG[`DVTF_SET_PROGRAM_LOADED]) begin
    `logI("Program is now loaded");
    program_loaded = `DVT_FLAG[`DVTF_PAT_LO];
    `DVT_FLAG[`DVTF_SET_PROGRAM_LOADED] = 0;
  end // always @(posedge `DVT_FLAG[`DVTF_SET_PROGRAM_LOADED])
  always @(posedge `DVT_FLAG[`DVTF_TOGGLE_CHIP_RESET_BIT]) 
  begin
    wait (`PBUS_RESET == 0);
    @(negedge `PBUS_CLOCK);
    #2000;
    `logI("Asserting pbus_Reset");
    force `PBUS_RESET = 1;
    repeat (10) @(negedge `PBUS_CLOCK);
    #2000;
    release `PBUS_RESET;      
    `DVT_FLAG[`DVTF_TOGGLE_CHIP_RESET_BIT] = 0;
  end // always @(posedge `DVT_FLAG[`DVTF_TOGGLE_CHIP_RESET_BIT]) 
  always @(posedge `DVT_FLAG[`DVTF_TOGGLE_DMI_RESET_BIT]) 
  begin
    `logI("Forcing topMod_debug_ndreset");
    force `DEBUG_NDRESET = 1;
    repeat (10) @(negedge `PBUS_CLOCK);
    release `DEBUG_NDRESET;
    `DVT_FLAG[`DVTF_TOGGLE_DMI_RESET_BIT] = 0;
  end // always @(posedge `DVT_FLAG[`DVTF_TOGGLE_DMI_RESET_BIT]) 
  always @(posedge `DVT_FLAG[`DVTF_GET_SOCKET_ID_BIT]) 
  begin
    `logI("DVTF_GET_SOCKET_ID_BIT");
    `ifdef OPENOCD_ENABLE
      `DVT_FLAG[`DVTF_PAT_HI:`DVTF_PAT_LO] = jtag_getSocketPortId();
    `endif
    `logI("SocketId = 0x%08x",`DVT_FLAG[`DVTF_PAT_HI:`DVTF_PAT_LO]);
    `DVT_FLAG[`DVTF_GET_SOCKET_ID_BIT] = 0;
  end // always @(posedge `DVT_FLAG[`DVTF_GET_SOCKET_ID_BIT])
  reg uart_loopback_enabled = 1;
  always @(posedge `DVT_FLAG[`DVTF_CONTROL_UART_LOOPBACK]) 
  begin
    uart_loopback_enabled = `DVT_FLAG[`DVTF_PAT_LO];
    `logI("DVTF_CONTROL_UART_LOOPBACK - %0d", uart_loopback_enabled);
    `DVT_FLAG[`DVTF_CONTROL_UART_LOOPBACK] = 0;
  end //posedge `DVT_FLAG[`DVTF_CONTROL_UART_LOOPBACK]) 
  reg spi_loopback_enabled = 1;
  always @(posedge `DVT_FLAG[`DVTF_CONTROL_SPI_LOOPBACK]) 
  begin
    spi_loopback_enabled = `DVT_FLAG[`DVTF_PAT_LO];
    `logI("DVTF_CONTROL_SPI_LOOPBACK - %0d", spi_loopback_enabled);
    `DVT_FLAG[`DVTF_CONTROL_SPI_LOOPBACK] = 0;
  end //posedge `DVT_FLAG[`DVTF_CONTROL_UART_LOOPBACK]) 
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // Tasks support "backdoor" read/write access from/to Main Memory
  //
  // They should only be accessed from the system thread given that they assert
  // signals on the memory components vs internal methods (as was the case in the DDR
  // memory).  Otherwise, you could potentially get multiple threads driving the same
  // signals concurrently, which will have an unpredictable behavior.
  //--------------------------------------------------------------------------------------  
  // Writes data directly to the Scratchpad (Main) Memory
  task write_mainmem_backdoor;
    input [31:0] addr;
    input [63:0] data;
    begin
    
      // If the memory is in reset, wait for it to be released
      if (`SCRATCHPAD_WRAPPER_PATH.rst == 1) @(negedge `SCRATCHPAD_WRAPPER_PATH.rst);
      @(negedge `SCRATCHPAD_WRAPPER_PATH.clk);
      // All backdoor memory access is 64-bit
      force `SCRATCHPAD_WRAPPER_PATH.scratchpad_mask_i        = '1;
      force `SCRATCHPAD_WRAPPER_PATH.scratchpad_write_i       = 1;
      force `SCRATCHPAD_WRAPPER_PATH.scratchpad_addr_i        = addr >> 3;
      force `SCRATCHPAD_WRAPPER_PATH.scratchpad_wdata_i       = data;
      @(negedge `SCRATCHPAD_WRAPPER_PATH.clk);
     
      release `SCRATCHPAD_WRAPPER_PATH.scratchpad_mask_i;
      release `SCRATCHPAD_WRAPPER_PATH.scratchpad_write_i;
      release `SCRATCHPAD_WRAPPER_PATH.scratchpad_addr_i;
      release `SCRATCHPAD_WRAPPER_PATH.scratchpad_wdata_i;
    end
  endtask // write_mainmem_backdoor
  // Reads data directly from the Scratcpad (Main) Memory
  task read_mainmem_backdoor;
    input   [31:0] addr;
    output  [63:0] data;
    begin
    
      // If the memory is in reset, wait for it to be released
      if (`SCRATCHPAD_WRAPPER_PATH.rst == 1) @(negedge `SCRATCHPAD_WRAPPER_PATH.rst);
      // Reads are registered, need to be synchronized to the clock
      force `SCRATCHPAD_WRAPPER_PATH.scratchpad_addr_i    = addr >> 3;
      @(posedge `SCRATCHPAD_WRAPPER_PATH.clk);
      @(negedge `SCRATCHPAD_WRAPPER_PATH.clk);
      #1;
      data = `SCRATCHPAD_WRAPPER_PATH.scratchpad_rdata_o;
      release `SCRATCHPAD_WRAPPER_PATH.scratchpad_addr_i;
    end
  endtask // read_mainmem_backdoor
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // Task to support "backdoor" read/write access from/to SD Flash Memory
  //
  // Note: SDFlash is 8-bits wide, so byte ordering will be important (Little Endian)
  //--------------------------------------------------------------------------------------
  task write_sdflash_backdoor;
    input [31:0] addr;
    input [63:0] data;
    begin
      `logI("Write 0x%x to address 0x%x", data, addr);
      // If the memory is in reset, wait for it to be released
      if (`SDCARD_PATH.rstn == 0) @(posedge `SDCARD_PATH.rstn);
      for (int i = 0; i < 8; i++) begin
        `SDCARD_PATH.write_flash_byte(addr + i, data[i*8 +: 8]);
      end
    end
  endtask // write_sdflash_backdopor
  task read_sdflash_backdoor;
    input   [31:0] addr;
    output  [63:0] data;
    begin
      // If the memory is in reset, wait for it to be released
      if (`SDCARD_PATH.rstn == 0) @(posedge `SDCARD_PATH.rstn);
      for (int i = 0; i < 8; i++) begin
        data[i*8 +: 8] = `SDCARD_PATH.flash_mem[addr + i];
      end
      // Advance a clock for good measure
      @(posedge `SDCARD_PATH.sclk);
    end
  endtask // write_sdflash_backdopor
  //--------------------------------------------------------------------------------------
  //--------------------------------------------------------------------------------------
  // System Driver support tasks when running the RISCV_TESTS
  //--------------------------------------------------------------------------------------
  // This is to handle single threading core: one core active at a time
  `ifdef RISCV_TESTS
    reg [63:0]  passFail [0:4]      = '{default:0};
    reg         passFailValid       = 0;
    int         file;
    initial begin
      `logI("==== ISA RISCV_TESTS is active ===");      
      // Perform a simple file I/O test to ensure file is there
      file = $fopen("PassFail.hex", "r");
      if (file) begin
        $fclose(file);
        passFailValid = 1;
        $readmemh("PassFail.hex", passFail);
        `logI("Reading from PassFail.hex: pass = 0x%0x, fail = 0x%0x, finish = 0x%0x, write_tohost = 0x%0x, hangme = 0x%0x",
          passFail[0], passFail[1], passFail[2], passFail[3], passFail[4]);
      end
    end
   
    // Force all cores into reset
    task ResetAllCores;
      begin
        force `TILE0_PATH.reset = 1;
        force `TILE1_PATH.reset = 1;
        force `TILE2_PATH.reset = 1;
        force `TILE3_PATH.reset = 1;
   
        repeat (2) @(posedge clk);
   
        release `TILE0_PATH.reset;  
        release `TILE1_PATH.reset;  
        release `TILE2_PATH.reset;  
        release `TILE3_PATH.reset;  
      end
    endtask // ResetAllCores
  `endif // endif `ifdef RISCV_TESTS
  //--------------------------------------------------------------------------------------
   
endmodule // v2c_top
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      tl_monitor.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Component is used to provide Testbench level visability into what
//                 the RocketTiles are doing
// Notes:          
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "cep_hierMap.incl"
`include "cep_adrMap.incl"
`include "v2c_cmds.incl"
`include "v2c_top.incl"
module tile_monitor (
  input         clock,
  input         reset,
  input         enable,
  input         auto_wfi_out_0,
  input         auto_int_local_in_3_0,
  input         auto_int_local_in_2_0,
  input         auto_int_local_in_1_0,
  input         auto_int_local_in_1_1,
  input         auto_int_local_in_0_0,
  input  [1:0]  auto_hartid_in,
  input         a_ready,
  input         a_valid,
  input [2:0]   a_bits_opcode,
  input [2:0]   a_bits_param,
  input [3:0]   a_bits_size,
  input [1:0]   a_bits_source,
  input [31:0]  a_bits_address,
  input [7:0]   a_bits_mask,
  input [63:0]  a_bits_data,
  input         b_ready,
  input         b_valid,
  input  [1:0]  b_bits_param,
  input  [3:0]  b_bits_size,
  input  [1:0]  b_bits_source,
  input  [31:0] b_bits_address,
  input         c_ready,
  input         c_valid,
  input [2:0]   c_bits_opcode,
  input [2:0]   c_bits_param,
  input [3:0]   c_bits_size,
  input [1:0]   c_bits_source,
  input [31:0]  c_bits_address,
  input [63:0]  c_bits_data,
  input         d_ready,
  input         d_valid,
  input  [2:0]  d_bits_opcode,
  input  [1:0]  d_bits_param,
  input  [3:0]  d_bits_size,
  input  [1:0]  d_bits_source,
  input  [1:0]  d_bits_sink,
  input         d_bits_denied,
  input  [63:0] d_bits_data,
  input         d_bits_corrupt,
  input         e_ready,
  input         e_valid,
  input [1:0]   e_bits_sink
);
  always @(posedge clock && enable) begin
    if (a_valid && a_ready) begin
      `logI("TILE_MONITOR: Tile #%0d A channel TL transaction - opcode=%0d, param=%0d, size=%0d, source=%0d, address=0x%x, mask=0x%x, data=0x%x",
        auto_hartid_in, a_bits_opcode, a_bits_param, a_bits_size, a_bits_source, a_bits_address, a_bits_mask, a_bits_data);
    end // end if a_valid)
    if (b_valid && b_ready) begin
    end // if (b_valid)
    if (c_valid && c_ready) begin
    end // if (c_valid)
    if (d_valid && d_ready) begin
      if (d_bits_denied && d_bits_corrupt)
        `logE("TILE_MONITOR: Tile #%0d D channel TL transaction - opcode=%0d, param=%0d, size=%0d, source=%0d, sink=%0d, denied=%0d, data=0x%x, corrupt=%0d",
          auto_hartid_in, d_bits_opcode, d_bits_param, d_bits_size, d_bits_source, d_bits_sink, d_bits_denied, d_bits_data, d_bits_corrupt);
      else
        `logI("TILE_MONITOR: Tile #%0d D channel TL transaction - opcode=%0d, param=%0d, size=%0d, source=%0d, sink=%0d, denied=%0d, data=0x%x, corrupt=%0d",
          auto_hartid_in, d_bits_opcode, d_bits_param, d_bits_size, d_bits_source, d_bits_sink, d_bits_denied, d_bits_data, d_bits_corrupt);
    end // if (d_valid)
    if (e_valid && e_ready) begin
    end // if (e_valid)
  end // always @(posedge clock && enable)
endmodule // tile_monitor | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      tl_master_beh.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Tilelink Master Bus Functional Model for the
//                 CEP Co-Simulation Environment
// Notes:          
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "tl_defines.incl"
`include "v2c_top.incl"
module tl_master_beh #(
  parameter CHIP_ID       = 0,
  parameter SRC_SIZE      = 2,
  parameter SINK_SIZE     = 2,
  parameter BUS_SIZE      = 8, 
  parameter ADR_WIDTH     = 32,
  localparam TL_SIZE      = 4, // $clog2(BUS_SIZE),
  localparam DATA_WIDTH   = (BUS_SIZE*8),
  localparam MAX_TIMEOUT  = 1000
) (
  input                       clock, 
  input                       reset, 
  
  // Channel A
  input                       tl_master_a_ready, 
  output reg                  tl_master_a_valid = 0, 
  output reg [2:0]            tl_master_a_bits_opcode = 0, 
  output reg [2:0]            tl_master_a_bits_param = 0, 
  output reg [TL_SIZE-1:0]    tl_master_a_bits_size = 0, 
  output reg [SRC_SIZE-1:0]   tl_master_a_bits_source = 0, 
  output reg [ADR_WIDTH-1:0]  tl_master_a_bits_address = 0, 
  output reg [BUS_SIZE-1:0]   tl_master_a_bits_mask = 0, 
  output reg [DATA_WIDTH-1:0] tl_master_a_bits_data = 0, 
  output reg                  tl_master_a_bits_corrupt = 0, 
  
  // Channel B
  output reg                  tl_master_b_ready = 1, 
  input                       tl_master_b_valid, 
  input [2:0]                 tl_master_b_bits_opcode, 
  input [1:0]                 tl_master_b_bits_param, 
  input [TL_SIZE-1:0]         tl_master_b_bits_size, 
  input [SRC_SIZE-1:0]        tl_master_b_bits_source, 
  input [ADR_WIDTH-1:0]       tl_master_b_bits_address, 
  input [BUS_SIZE-1:0]        tl_master_b_bits_mask, 
  input                       tl_master_b_bits_corrupt,
 
  // Channel C    
  input                       tl_master_c_ready, 
  output reg                  tl_master_c_valid = 0, 
  output reg [2:0]            tl_master_c_bits_opcode = 0, 
  output reg [2:0]            tl_master_c_bits_param = 0, 
  output reg [3:0]            tl_master_c_bits_size = 0,
  output reg [SRC_SIZE-1:0]   tl_master_c_bits_source = 0, 
  output reg [ADR_WIDTH-1:0]  tl_master_c_bits_address = 0, 
  output reg [DATA_WIDTH-1:0] tl_master_c_bits_data = 0, 
  output reg                  tl_master_c_bits_corrupt = 0, 
  
  // Channel D
  output reg                  tl_master_d_ready = 1,
  input                       tl_master_d_valid, 
  input [2:0]                 tl_master_d_bits_opcode, 
  input [1:0]                 tl_master_d_bits_param, 
  input [3:0]                 tl_master_d_bits_size,
  input [SRC_SIZE-1:0]        tl_master_d_bits_source, 
  input [SINK_SIZE-1:0]       tl_master_d_bits_sink, 
  input                       tl_master_d_bits_denied, 
  input [DATA_WIDTH-1:0]      tl_master_d_bits_data, 
  input                       tl_master_d_bits_corrupt, 
  
  // Channel E          
  input                       tl_master_e_ready, 
  output reg                  tl_master_e_valid = 0, 
  output reg [SINK_SIZE-1:0]  tl_master_e_bits_sink = 0
);
  integer              i;
  reg                  tl_err = 0;
//`define TICK_DELAY #1
`define TICK_DELAY 
   //
   // checkReset
   //
   task checkReset;
      begin
     tl_err = 0;
     `ifdef REMOVE_ME
     if (reset) begin
        `logW("Chip is in reset... Waiting to get out");
        i = 0;
        @(posedge clock);
        while (reset && !tl_err && (i < MAX_TIMEOUT)) begin
           i = i + 1;                  
           @(posedge clock);
           if (i >= MAX_TIMEOUT) begin
          `logE("** timeout while waiting for reset to de-asserted");
          tl_err = 1;
           end
           //
        end
     end // if (reset)
     `endif
      end
   endtask // if
   //
   // decode for CEP
   //    
   task tl_x_ul_read;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      output [DATA_WIDTH-1:0] d;
      begin
     tl_a_ul_read(src_id,a,d);
      end
   endtask // checkReset
   task tl_x_ul_write;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [DATA_WIDTH-1:0] d;
      //
      begin
     tl_a_ul_write_generic(src_id,a,d,(1<<BUS_SIZE)-1,3);
      end
   endtask // tl_a_ul_write_generic
   
   //
   // TL-UL-GET  (64 bits for now)
   //
   task tl_a_ul_read;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      output [DATA_WIDTH-1:0] d;
      //
      begin
     checkReset();
     if (tl_err) disable tl_a_ul_read;
     //`logI("%m : src=%d a=0x%x %t",src_id,a,$time);
     //
     // use negedge to drive output
     @(posedge clock); `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_GET;
     tl_master_a_bits_param  = 0; // must
     tl_master_a_bits_size   = 3; // log2(8bytes)
     tl_master_a_bits_source = src_id;
     tl_master_a_bits_address= a;
     tl_master_a_bits_mask   = 'hFF;
     tl_master_a_bits_data   = 0; // dont care
     tl_master_a_valid       = 1; // issue a valid
     // wait until slave took it
     i = 0;
     @(posedge clock);
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        i = i + 1;              
        @(posedge clock);       
        if (i >= MAX_TIMEOUT) begin
           `logE(" **ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     i = 0;
     @(posedge clock);       
     //
     while (!tl_err && !tl_master_d_valid) begin
        i = i + 1;
        @(posedge clock);
        if (i > MAX_TIMEOUT) begin
           `logE("**ERROR** timeout while waiting for data from channelD src=%d a=0x%x",src_id,a);
           tl_err = 1;        
        end
     end
     // check and verify the data is for this tracaction
     if (!tl_err && 
         ((tl_master_d_bits_opcode != `TL_D_ACCESSACKDATA) ||
          (tl_master_d_bits_param != 0) ||
//        (tl_master_d_bits_size != 3) ||
          (tl_master_d_bits_source != src_id) ||
          (tl_master_d_bits_denied) ||
          (tl_master_d_bits_corrupt))) begin
        `logE("**ERROR** src_id=%d reported from channelD op/par/sz/src/den/cor=%x/%x/%x/%x/%x/%x",src_id,
             tl_master_d_bits_opcode,tl_master_d_bits_param,tl_master_d_bits_size,tl_master_d_bits_source,tl_master_d_bits_denied,tl_master_d_bits_corrupt);
        tl_err = 1;
     end
     else if (!tl_err) begin
        d = tl_master_d_bits_data;         
        `logI("src=%d a=0x%x d=0x%x",src_id,a,d);
     end
     @(posedge clock);   
      end      
   endtask 
   task tl_x_ul_read_generic;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [BUS_SIZE-1:0]   mask;
      input [1:0]        bits_size;       // log2(8bytes)
      output [DATA_WIDTH-1:0] d;
      //
      begin
     checkReset();
     if (tl_err) disable tl_a_ul_read;
     //`logI("%m : src=%d a=0x%x %t",src_id,a,$time);
     //
     // use negedge to drive output
     @(posedge clock); `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_GET;
     tl_master_a_bits_param  = 0; // must
     tl_master_a_bits_size   = bits_size;
     /*
     if (mask == ((1<<BUS_SIZE)-1))      
       tl_master_a_bits_size   = 3; // log2(8bytes)
     else
       tl_master_a_bits_size   = 2; // log2(8bytes)  
      */
     tl_master_a_bits_source = src_id;
     tl_master_a_bits_address= a;
//   tl_master_a_bits_mask   = 'hFF;
     tl_master_a_bits_mask   = mask;     
     tl_master_a_bits_data   = 0; // dont care
     tl_master_a_valid       = 1; // issue a valid
     // wait until slave took it
     i = 0;
     @(posedge clock);
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        i = i + 1;              
        @(posedge clock);       
        if (i >= MAX_TIMEOUT) begin
           `logE(" **ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     i = 0;
     @(posedge clock);       
     //
     while (!tl_err && !tl_master_d_valid) begin
        i = i + 1;
        @(posedge clock);
        if (i > MAX_TIMEOUT) begin
           `logE("**ERROR** timeout while waiting for data from channelD src=%d a=0x%x",src_id,a);
           tl_err = 1;        
        end
     end
     // check and verify the data is for this tracaction
     if (!tl_err && 
         ((tl_master_d_bits_opcode != `TL_D_ACCESSACKDATA) ||
          (tl_master_d_bits_param != 0) ||
//        (tl_master_d_bits_size != 3) ||
          (tl_master_d_bits_source != src_id) ||
          (tl_master_d_bits_denied) ||
          (tl_master_d_bits_corrupt))) begin
        `logE("**ERROR** src_id=%d reported from channelD op/par/sz/src/den/cor=%x/%x/%x/%x/%x/%x",src_id,
             tl_master_d_bits_opcode,tl_master_d_bits_param,tl_master_d_bits_size,tl_master_d_bits_source,tl_master_d_bits_denied,tl_master_d_bits_corrupt);
        tl_err = 1;
     end
     else if (!tl_err) begin
        d = tl_master_d_bits_data;         
        `logI("src=%d a=0x%x d=0x%x",src_id,a,d);
     end
     @(posedge clock);   
      end      
   endtask 
   
   
   //
   // TL-UL-PUT Full  (64 bits for now)
   //
   task tl_a_ul_write;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [DATA_WIDTH-1:0] d;
      //
      begin
     //
     tl_a_ul_write_generic(src_id,a,d,(1<<BUS_SIZE)-1,3);
      end
   endtask // tl_a_ul_write_generic
   
   //
   // TL-UL-TL_A_PUTPARTIALDATA
   //
   task tl_a_ul_write_generic; // support both full and partial
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [DATA_WIDTH-1:0] d;
      input [BUS_SIZE-1:0]   mask;
      input [1:0]        bits_size;
      //
      begin
     //
     checkReset();
     if (tl_err) disable tl_a_ul_write;
     `logI("src=%d a=0x%x d=0x%x mask=0x%x",src_id,a,d,mask);    
     @(posedge clock);  `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_PUTFULLDATA;    
     /*
     if (mask == ((1<<BUS_SIZE)-1))
       tl_master_a_bits_opcode = `TL_A_PUTFULLDATA;
     else
       tl_master_a_bits_opcode = `TL_A_PUTPARTIALDATA;   
      */
     tl_master_a_bits_param  = 0; // must
     /*
     if (mask == ((1<<BUS_SIZE)-1))  
       tl_master_a_bits_size   = 3; // log2(8bytes)
     else
       tl_master_a_bits_size   = 2; // log2(8bytes)    
      */
     tl_master_a_bits_size   = bits_size;
     //
     tl_master_a_bits_source = src_id;
     tl_master_a_bits_address= a;
     tl_master_a_bits_mask   = mask;
     tl_master_a_bits_data   = d; // dont care
     tl_master_a_valid       = 1; // issue a valid
     // wait until slave took it
     i = 0;
     @(posedge clock);       
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        i = i + 1;              
        @(posedge clock);
        if (i >= MAX_TIMEOUT) begin
           `logE("**ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     if (!tl_err) begin
        //
        i = 0;
        @(posedge clock);
        while (!tl_master_d_valid && (i < MAX_TIMEOUT)) begin
           i = i + 1;                  
           @(posedge clock);
           if (i >= MAX_TIMEOUT) begin
          `logE("**ERROR** timeout while waiting for data from channelD src=%d a=0x%x",src_id,a);
          tl_err = 1;         
           end
        end
        // check and verify the data is for this tracaction
        if (!tl_err &&
        ((tl_master_d_bits_opcode != `TL_D_ACCESSACK) ||
         (tl_master_d_bits_param != 0) ||
//       (tl_master_d_bits_size != 3) ||
         (tl_master_d_bits_source != src_id) ||
         (tl_master_d_bits_denied) ||
         (tl_master_d_bits_corrupt))) begin
           `logE("**ERROR** src_id=%d reported from channelD op/par/sz/src/den/cor=%x/%x/%x/%x/%x/%x",src_id,
            tl_master_d_bits_opcode,tl_master_d_bits_param,tl_master_d_bits_size,tl_master_d_bits_source,tl_master_d_bits_denied,tl_master_d_bits_corrupt);
        end
     end // if (tl_master_a_ready)
     @(posedge clock);   
      end
   endtask // checkReset
   reg [DATA_WIDTH-1:0] tl_buf [31:0]; // for burst
   //
   // TL-UL-TL_A_PUTPARTIALDATA : burst!!
   // one ack per 64-bytes
   //
   task tl_a_ul_write_burst; 
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [BUS_SIZE-1:0]  mask;      
      input [3:0]        bits_size;
      //
      int        i, ackCnt;
      reg [7:0]      cnt;
      
      begin
     //
     checkReset();
     if (tl_err) disable tl_a_ul_write_burst;
     tl_master_d_ready = 1; // not ready to accept       
     `logI("src=%d a=0x%x size=%d mask=0x%x",src_id,a,cnt,mask);     
     @(posedge clock);  `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_PUTFULLDATA;    
     tl_master_a_bits_param  = 0; // must
     tl_master_a_bits_size   = bits_size;
     tl_master_a_bits_mask   = mask;
     //
     cnt = (1 << bits_size) >> 3;
     i = 0;
     ackCnt = 0;
     while (i < cnt) begin
        tl_master_a_bits_source = src_id;
        tl_master_a_bits_address= a;
        tl_master_a_bits_data   = tl_buf[i]; // dont care
        tl_master_a_valid       = 1; // issue a valid
        @(posedge clock);  `TICK_DELAY;
        //`logI("Cnt=%d i=%d data=%x",cnt,i,tl_buf[i]);
        if (tl_master_a_ready) i++;
        if (tl_master_d_valid) ackCnt++;
     end
     tl_master_a_valid       = 0;
     // wait until slave took it
     i = 0;
     @(posedge clock);
     if (tl_master_d_valid) ackCnt++;    
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        i = i + 1;              
        @(posedge clock);
        if (tl_master_d_valid) ackCnt++;        
        if (i >= MAX_TIMEOUT) begin
           `logE("**ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     if (!tl_err) begin
        // how many ack?? one per 8 64-bits
        cnt = (cnt <= 8) ? 1 : (cnt >> 3);
        while (ackCnt < cnt) begin
           //
           i = 0;
           @(posedge clock);
           while (!tl_master_d_valid && (i < MAX_TIMEOUT)) begin
          i = i + 1;                   
          @(posedge clock);
          if (i >= MAX_TIMEOUT) begin
             `logE("**ERROR** timeout while waiting for data from channelD src=%d a=0x%x",src_id,a);
             tl_err = 1;          
          end
           end
           ackCnt++;
           // check and verify the data is for this tracaction
           if (!tl_err &&
           ((tl_master_d_bits_opcode != `TL_D_ACCESSACK) ||
            (tl_master_d_bits_param != 0) ||
            (tl_master_d_bits_source != src_id) ||
            (tl_master_d_bits_denied) ||
            (tl_master_d_bits_corrupt))) begin
          `logE("**ERROR** src_id=%d reported from channelD op/par/sz/src/den/cor=%x/%x/%x/%x/%x/%x",src_id,
            tl_master_d_bits_opcode,tl_master_d_bits_param,tl_master_d_bits_size,tl_master_d_bits_source,tl_master_d_bits_denied,tl_master_d_bits_corrupt);
           end
        end // while (ackCnt < cnt)
     end // if (tl_master_a_ready)
     @(posedge clock);   
      end
   endtask // checkReset
   //
   // TL-UL-GET  (64 bits for now)
   //
   event mark;
   task tl_a_ul_read_burst;
      input [SRC_SIZE-1:0] src_id;
      input [ADR_WIDTH-1:0] a;
      input [3:0]       bits_size;
      //
      int       cnt,i,to;      
      //
      begin
     checkReset();
     if (tl_err) disable tl_a_ul_read_burst;
     tl_master_d_ready = 0; // not ready to accept       
     `logI("%m : src=%x2d a=0x%x %t",src_id,a,$time);
     //
     // use negedge to drive output
     @(posedge clock); `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_GET;
     tl_master_a_bits_param  = 0; // must
     tl_master_a_bits_size   = bits_size; // log2(8bytes)
     tl_master_a_bits_source = src_id;
     tl_master_a_bits_address= a;
     tl_master_a_bits_mask   = 'hFF;
     tl_master_a_bits_data   = 0; // dont care
     tl_master_a_valid       = 1; // issue a valid
     // wait until slave took it
     to = 0;
     @(posedge clock);
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        to++;
        @(posedge clock);       
        if (to >= MAX_TIMEOUT) begin
           `logE(" **ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     cnt = (1 << bits_size) >> 3;
     i = 0;
     while (i < cnt) begin
        @(posedge clock);
        if (tl_master_d_valid) begin
           tl_buf[i] = tl_master_d_bits_data;
           //`logI("src=%d a=0x%x d[%d]=0x%x",src_id,a,i,tl_buf[i]);          
           i++;
        end 
     end // while (i < cnt)
      end
   endtask // checkReset
   //
   // TL-UL-LogicalData
   //
   task tl_a_ul_logical_data;
      input [SRC_SIZE-1:0]   src_id;
      input [ADR_WIDTH-1:0]  a;
      input [2:0]        param   ;
      input [DATA_WIDTH-1:0] d;
      input [BUS_SIZE-1:0]   mask;
      input [1:0]        bits_size;
      //
      begin
     //
     checkReset();
     if (tl_err) disable tl_a_ul_write;
     `logI("src=%d a=0x%x d=0x%x mask=0x%x",src_id,a,d,mask);    
     @(posedge clock);  `TICK_DELAY;
     tl_master_a_bits_opcode = `TL_A_LOGICALDATA;
     tl_master_a_bits_param  = param; // must
     tl_master_a_bits_size   = bits_size;
     //
     tl_master_a_bits_source = src_id;
     tl_master_a_bits_address= a;
     tl_master_a_bits_mask   = mask;
     tl_master_a_bits_data   = d; // dont care
     tl_master_a_valid       = 1; // issue a valid
     // wait until slave took it
     i = 0;
     @(posedge clock);       
     while (!tl_master_a_ready && (i < MAX_TIMEOUT)) begin
        i = i + 1;              
        @(posedge clock);
        if (i >= MAX_TIMEOUT) begin
           `logE("**ERROR** timeout while waiting for ready on channelA src=%d a=0x%x",src_id,a);
           tl_err = 1;
        end
     end
     //
     `TICK_DELAY;    
     tl_master_d_ready = 1; // ready to accept
     tl_master_a_valid = 0; // take valid away
     //
     // wait on channel D for  respond
     if (!tl_err) begin
        //
        i = 0;
        @(posedge clock);
        while (!tl_master_d_valid && (i < MAX_TIMEOUT)) begin
           i = i + 1;                  
           @(posedge clock);
           if (i >= MAX_TIMEOUT) begin
          `logE("**ERROR** timeout while waiting for data from channelD src=%d a=0x%x",src_id,a);
          tl_err = 1;         
           end
        end
        
     end // if (tl_master_a_ready)
     @(posedge clock);   
      end
   endtask // checkReset
   //
   // =============================
   // To handle cache coherency!!!
   // =============================   
   // If see PROBE on B, send and ProbeAck on C
   integer t;
   
   always @(posedge clock) begin
      if (tl_master_b_valid) begin
     if (tl_master_b_bits_opcode == `TL_B_PROBE) begin
        `logD("Got a PROBE from channel B src=0x%x adr=0x%x cap=0x%x.. Sending back probeACK on C",
          tl_master_b_bits_source,tl_master_b_bits_address,tl_master_b_bits_param);
        //
        // copy before they go away
        tl_master_c_bits_param   = tl_master_b_bits_param;
        tl_master_c_bits_size    = tl_master_b_bits_size;
        tl_master_c_bits_source  = tl_master_b_bits_source;
        tl_master_c_bits_address = tl_master_b_bits_address;
        tl_master_c_bits_data    = 0;
        tl_master_c_bits_corrupt = 0;
        // respond
        @(negedge clock);
        tl_master_b_ready = 0;
        tl_master_c_valid = 1;
        tl_master_c_bits_opcode  = `TL_C_PROBEACK;
        // wait until slave took it
        t = 0;
        @(posedge clock);        
        while (!tl_master_c_ready && (t < MAX_TIMEOUT)) begin
           t = t + 1;               
           @(posedge clock);
           if (i >= MAX_TIMEOUT) begin
          `logE("**ERROR** timeout while waiting for ready on channelB src=%d a=0x%x",tl_master_c_bits_source,tl_master_c_bits_address);
          tl_err = 1;
           end
        end
        @(negedge clock);
        tl_master_c_valid = 0; // take it away
        tl_master_b_ready = 1;
     end // if (tl_master_b_bits_param == `CAP_toN)
     else begin
        `logE("ERROR:Got a PROBE from channel B src=0x%x adr=0x%x.. but don't  know how to repsond to OPCODE=0x%x PARAM=%d",
          tl_master_b_bits_source,tl_master_b_bits_address,tl_master_b_bits_opcode,tl_master_b_bits_param);     
     end
      end
   end // always @ (posedge clock)
   
   //
   // some quick self-test (called from the top)
   //
//`define WRITE_PARTIAL   
   task selfTest;
      input [ADR_WIDTH-1:0] baseReg; // register to play with
      //
      output            error;
      reg [ADR_WIDTH-1:0]   adr;
      reg [63:0]        wd64, rd64;
      integer           i,l;
      begin
     error = 0;
     tl_err = 0;
     // =======================
     // revision register and check
     // =======================  
     //
     adr = 'h700F_0000;
     `logI("=== TL-UL Checking FPGA version ===");   
     wd64 = 64'h0002_0000_0000_0000;
     for (l=0;l<2;l=l+1) begin // RO
        tl_a_ul_read(CHIP_ID & 1, adr, rd64); // source=0 or 1 ONLY
        if (wd64 !== rd64) begin
           `logE("%m: **ERROR** Version Reg adr=0x%x exp=0x%x act=0x%x %t",adr,wd64,rd64,$time);
           error = 1;
        end
        else begin
           `logI("%m: OK Version adr=0x%x exp=0x%x act=0x%x %t",adr,wd64,rd64,$time);       
        end
        // write and make sure it never change
        if (l == 0) begin
           tl_a_ul_write(CHIP_ID & 1, adr, ~wd64); // source=0 or 1 ONLY           
        end
     end // for (l=0;l<2;l=l+1)
     //
     // =======================  
     // TL-UL read/write partial&full
     // =======================  
     //
     `ifdef WRITE_PARTIAL
     //
     // Using PUTPARTIAL
     //
     `logI("%m: === TL-UL Data bus walk 0/1 test with Partial mask ===");    
     adr = baseReg;  
     for (i=0;i<64;i=i+1) begin
        if (error) break;
        //
        case (CHIP_ID)
          3:       wd64 = 1 << i;         // walking 1 from LSB
          2:       wd64 = 1 << (63-i);    // walking 1 from MSB
          1:       wd64 = ~(1 << i);      // walking 0 from LSB
          default: wd64 = ~(1 << (63-i)); // walking 1 from LSB       
        endcase // case (CHIP_ID)
        // write
        tl_a_ul_write_generic(CHIP_ID & 1, adr, {wd64[63:32],32'h12345678},'hF0,2); // upper
        tl_a_ul_write_generic(CHIP_ID & 1, adr, {32'h9ABCDEF0,wd64[31:0]},'h0F,2); // lower
        // read back and compare
        tl_a_ul_read(CHIP_ID & 1, adr, rd64); // source=0 or 1 ONLY
        //
        if (wd64 != rd64) begin
           `logI("%m: **ERROR** adr=0x%x exp=0x%x act=0x%x i=%d",adr,wd64,rd64,i);
           error = 1;
        end
        else begin
           `logI("%m: OK adr=0x%x exp=0x%x act=0x%x i=%d",adr,wd64,rd64,i);     
        end
     end // for (i=0;i<64;i=i+1)
     `endif
     //
     // Using PUTFULL
     //
     `logI("%m: === TL-UL Data bus walk 0/1 test with full mask ===");   
     adr = baseReg;  
     for (i=0;i<64;i=i+1) begin
        if (error) break;       
        case (CHIP_ID)
          0:       wd64 = 1 << i;         // walking 1 from LSB
          1:       wd64 = 1 << (63-i);    // walking 1 from MSB
          2:       wd64 = ~(1 << i);      // walking 0 from LSB
          default: wd64 = ~(1 << (63-i)); // walking 1 from LSB       
        endcase // case (CHIP_ID)
        // write
        tl_a_ul_write(CHIP_ID & 1, adr, wd64); // source=0 or 1 ONLY
        // read back and compare
        tl_a_ul_read(CHIP_ID & 1, adr, rd64); // source=0 or 1 ONLY
        //
        if (wd64 != rd64) begin
           `logI("%m: **ERROR** adr=0x%x exp=0x%x act=0x%x i=%d",adr,wd64,rd64,i);
           error = 1;
        end
        else begin
           `logI("%m: OK adr=0x%x exp=0x%x act=0x%x i=%d",adr,wd64,rd64,i);     
        end
     end // for (i=0;i<64;i=i+1)
      end
   endtask
   
endmodule // tl_master__beh
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      tl_slave_beh.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Tilelink Slave Bus Functional Model for the
//                 CEP Co-Simulation Environment
// Notes:          
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "tl_defines.incl"
`include "v2c_top.incl"
module tl_slave_beh 
  #(parameter
    CHIP_ID=0, // for sim ONLY
    SRC_SIZE=2,
    SINK_SIZE=3,
    BUS_SIZE=8, 
    ADR_WIDTH=32,
    //
    localparam TL_SIZE=$clog2(BUS_SIZE),
    localparam DATA_WIDTH=(BUS_SIZE*8)
    )
   ( // Master mode
     input 			 clock, 
     input 			 reset, 
     // Channel A
     output reg 		 tl_a_ready=1, 
     input 			 tl_a_valid, 
     input [2:0] 		 tl_a_bits_opcode, 
     input [2:0] 		 tl_a_bits_param, 
     input [TL_SIZE-1:0] 	 tl_a_bits_size, 
     input [SRC_SIZE-1:0] 	 tl_a_bits_source, 
     input [ADR_WIDTH-1:0] 	 tl_a_bits_address, 
     input [BUS_SIZE-1:0] 	 tl_a_bits_mask, 
     input [DATA_WIDTH-1:0] 	 tl_a_bits_data, 
     input 			 tl_a_bits_corrupt, 
    // Channel D
     input 			 tl_d_ready, // default 
     output reg 		 tl_d_valid=0, 
     output reg [2:0] 		 tl_d_bits_opcode=0, 
     output reg [1:0] 		 tl_d_bits_param=0, 
     output reg [TL_SIZE-1:0] 	 tl_d_bits_size=0, 
     output reg [SRC_SIZE-1:0] 	 tl_d_bits_source=0, 
     output reg [SINK_SIZE-1:0]  tl_d_bits_sink=0, 
     output reg 		 tl_d_bits_denied=0, 
     output reg [DATA_WIDTH-1:0] tl_d_bits_data=0, 
     output reg 		 tl_d_bits_corrupt=0,
     // system side
     output reg 		 req,
     output reg [ADR_WIDTH-1:0]  adr,
     output reg 		 rdWr=0,
     output reg [63:0] 		 wrDat,
     input [63:0] 		 rdDat,
     input 			 ack
     );
   //
   // Very simple TL-UL Only A/D
   //
   always @(posedge tl_a_valid) begin
      if (tl_a_bits_opcode == `TL_A_PUTFULLDATA) begin // write
	 @(posedge clock);#1;
	 req   = 1;
	 adr   = tl_a_bits_address;	 	 
	 rdWr  = 0;
	 wrDat = tl_a_bits_data;
	 tl_d_valid = 1;
	 tl_d_bits_opcode= `TL_D_ACCESSACK;
	 tl_d_bits_param = tl_a_bits_param;
 	 tl_d_bits_size  = tl_a_bits_size;
	 tl_d_bits_source= tl_a_bits_source;
	 tl_d_bits_sink  = 0;
	 @(posedge clock);#1;
	 tl_d_valid = 0;
	 @(posedge ack); // wait
	 req = 0;
      end // if (tl_a_bits_opcode == TL_A_PUTFULLDATA)
      else if (tl_a_bits_opcode == `TL_A_GET) begin // read
	 // issue a read to system
	 @(posedge clock);#1;	 
	 req  = 1;
	 rdWr = 1;
	 adr  = tl_a_bits_address;	 
	 @(posedge ack); // wait
	 @(posedge clock);#1;	
	 req  = 0;
	 tl_d_valid = 1;
	 tl_d_bits_opcode= `TL_D_ACCESSACKDATA;
	 tl_d_bits_param = tl_a_bits_param;
 	 tl_d_bits_size  = tl_a_bits_size;
	 tl_d_bits_source= tl_a_bits_source;
	 tl_d_bits_sink  = 0;
	 tl_d_bits_data  = rdDat;
	 @(posedge clock);#1;
	 tl_d_valid = 0;	 
      end
   end
endmodule // tl_slave_beh
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: BSD-2-Clause
//
// File Name:      uart_model.sv
// Program:        Common Evaluation Platform (CEP)
// Description:    CEP Co-Simulation Top Level Testbench 
// Notes:          UART Model that will receive and log a line of text
//
//--------------------------------------------------------------------------------------
`include "suite_config.v"
`include "cep_hierMap.incl"
`include "cep_adrMap.incl"
`include "v2c_cmds.incl"
`include "v2c_top.incl"
module uart_model #(
  parameter   BIT_RATE        = 9600,
  parameter   CLK_HZ          = 50_000_000,
  parameter   PAYLOAD_BITS    = 8,
  parameter   STOP_BITS       = 1
) (
  input  wire       clk          ,
  input  wire       resetn       ,
  input  wire       uart_rxd     ,
  input  wire       uart_rx_en
);
  localparam LINE_BUFFER_MAX_LENGTH     = 132;
  reg[LINE_BUFFER_MAX_LENGTH*8 - 1:0]   line_buffer_reg = 0;
  wire                                  uart_rx_valid;
  wire                                  uart_rx_break;
  wire [7:0]                            uart_rx_data;
  // Testbench UART receiver
  uart_rx #(
    .BIT_RATE(BIT_RATE),
    .CLK_HZ(CLK_HZ),
    .PAYLOAD_BITS(PAYLOAD_BITS),
    .STOP_BITS(STOP_BITS)
  ) uart_rx_inst (
    .clk              (clk),
    .resetn           (resetn),
    .uart_rxd         (uart_rxd),
    .uart_rx_en       (uart_rx_en),
    .uart_rx_break    (uart_rx_break),
    .uart_rx_valid    (uart_rx_valid),
    .uart_rx_data     (uart_rx_data)
  );  
  always @(posedge clk)
  begin
    if (uart_rx_valid) begin
      `logI("TB_UART = %x", uart_rx_data);
      line_buffer_reg = {line_buffer_reg[LINE_BUFFER_MAX_LENGTH*8 - 9:0], uart_rx_data};
      if (uart_rx_data == 8'h0a) begin
        `logI("TB_UART_LINE: %0s", line_buffer_reg);
        line_buffer_reg = 0;
      end
    end // end if (uart_rx_valid)
  end   // always @(clk)
endmodule
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
// SPDX short identifier: MIT
//
// File Name:      uart_rx.v
// Program:        Common Evaluation Platform (CEP)
// Description:    UART Receiver for Co-Simulation environment
// Notes:          Source: https://github.com/ben-marshall/uart
//
//--------------------------------------------------------------------------------------
module uart_rx #(
  parameter   BIT_RATE        = 9600,
  parameter   CLK_HZ          = 50_000_000,
  parameter   PAYLOAD_BITS    = 8,
  parameter   STOP_BITS       = 1
) (
input  wire       clk          , // Top level system clock input.
input  wire       resetn       , // Asynchronous active low reset.
input  wire       uart_rxd     , // UART Recieve pin.
input  wire       uart_rx_en   , // Recieve enable
output wire       uart_rx_break, // Did we get a BREAK message?
output wire       uart_rx_valid, // Valid data recieved and available.
output reg  [PAYLOAD_BITS-1:0] uart_rx_data   // The recieved data.
);
// Input bit rate of the UART line.
localparam  BIT_P           = 1_000_000_000 * 1/BIT_RATE;   // nanoseconds
// Clock frequency in hertz.
localparam  CLK_P           = 1_000_000_000 * 1/CLK_HZ;     // nanoseconds
// Number of clock cycles per uart bit.
localparam       CYCLES_PER_BIT     = BIT_P / CLK_P;
//
// Size of the registers which store sample counts and bit durations.
localparam       COUNT_REG_LEN      = 1+$clog2(CYCLES_PER_BIT);
// -------------------------------------------------------------------------- 
// Internal registers.
// 
//
// Internally latched value of the uart_rxd line. Helps break long timing
// paths from input pins into the logic.
reg rxd_reg;
reg rxd_reg_0;
//
// Storage for the recieved serial data.
reg [PAYLOAD_BITS-1:0] recieved_data;
//
// Counter for the number of cycles over a packet bit.
reg [COUNT_REG_LEN-1:0] cycle_counter;
//
// Counter for the number of recieved bits of the packet.
reg [3:0] bit_counter;
//
// Sample of the UART input line whenever we are in the middle of a bit frame.
reg bit_sample;
//
// Current and next states of the internal FSM.
reg [2:0] fsm_state;
reg [2:0] n_fsm_state;
localparam FSM_IDLE = 0;
localparam FSM_START= 1;
localparam FSM_RECV = 2;
localparam FSM_STOP = 3;
// --------------------------------------------------------------------------- 
// Output assignment
// 
assign uart_rx_break = uart_rx_valid && ~|recieved_data;
assign uart_rx_valid = fsm_state == FSM_STOP && n_fsm_state == FSM_IDLE;
always @(posedge clk) begin
    if(!resetn) begin
        uart_rx_data  <= {PAYLOAD_BITS{1'b0}};
    end else if (fsm_state == FSM_STOP) begin
        uart_rx_data  <= recieved_data;
    end
end
// --------------------------------------------------------------------------- 
// FSM next state selection.
// 
wire next_bit     = cycle_counter == CYCLES_PER_BIT ||
                        fsm_state       == FSM_STOP && 
                        cycle_counter   == CYCLES_PER_BIT/2;
wire payload_done = bit_counter   == PAYLOAD_BITS  ;
//
// Handle picking the next state.
always @(*) begin : p_n_fsm_state
    case(fsm_state)
        FSM_IDLE : n_fsm_state = rxd_reg      ? FSM_IDLE : FSM_START;
        FSM_START: n_fsm_state = next_bit     ? FSM_RECV : FSM_START;
        FSM_RECV : n_fsm_state = payload_done ? FSM_STOP : FSM_RECV ;
        FSM_STOP : n_fsm_state = next_bit     ? FSM_IDLE : FSM_STOP ;
        default  : n_fsm_state = FSM_IDLE;
    endcase
end
// --------------------------------------------------------------------------- 
// Internal register setting and re-setting.
// 
//
// Handle updates to the recieved data register.
integer i = 0;
always @(posedge clk) begin : p_recieved_data
    if(!resetn) begin
        recieved_data <= {PAYLOAD_BITS{1'b0}};
    end else if(fsm_state == FSM_IDLE             ) begin
        recieved_data <= {PAYLOAD_BITS{1'b0}};
    end else if(fsm_state == FSM_RECV && next_bit ) begin
        recieved_data[PAYLOAD_BITS-1] <= bit_sample;
        for ( i = PAYLOAD_BITS-2; i >= 0; i = i - 1) begin
            recieved_data[i] <= recieved_data[i+1];
        end
    end
end
//
// Increments the bit counter when recieving.
always @(posedge clk) begin : p_bit_counter
    if(!resetn) begin
        bit_counter <= 4'b0;
    end else if(fsm_state != FSM_RECV) begin
        bit_counter <= {COUNT_REG_LEN{1'b0}};
    end else if(fsm_state == FSM_RECV && next_bit) begin
        bit_counter <= bit_counter + 1'b1;
    end
end
//
// Sample the recieved bit when in the middle of a bit frame.
always @(posedge clk) begin : p_bit_sample
    if(!resetn) begin
        bit_sample <= 1'b0;
    end else if (cycle_counter == CYCLES_PER_BIT/2) begin
        bit_sample <= rxd_reg;
    end
end
//
// Increments the cycle counter when recieving.
always @(posedge clk) begin : p_cycle_counter
    if(!resetn) begin
        cycle_counter <= {COUNT_REG_LEN{1'b0}};
    end else if(next_bit) begin
        cycle_counter <= {COUNT_REG_LEN{1'b0}};
    end else if(fsm_state == FSM_START || 
                fsm_state == FSM_RECV  || 
                fsm_state == FSM_STOP   ) begin
        cycle_counter <= cycle_counter + 1'b1;
    end
end
//
// Progresses the next FSM state.
always @(posedge clk) begin : p_fsm_state
    if(!resetn) begin
        fsm_state <= FSM_IDLE;
    end else begin
        fsm_state <= n_fsm_state;
    end
end
//
// Responsible for updating the internal value of the rxd_reg.
always @(posedge clk) begin : p_rxd_reg
    if(!resetn) begin
        rxd_reg     <= 1'b1;
        rxd_reg_0   <= 1'b1;
    end else if(uart_rx_en) begin
        rxd_reg     <= rxd_reg_0;
        rxd_reg_0   <= uart_rxd;
    end
end
endmodule
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
//
// File Name:      suite_config.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Testbench Defines for the Bare Metal Test Suite
// Notes:          
//
//--------------------------------------------------------------------------------------
`timescale 1ns/100ps
 | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
//
// File Name:      suite_config.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Testbench Defines for the BFM Test Suite
// Notes:          
//
//--------------------------------------------------------------------------------------
`timescale 1ns/100ps | 
| 
	//--------------------------------------------------------------------------------------
// Copyright 2022 Massachusets Institute of Technology
//
// File Name:      suite_config.v
// Program:        Common Evaluation Platform (CEP)
// Description:    Testbench Defines for the isa Test Suite
// Notes:          
//
//--------------------------------------------------------------------------------------
`timescale 1ns/100ps
 | 
| 
	#***********************************************************************
# Copyright 2022 Massachusets Institute of Technology
# SPDX short identifier: BSD-2-Clause
#
# File Name:      CMakeLists.txt
# Program:        Common Evaluation Platform (CEP)
# Description:    CMake file
# Notes:          
#************************************************************************
cmake_minimum_required(VERSION 3.8)
project(gpiotest C)
set(CMAKE_C_STANDARD 11)
add_executable(gpiotest gpiotest.c)
target_include_directories(gpiotest PRIVATE)
target_link_libraries(gpiotest PRIVATE "gpiod")
set(CMAKE_INSTALL_PREFIX "/usr" CACHE PATH "Standard install prefix" FORCE)
install(TARGETS gpiotest RUNTIME DESTINATION bin) | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.
