csrwpseudo

csrw

pseudo
RISC-V Assembly Reference

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

Description

csrw copies a register into a control register. A control and status register, or CSR, holds processor state such as the trap handler address and the interrupt switches (see csrrw). The form below copies rs into the CSR and discards the old value.

csrw csr, rs

It is a pseudo-instruction, a readable name that the assembler rewrites into a real instruction. It becomes the instruction below, where rd is zero so the old value is not read.

csrrw zero, csr, rs

The most common use sets the trap handler. The lines below put the address of the label handler into mtvec.

la t0, handler
csrw mtvec, t0

The low two bits of mtvec select the mode. With 00, every trap jumps to the address in mtvec. With 01, called vectored mode, an interrupt jumps to the address plus 4 times its cause code, so the button interrupt, code 11, lands 44 bytes past the base address. The address itself must have its low two bits free, because they hold the mode.

The RISC-V manual defines csrw csr, rs1 as csrrw x0, csr, rs1.

Expands to

csrrw zero, csr, rs

The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.

Example

li t0, 0x100
csrw mtvec, t0   # mtvec = 0x100