In an svd2rust-generated peripheral access crate, how do a register's `write` and `modify` closures differ, and why are raw `bits()` writes `unsafe`?
answer
- the writer's starting value
- reset value versus current value
- one load, one store
- the SVD cannot prove every pattern
- one-bit fields stay safe
basics
~20 swrite starts from the register's reset value, so unnamed fields are reset; modify reads the current value and changes only the named fields. Raw bits() is unsafe because the SVD file cannot prove every bit pattern is valid.
solid answer
~40 sEvery svd2rust register is a `Reg` with closure-based methods. `read()` returns an `R` with a reader per field, such as `r.odr5().bit_is_set()`. `write(|w| ...)` hands the closure a `W` that starts from the register's **reset value** and then performs one volatile store, so `odr().write(|w| w.odr5().set_bit())` sets pin 5 and returns every other pin to its reset state. `modify(|r, w| ...)` does one volatile load, starts `w` from the **current** value and stores the result, so other fields keep their state; the load and store are separate, though, so an interrupt in between can lose an update. One-bit fields get safe `set_bit`, `clear_bit` and `bit(b)`. A multi-bit field's `bits()` and the register-wide `W::bits` are `unsafe`; when the SVD declares every value legal a safe `set()` exists beside them, and enumerated values give a safe `variant()`.
code
rust · 21 linesuse minipac::gpioa::RegisterBlock;
#[test]
fn write_vs_modify() {
// Stand-in memory for GPIOA: MODER at its reset value, ODR with pin 6 high.
let mut mem = [0xA800_0000u32, 0b0100_0000];
let gpio: &RegisterBlock = unsafe { &*(mem.as_mut_ptr() as *const RegisterBlock) };
gpio.odr().modify(|_, w| w.odr5().set_bit());
assert_eq!(gpio.odr().read().bits(), 0b0110_0000); // pin 6 kept
gpio.odr().write(|w| w.odr5().set_bit());
assert_eq!(gpio.odr().read().bits(), 0b0010_0000); // pin 6 back to reset value 0
gpio.odr().modify(|r, w| w.odr5().bit(!r.odr5().bit_is_set())); // toggle
assert!(gpio.odr().read().odr5().bit_is_clear());
gpio.moder().modify(|_, w| unsafe { w.moder5().bits(0b01) }); // 2-bit field
assert_eq!(gpio.moder().read().moder5().bits(), 0b01);
assert_eq!(gpio.moder().read().bits(), 0xA800_0400); // other fields untouched
}go deeper
Recall read, write and modify on a PAC register, and that write resets every field the closure does not name.
Explain reset value versus current value as the writer's starting point, the single load and store, and why a multi-bit bits() write needs unsafe.
Spot the lost update when an interrupt changes the same register between modify's load and store, and know the safe set(), variant() and atomics alternatives.
Set the habit that raw bits() writes carry a SAFETY comment citing the reference manual, and that multi-step peripheral procedures live in a HAL, not scattered PAC calls.
## Where the API comes from `svd2rust` reads a vendor's **SVD file** (XML listing every peripheral, register, bit field, reset value and allowed values) and generates a peripheral access crate. Each peripheral dereferences to a `RegisterBlock`. Since svd2rust 0.31 each register is reached through a method such as `gpioa.odr()` rather than a public field, so older examples written `gpioa.odr.write(...)` no longer match current output. Every register is a `Reg<SPEC>` wrapping a `vcell::VolatileCell`, so each access is a real volatile load or store that the compiler cannot merge or drop. ## The three access methods 1. **`read()`** loads the register once and returns an `R`. Field readers hang off it: `r.odr5().bit_is_set()`, `r.moder5().bits()`, or `r.bits()` for the whole word. 2. **`write(|w| ...)`** creates a `W` whose bits start at the register's **reset value**, lets the closure change fields, and stores the result once. The identity closure `|w| w` writes the reset value (adjusted only for write-one-to-clear style fields, described below), much as `reset()` does. 3. **`modify(|r, w| ...)`** loads the register once, gives the closure `r` (the old value) and a `W` that starts from that **current value**, and stores once. Fields the closure does not touch keep what they held. | Method | Writer starts from | Accesses | Fields you do not name | |---|---|---|---| | `write` | reset value | one store | return to their reset value | | `modify` | current value | one load, one store | keep their value | | `reset` | reset value | one store | all at reset | A host test against a stand-in register shows the difference: with pin 6 of an output register already high, `modify(|_, w| w.odr5().set_bit())` leaves `0b0110_0000`, while `write(|w| w.odr5().set_bit())` leaves `0b0010_0000`, because pin 6's reset value is 0. `write` and `modify` also return the raw value they stored, and the variants `from_write` and `from_modify` let the closure return a value of its own, which is useful when the new setting is computed inside the closure and needed afterwards. ## Why modify is not atomic `modify` is a read-modify-write in ordinary instructions. If an interrupt handler changes the same register between the load and the store, the store overwrites the handler's change; guarding against that is the job of critical sections and the interrupt-safety rules covered with interrupts and shared state. svd2rust's `--atomics` flag generates `set_bits`, `clear_bits` and `toggle_bits` methods that change bits without a read-modify-write sequence; they are themselves `unsafe` and need the `portable-atomic` crate. ## When bits() is unsafe - `W::bits(raw)` on a whole register is always an `unsafe fn`. When svd2rust marks the register safe, because its single field or the register itself has a write constraint covering every value, a safe `W::set(raw)` exists beside it. - A multi-bit field's `bits(value)` has been `unsafe` since svd2rust 0.33 (its changelog: "Make field writer `bits` always `unsafe`, add `set` for safe writing"). The value is **masked** to the field width, so `bits(6)` on a two-bit field writes `2` instead of carrying into the neighbouring field. - When the SVD gives a field a write constraint covering its full range, the field gets a safe `set(value)`; with a narrower range, `set` asserts at run time that the value is inside it. - **Enumerated values** in the SVD produce `variant(...)` and named methods, which are safe because only listed values can be written. - **One-bit fields** without a write constraint are safe: `set_bit()`, `clear_bit()` and `bit(bool)`. The generator's own doc comment states the reason: passing an incorrect value "can cause undefined behaviour. See reference manual". An SVD file often says nothing about which bit patterns are reserved, so svd2rust leaves that promise to the caller. ## Write-one-to-clear flags Status registers often hold flags cleared by writing 1. svd2rust records such fields in `ONE_TO_MODIFY_FIELDS_BITMAP` (and fields changed by writing 0 in `ZERO_TO_MODIFY_FIELDS_BITMAP`), and both `write` and `modify` start the writer with those bits at their no-effect value, so rewriting a register through `modify` does not clear a pending flag by accident. ## Habits that follow - Use `modify` to change one field of a configuration register; use `write` when you mean to set the whole register. - Prefer named field methods, `set()` and `variant()` over raw `bits()`, and give each remaining `unsafe` a SAFETY comment citing the reference manual. - Reach for the HAL when a peripheral needs a multi-step procedure; the PAC writes exactly what you ask, valid or not.
- How do you toggle a single bit with an svd2rust register API?Use the reader inside `modify`: `odr().modify(|r, w| w.odr5().bit(!r.odr5().bit_is_set()))`. The closure gets the value loaded at the start, flips one field, and the single store keeps every other field. It is still a load followed by a store, not an atomic toggle.
- What does `reg.write(|w| w)` do on an svd2rust register?It writes the register's reset value, because the writer starts from the reset value and the identity closure changes nothing; only fields of the write-one-to-clear kind are first set to their no-effect value. `reset()` writes the plain reset value. It is a common way to clear a configuration register back to its documented power-on state.
- Why does older embedded Rust code write `gpioa.odr.write(...)` while current PACs need `gpioa.odr().write(...)`?svd2rust before 0.31 exposed registers as public fields of the register block. Version 0.31 switched to accessor methods for every register and cluster, so code written against an older PAC needs the parentheses added when the PAC is regenerated or upgraded.
- write changes only the fields named in the closure and leaves the rest alone.
- modify is a single atomic instruction, so interrupts cannot interfere with it.
- bits() is unsafe because it dereferences a raw pointer to the register.
- Passing 6 to a two-bit field's bits() carries into the neighbouring field.
- The register value is cached in the struct and written back later.