Posted on

MaSoCist support of OpenSource synthesis for ECP5

Find the a (currently unstable) development branch here:

NOTE: In process of upgrading to ghdl v1.0 synthesis. The build system is currently not functional. Use the self extracting script from the Instructions (2) below for a frozen working configuration.

Configurations that work (from those appearing when you run ‘make which’ in the masocist top dir):

  • *-zpu-ghdlsynth: ZPUng setup with ‘beatrix’ configuration.
  • *-pyrv32-ghdlsynth: RISC-V 32 bit basic configuration, proof of concept only, not fully functional as SoC in synthesis (as of now)
    Note: You need to explicitely install the rv32 toolchain (inside the docker container) for this config:
    sudo apt-get install riscv32-binutils riscv32-gcc riscv32-newlib-libc


This can be done online in a browser, if you don’t run Linux, see also

Note: Since this setup depends on external packages, there is no guarantee it will build smoothly.

  1. Run docker container with exported USB devices (if you want to program the plugged in board right away):
    docker run -it --device=/dev/bus/usb hackfin/masocist:synth
  2. Pull synthesis self-extracting build script:
    wget && sh
  3. Pull packages and build:
    make all
  4. Configure platform:
    cd src/vhdl/masocist-opensource;
    make versa_ecp5-zpu-ghdlsynth
  5. Build for synthesis:
    make clean sw syn
  6. When successful, you’ll end up with a $(PLATFORM).SVF file in syn/.
  7. See next paragraph on how to program the board (this procedure will be simplified)

Supported boards

Currently, the following ECP5 based boards are supported/under scrutiny:

Programming with on board FT2232H JTAG interface:

Note that programming will only work when the container is run/started after plugging in the board.

To program the FPGA SRAM on the board with the produced SVF file:

  1. Make sure board is connected via USB and powered up.
  2. You may need to restart the container from above:
    docker start -i <id>
    where ‘id’ is the container id of the above stopped container (retrieve from shell history or with docker ps -a)
  3. Install openocd:
    sudo apt-get install openocd
  4. Make sure board is connected via USB and powered up, then run, inside $(MASOCIST)/syn:
    make download OPENOCD="sudo openocd"
  5. If you see a lot scrolling by, board programming tends to be successful (interface was recognized). You can ignore errors like:
    Error: tdo check error at line 26780
    as they are due to the changed USERCODE.
  6. You should see the segment display on the board ‘spinning’. Also, you can talk to the SoC through the UART at 115200, 8N1, for example using minicom:
    minicom -o -D /dev/ttyUSB1
    The output upon booting of the SoC should be:
Probing flash…
Flash Type: m25p128         
Booting beatrix HW rev: 04 @25 MHZ
------------- test shell -------------                                          
--        SoC for Versa ECP5        --                                          
            arch: ZPUng                                                          
--  (c) 2012-2020  --                                          
--     type 'h' for help            --                                          


Short summary on what works in particular and what does not:

Ram inference

RAM inference is currently problematic and needs to be investigated further. TODO:

  • Make synthesis recognize more variants of RAM with init values
  • Implement dual process true dual port RAM
  • Fully eliminate Verilog RAM wrapper workarounds

FSM optimization

Some FSM seem to optimize away in yosys. Needs to be investigated if it’s a VHDL synthesis or internal Yosys issue.

Vendor primitives

Vendor specific Black Box primitives will no longer have to be wrapped starting with new ghdl-1.0 releases (Container namehackfin/masocist:synth-1.0). However, for the time being you might want to visit:

So far tested primitives within MaSoCist:

  • JTAGG: Test access port to ZPUng and pyrv32 for JTAG debugging or automated in circuit emulation hardware tests.
  • EHXPLLL: PLL primitive for clock frequency conversion
  • USRMCLK: Access to SPI master clock on ECP5

