OpenXiangShan / NEMU

Other
224 stars 84 forks source link

NEMU does not trap when accessing unimplemented CSRs #392

Closed shinezyy closed 1 month ago

shinezyy commented 1 month ago

In src/isa/riscv64/system/priv.c, csr_read always returns *src even if this CSR is not defined, and does not trap.

However, OpenSBI uses the trap behavior to decide whether an extension/feature is implemented: https://github.com/riscv-software-src/opensbi/blob/0a667542950ac108e609c2bdfed4c0df87363717/include/sbi/sbi_csr_detect.h#L17

When CONFIG_RV_SMSTATEEN is not enabled in NEMU, reading mstateen0 returns *src and does not trap. Then OpenSBI thinks NEMU implements SMSTATEEN

cebarobot commented 1 month ago

I think accessing mstateen0 without CONFIG_RV_SMSTATEEN would trap into EX_II.

First, without CONFIG_RV_SMSTATEEN, mstateen0 would not defined in CSR.h: https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/local-include/csr.h#L318-L324

Then, csr_exist[4096] is initialized: https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L41-L48

After that, NEMU will traped when trying to accessing NEMU:

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L1031-L1035

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L91-L99

Function csr_read() and csr_write() just do the read and write. Accessiblity checking is done in csrrw() function.

Do you have any tests that may cause this problem?

shinezyy commented 1 month ago

I think accessing mstateen0 without CONFIG_RV_SMSTATEEN would trap into EX_II.

First, without CONFIG_RV_SMSTATEEN, mstateen0 would not defined in CSR.h:

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/local-include/csr.h#L318-L324

Then, csr_exist[4096] is initialized:

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L41-L48

After that, NEMU will traped when trying to accessing NEMU:

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L1031-L1035

https://github.com/OpenXiangShan/NEMU/blob/84c7e4068512c90bb6a45c4b42a9309f459998b9/src/isa/riscv64/system/priv.c#L91-L99

Function csr_read() and csr_write() just do the read and write. Accessiblity checking is done in csrrw() function.

Do you have any tests that may cause this problem?

Running OpenSBI and difftest against Spike

shinezyy commented 1 month ago

Cannot be reproduced on current master (ec82526c0c69317cec4046e31)