</>EmbeddedInterview

Why can a read-modify-write on a register be dangerous?

HardEmbedded C

Short answer: REG |= BIT; is three separate operations: read the register, OR in the bit, write it back. If anything changes the register between the read and the write (an ISR, another core, DMA, or the hardware itself), that change is overwritten. Read-modify-write can also clear write-1-to-clear flags you did not intend to touch, and lose data on registers that change when read.

Three classic failures

  1. Interrupt race:
/* main loop */                    /* ISR (runs between the read and the write) */
tmp = GPIOA->ODR;    /* reads 0x00 */
                                   GPIOA->ODR |= LED2;   /* ODR = 0x04 */
tmp |= LED1;
GPIOA->ODR = tmp;    /* writes 0x01: LED2 turned off again! */
  1. Write-1-to-clear flags: a status register has TC (transfer complete) and ERR flags, both cleared by writing 1. SR |= TC_FLAG; reads both as 1 and writes both back as 1, clearing an error you have not handled yet. Write SR = TC_FLAG;.

  2. Read side effects: some registers clear or pop on read (UART data registers, some interrupt status registers, FIFO registers). A read-modify-write consumes data.

  3. Hardware-updated bits: a control register may contain a bit the hardware clears when an operation finishes (e.g. a "start conversion" bit). Reading it as 1 and writing it back restarts the operation.

Solutions

Solution Notes
Hardware set/clear registers (STM32 BSRR/BRR, NXP SET/CLR/TOGGLE aliases, nRF OUTSET/OUTCLR) one write, atomic, best option
Bit-banding (Cortex-M3/M4 only) atomic single-bit writes
Critical section around the RMW simple; adds latency
LDREX/STREX loop atomic for normal memory; not usable on many peripheral registers
Ownership design so only one context ever writes a given register

Interview tip: mention that the same issue appears with shared variables, not just registers, and that it is the main reason for driver design rules such as "configure a peripheral only from one context".