Not working

  • System Interrupt Controller (CONFIG_SIC) is currently not supported: #1140
    Fixed. Make sure to install the up to date debian GHDL packages when reusing an old container:
    sudo apt-get update; sudo apt-get install ghdl ghdl-libs
    You also have to rebuild the module in src/ghdl-yosys-plugin:
    make clean all; sudo make install
  • FLiX DSP and JPEG core unsupported (due to true dual port RAM issues)
  • Under scrutiny: pktfifo (CONFIG_MAC) problematic (TDP BRAM issues)
  • Post map simulation does not work with DP16KD primitives, due to missing ‘whitebox’ model, see also #32. You will have to separately use the supplied vendor model from the Diamond libraries.
Posted on

RISC-V in the loop

Continuous integration (‘CI’) for hardware is a logical step to take: Why not do for hardware, what works fine for software?

To keep things short: I’ve decided to stick my proprietary RISC-V approach ‘pyrv32’ into the opensourced MaSoCist testing loop to always have an online reference that can run anywhere without massive software installation dances.

Because there’s still quite a part of the toolchain missing from the OpenSource repo (work in progress), only a stripped down VHDL edition of the pyrv32 is available for testing and playing around.

This is what it currently does, when running ‘make all test’ in the provided Docker environment:

  • Build some tools necessary to build the virtual hardware
  • Compile source code, create a ROM file from it as VHDL
  • Build a virtual System on Chip based on the pyrv32 core
  • Downloads the ‘official’ riscv-tests suite onto the virtual target and runs the tests
  • Optionally, you can also talk to the system via a virtual (UART) console


This is the quickest ‘online’ way without installing software. You might need to register yourself a docker account beforehand.

  1. Log in at the docker playground:
  2. Add a new instance of a virtual machine via the left panel
  3. Run the docker container:
    docker run -it hackfin/masocist
  4. Run the test suite:
    wget && sh && make all test
  5. Likewise, you can run the virtual console demo:
    make clean run-pyrv32
  6. Wait for Boot message and # prompt to appear, then type h for help.
  7. Dump virtual SPI flash:
    s 0 1
  8. Exit minicom terminal by Ctrl-A, then q.

What’s in the box?

  • ghdl, ghdlex: Turns a set of VHDL sources into a simulation executable that exposes signals to the network (The engine for the virtual chip).
  • masocist: A build system for a System on Chip:
    • GNU Make, Linux kconfig
    • Plenty of XML hardware definitions based on netpp.
    • IP core library and plenty of ugly preprocessor hacks
    • Cross compiler packages for ZPU, riscv32 and msp430 architectures
  • gensoc: SoC generator alias IP-XACT’s mean little brother (from another mother…)
  • In-House CPU cores with In Circuit Emulation features (Debug TAPs over JTAG, etc.):
    • ZPUng: pipelined ZPU architecture with optimum code density
    • pyrv32: a rv32ui compatible RISC-V core
  • Third party opensource cores, not fully verified (but running a simple I/O test):
    • neo430: a msp430 compatible architecture in VHDL
    • potato: a RISC-V compatible CPU design

Posted on

RISC-V experiments

Yes, the RISC-V is fun. It’s not only the market momentum it currently has, or the political aspects of disrupting the world of closed source processor IP. Its design is just a somewhat logical attractor, when you’ve made the way from classic RISC (MIPS) pipelines, over the DLX improvements with various visits to FPGA specific developments like Xilinx’ microblaze architecture, Altera’s NIOS or the Lattice lm32.

Starting with MIPS makes sense, beause you’ve got a well matured open source toolchain which you can use as a reference for regress-testing your newly developed architecture. However, at some point one will run into scratchy issues, like the branch delay slot (which requires workaround logic for in circuit emulation) or the not optimum instruction set density, let aside one of the biggest issues: absolute addressing versus pc relative (which was brought in with the MIPS16 ASE). So, sooner or later you will find out that the RISC-V arrangements are pretty optimal for this type of RISC architecture.

