csrrw

csrrw

RISC-V Assembly Reference

lyszt.net covers csrrw and other RISC-V instructions in more detail.

Description

csrrw exchanges a control register with a general register. A control and status register (CSR) is a special register that holds processor state, including the trap handler address and whether interrupts are enabled. A CSR has a 12-bit number and typically a name like mtvec. Only CSR instructions can access CSRs, and lw or sw cannot. The name stands for atomic read and write CSR. Atomic means the read and the write occur as a single indivisible step.

csrrw rd, csr, rs1

The CSR's old value is written to rd, and rs1's value is written to the CSR. The line below stores the address in t0 into mtvec and leaves the previous mtvec value in t1.

csrrw t1, mtvec, t0

If rd is zero, the old value is discarded and the CSR is not read. This form is the csrw shorthand. If rs1 is zero, the CSR is overwritten with 0.

This simulator provides six CSRs: mstatus, mie, mtvec, mepc, mcause and mip. Writes to mip are ignored because the hardware sets it. Any other CSR number reads as 0 and ignores writes. See csrr for reading and csrs and csrc for changing single bits.

The RISC-V manual states that with rd=x0, csrrw does not read the CSR, and that csrrw with rs1=x0 attempts to write zero to it.

Example

li t0, 0x100
csrrw t1, mtvec, t0   # mtvec = 0x100, t1 = old mtvec