bluespec / Piccolo

RISC-V CPU, simple 3-stage pipeline, for low-end applications (e.g., embedded, IoT)
Apache License 2.0
301 stars 48 forks source link

Illegal instruction not handled properly #9

Closed acw1251 closed 5 years ago

acw1251 commented 5 years ago

When you have a branch instruction with an illegal funct3 field (e.g. 3'b010), the processor triggers an exception and jumps to the exception handler, but it sets the wrong cause to the mcause CSR. The cause should be illegal instruction (2) instead of instruction address misaligned (0). I haven't looked to see if there are any other illegal instructions that result in the wrong cause to be written to the mcause CSR.

The relevant code in Piccolo can be found here: https://github.com/bluespec/Piccolo/blob/master/src_Core/Core/EX_ALU_functions.bsv#L227-L239

And here is a small test I used to observe the error:

.text.init:

.globl _start
.globl tohost
.globl exit

_start:
    # setup trap handler
    la t0, trap_handler
    csrw mtvec, t0
    # do an illegal instruction that looks like a branch
    .word 0x00002063
    # .word 0x00001063 # legal branch
    li a0, 1337
    j write_tohost

trap_handler:
    csrr a0, mcause
    j write_tohost

write_tohost:
    slli t0, a0, 1
    ori t0, t0, 1
    la t1, tohost
    sw t0, 0(t1)
exit:
    j exit

.align 4

tohost:
    .word 0x0

This test prints PASS when it runs because the mcause CSR had 0 in it (the code for instruction address misaligned). This test should fail with a code of 2 representing an illegal instruction exception.

rsnikhil commented 5 years ago

Andy, thanks for finding this bug and for the detailed and accurate diagnosis. I have fixed the problem both in Piccolo and in Flute.