The classic RISC five stage pipeline

This is something that’s explained in detail in plenty of papers published from You will find a lot of valuable information from the driving forces behind the RISC-V architecture.

Anyway, these are the processing stages of that little bucket chain working in the processor — in parallel:

  • FE: The fetch stage, get an instruction word from instruction(program) memory
  • DE: Decode the instruction into an arithmetic, load/store, jump, branch or other function
  • EX: Execute the instruction
  • MEM: The memory stage is more complicated. Let’s discuss this later.
  • WB: Write back of a computed or loaded value to an internal register

In a chip architecture, bottlenecks will occur when much of the logic zoo gathers in one area of the silicon. In general, this is the case for often used multiplexers (these can be seen as routers, directing the data to the right logic). Flipflops do better, they will hold data in a register and can propagate the data to process to another area of the chip. Ok, we knew that, not too new.

Now the first question: If we have an instruction reading from data memory, when can we start asserting an address to the RAM? Answer: For most architectures, we can do that early in the DE stage. The ASCII art approach below demonstrates how that works for a fast reading scenario (READ_FAST): Data is READY one cycle after the READ event. If this was the case for all data access, we could omit the MEM stage. For a READ_WAIT scenario however, data might not be ready. So we just need this stage to determine whether data is ready and valid before we can write it to the destination register in the WB stage.

                 |   FE   |   DE   |   EX   |  MEM  |   WB   |
READ_FAST                    READ     READY          
READ_WAIT                    READ     WAIT    READY

On some architectures again, we might want to save on logic and not assert the READ event in the DE, but in the EX stage. Then we’d have to insert these infamous pipeline stalls that force the processor to wait (and do nothing) for these few cycles. On the other hand, we’d possibly save some adder and multiplexing logic in DE.

The same dispute can be carried out over branching. When a decision to branch can be taken, most architectures calculate a jump target address relative to the current program counter (of the DE stage). This can be calculated either in the DE stage, or by the ALU (arithmetic logic unit) in the EX stage (more about that later).

Branch penalties

When a branch is taken, i.e. if it turns out during the EX stage that the program counter that is fetched from (which by default – without branch prediction – just keeps incrementing linearly) is actually invalid, fetched and decoded data is thrown away until the data fetched from the target jump address is valid again. The cycles consumed by this ‘pipeline flushing’ is the so called branch penalty (‘BP’). The later we calculate the target address, the greater the ‘BP’.

Hands on

For this example, a RISC-V design (called ‘pyrv32’) was synthesized for a Spartan-6 LX45. No optimization to specific RAMs took place, the toolchain decides to allocate quite a bit of LUT RAM. A few words about this design:

  • Simplified RISC-Pipeline with minimum hazard scenarios, no branch delay slot (unlike MIPS)
  • RV32I instruction set compatibility, but missing CSR unit
  • Very simple exception/irq/debug/emulation support
  • 4-5 stage pipeline with shortcut logic to allow READ_FAST and READ_WAIT scenarios

The complete design is a fully working system on chip, like a microprocessor from the shelf with Ethernet MAC, I2C and what not. I wanted want to see things in a known working setup, so I basically swapped out the original ZPUng against our proprietary ‘pyrv32’:

‘Early’ branch calculation:

f_max = 62 MHz

Branch penalty: 2 cycles

‘Late’ branch calculation:

f_max = 68 MHz

Branch penalty: 3 cycles

For the ‘late’ branch calculation you can see the maximum clock frequency going up, likewise the LUT count. However, total count is lower for the entire SoC. Probably the synthesis is doing some optimization that would be subject to further scrutiny.

This branching option is a configureable variable (CONFIG_EARLY_BRANCH_DETECTION). By default it is True. This configuration provides – depending on the typical amount of branching – more power.

Bare bone

When synthesizing the CPU as single unit without the peripheral memory logic, the frequency variations are marginal:

  • ‘early’: f_max = 110 MHz
  • ‘late’: f_max = 114 MHz

