About volatile writes

I'm having trouble understanding the concept of a volatile write. I know what a volatile read is but I don't think I have ever thought about the opposite.

Could someone shed some light into this topic for me? I read the documentation but I ended up just as lost as before.

In its simplest form, a volatile write is a write operation that can have side-effects of arbitrary consequence that are unknown to the compiler. For example, a volatile write to a configuration register of an SoC (system on a chip) might reconfigure some of the chip peripheral devices, or push a byte into a communication FIFO. Because the potential side effects are unknown to the compiler, many of the compiler's usual optimizations have to be suppressed. For example, if on each iteration a loop writes an 0x20 to a non-volatile memory location, the compiler can move that write out of the loop and do it only once. But if writing to a volatile memory location, you might be outputting a space character with each write, so the compiler can't optimize that write out of the loop.

Interestingly, the example in the Rust documentation of volatile that you cite in your post above is potentially flawed, because the assert_eq!(…) appears to assume that what is written to a volatile location can be read back unchanged. Many hardware peripherals on chips do not behave that way; they have separate, only loosely correlated, input-only status bytes and output-only command bytes assigned to the same hardware address(es).

Edit: In Rust it is read and write operations, not memory locations, that can be volatile, so please make the appropriate adjustments in the above example.

5 Likes

Makes sense. Thanks for the thorough explanation!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.