Home/Instructions/CSR Read/Write
CSRRW

RISC-V CSRRW Instruction Details

Instruction ManualI-type

Atomically swap CSR and integer register: read the old CSR value into rd and write rs1 into the CSR

Instruction Syntax

csrrw rd, csr, rs1
Operand Breakdown
Destination rd: general-purpose register receiving the result.
Source rs1: register holding the first operand.
Immediate imm: 12-bit signed value, sign-extended before operation with rs1.
ZicsrCSR OperationSystem

Instruction Encoding

31..20
imm[11:0]
19..15
rs1
14..12
funct3
11..7
rd
6..0
opcode

CSRRW uses opcode 1110011 (0x73), funct3 001. The rs1 field selects the source register, the 12-bit immediate provides the second operand, and rd selects the destination.

Format: I-type
opcode: 1110011 (0x73)
funct3: 001 (0x1)

Instruction Behavior

CSRRW atomically swaps values between a CSR and an integer register: reads the old CSR value (zero-extended to XLEN bits) into rd, and writes the initial value from rs1 into the CSR. If rd=x0, the instruction shall not read the CSR and shall not cause any CSR read side effects, though the write still occurs. If rs1=x0, the value zero is written to the CSR. This is the most direct CSR atomic read/write primitive, commonly used for saving/restoring CSR state during context switches.

Quick Understanding & Search Notes

CSRRW is a Zicsr atomic CSR read-modify-write instruction. CSR addresses are 12 bits, and whether read/write side effects occur depends on rd and on rs1 or uimm being x0/0.

CSRRW does not read the CSR when rd=x0; CSRRS/CSRRC do not write the CSR when rs1=x0.
Immediate forms use a zero-extended 5-bit uimm; uimm=0 suppresses writes for CSRRSI/CSRRCI.
Accessing absent CSRs, insufficient privilege, or illegally writing read-only CSRs raises illegal-instruction.

Common Usage Scenarios

Atomic & Sync

Understand this scenario with real code like «csrrw x5, mepc, x6 # x5 = old mepc; mepc = x6».

System & Privilege

Understand this scenario with real code like «csrrw x5, mepc, x6 # x5 = old mepc; mepc = x6».

Pre-Use Checklist

Syntax Check
  • Confirm the current instruction format is I-type.
  • Confirm the operand order matches the example.
Semantic Check
  • Ensure the destination register usage is compatible with the calling convention.
  • Confirm this is not the lower-level form of a pseudo-instruction expansion.

Pitfalls / Common Confusions

When rd=x0, CSR read and its side effects are suppressed, but write still occurs
rs1=x0 writes all zeros to the CSR, which may inadvertently clear critical control bits
Assembler provides CSRW(csr, rs1) → CSRRW x0, csr, rs1 (write-only, no read)

FAQ

Are CSR instructions memory atomics?

No. Atomic here means the CSR read-modify-write is one instruction, not an AMO to memory.

What does rd=x0 change?

For CSRRW it suppresses the CSR read and read side effects; CSRRS/CSRRC still read the CSR.