This is to expect as logic congestion is reduced due to the missing peripheral and DMA bus logic.

Risc-V 32 bit for netpp node

Yes, the RiscV fits on the netpp node with the existing ‘dagobert’ configuration:

  • IRAM size: 0x8000
  • DRAM size: 0x4000
  • DMA scratch pad like with the ZPUng configuration: 2x 0x800
  • 54 MHz core clock

Although the DRAM memory is DMA capable by principle, the scratch pad must be used for all fast I/O (networking) like on the ZPUng architecture. The reason for this are a few configurations reserved for the future, like shared memory between cache, pyrv32 and the DSP extension which use the dual ports of the block ram to read 64 bit instructions from certain memory portions.

The DMA default width however is 16 bit, unlike 8 bit as on the ZPUng. This allows for higher throughput, like 1G ethernet. Not making sense on the netpp node, but on a camera, for example.

The tedious path to optimization

A lot of tweaking is necessary to crank f_max up to the possible maximum. Some tools will help you with that and point out stupid mistakes, with most of the synthesis tools it is a bit of trial and error and careful reading of the logfiles. These details are boring, so I will spare them here. Short version: You can get some interesting insight using the various floorplanning tools which can visualize signal and data paths between critical logic.

However, one may not want to go for maximum f_max, as most cycles are burnt elsewhere. Many things can be optimized in software or using clever DMA processing. This is where the CPU architecture is less relevant than a tricky SoC memory cross bar which allows the peripherals to use DMA while the CPU can do other things.

Optimization attack targets

There are a few deviations from the RISC-V standard you can look at:

  • Implementing the CSR as memory mapped unit by replacing csr register exchange/set/clr commands through memory mapped I/O range accesses: This spares you some logic in the CPU and avoids further congestion close to the ALU
  • Eliminating IRQ support all together by using DMA queues. This might appear odd, but for some data processing, pure DMA will do, and the main loop ends up to run deterministically.
CSR quirks

When implementing the CSR unit as memory mapped (to MMR space, i.e. memory mapped registers), there are a few quirks. First, remember that the CSRRS/CSRRC/CSRRW are supposed to be atomic, i.e. no emulation of the sort (1) Get register (2) or with value (3) write back is ok. Therefore this MMR mapped CSR needs to implement a W1C (write one to clear) respective W1S (…to set) logic. Because we only have write_enable or read_enable signals to the MMR I/O, W1C and W1S is to be implemented as shadow registers using an offset address.

Meaning, the register logic works as follows: An access to the CSR register 0xb05 will work with the following assembler instructions mapping, for example:

  • CSRRW: A simultaneous read/write from/to address 0xffe0000 + (0x0b05 << 2)
  • CSRRC: A W1C to  0xffe01000 + (0x0b05 << 2)
  • CSRRS: A W1S to 0xffe02000 + (0x0b05 << 2)

Thus, the W1* logic is implemented in the peripherals for each register. Note: Since the CSR is sitting in MMR, a read is subject to a delay. Under certain circumstances, the pipeline may stall for one cycle, depending on the previous memory access history. This has to do with the 4/5-Pipeline shortcut/delaying mechanisms.

Optimization updates:
  1. 02 Oct 2019: no IRQ, pure DMA (no CSR), register file moved to LUT RAM, debug logic mostly eliminated:
    | Module                             | Partition | Slices*       | Slice Reg     | LUTs          | LUTRAM        | BRAM/FIFO | DSP48A1 | BUFG  | BUFIO | BUFR  | DCM   | PLL_ADV   | Full Hierarchical Name                                                                        |
    | ++pyrv32_cpu_inst                  |           | 347/348       | 354/354       | 1035/1036     | 44/44         | 0/0       | 0/0     | 0/0   | 0/0   | 0/0   | 0/0   | 0/0       | netpp_node_top/soc/pyrv32_cpu_inst                                                            |