liveBook · Manning

Read-modify-write operation

As explained in Embedded Software with Rust

Read-modify-write reads a value, changes selected parts, and writes the result back to the same location.

A read-modify-write operation reads a register, changes selected fields, then writes the updated value back. In a Peripheral Access Crate (PAC), `modify` provides this pattern: unmentioned fields keep their current values. Because the sequence reads before writing, another context such as an interrupt can update the register in between. section 5.3.3 section 5.3.1

gpioc.crh().modify(|_, w| {
    w.mode13().output2() // Set mode to output, 2MHz
     .cnf13().push_pull() // Set configuration to push-pull
});

This PAC call updates GPIO pin 13's mode and configuration fields in CRH while preserving the other fields. section 5.3.3

For GPIO output changes, STM32's BSRR register offers an alternative: writing set/reset bits changes pins without reading the current port state, avoiding the read-modify-write race. section 5.3.1 section 5.3.3

How Embedded Software with Rust covers it

How deep it goes
Traces a PAC modify call through a volatile load, read and write proxies, and one store; the sequence remains vulnerable to races.
Examples
Updates GPIO pin 13 through CRH and contrasts BSRR writes that set or reset pins without reading first.
What you can do after
Apply field-specific register updates through a PAC modify closure while retaining other register bits.
How it connects
Connects memory-mapped I/O, volatile access, peripheral access crates, GPIO registers, and interrupts.

Also explained in

Compare how 5 books explain read-modify-write operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.