STM32 gotchas
269. ECC-protected SRAM may be not written immediately (with consequences on backup SRAMs)

Newer STM32 - such as 'H7, 'H5, 'U5 - have some or all portions of SRAM protected by ECC. The exact implementation - ECC row width, exact consequences of reading rows with single-bit and double-bit errors, individual SRAM portions' coverage (including the VBAT-powered backupSRAM), configurability - varies from family to family, or even between models within a family, so has to be looked up carefully in the given model's reference manual.

Usually, while the SRAM ECC is calculated with every write, the result is not written to the SRAM immediately. This is to optimize performance, as the write width may be narrower than the row width, thus write with ECC calculation in fact constitutes a read-modify-write cycle. The complete ECC row together with the changed portion and calculated ECC is thus kept in a buffer, so that a subsequent write to the same row does not require a new read. A side effect of this arrangement is also a slight decrease in consumption for such sequence of writes.

Note, that even word writes to unaligned addresses in fact result in two or three less-than-a-word-wide writes physically, thus they use this read-modify-write mechanism, too.

When does the buffer get written back to SRAM, is again dependent on the model. For example, in 'H7, it gets written only if an unaligned write outside the buffered row occurs; whereas in 'U5/'H5 it gets written back after 2 AHB cycles after the last access to given SRAM. Again, the details have to be checked in the respective reference manual and/or AN5342.

The consequence of this arrangement is, that if a reset occurs while the buffer hasn't been written back, the write gets lost. As SRAM usually gets initialized after reset, in most applications this does not matter. However, if SRAMs are intended to hold data across reset - either the VBAT-powered backupSRAM, or any portion of SRAM if the whole mcu is held under battery power in some of the ultralow-power modes, or even if just some values are expected to be retained across a "hot" reset without power removal - in these cases, it's important that the user keeps this mechanism in mind. For example in 'H7, AN5342 recommends to perform a dummy write to a different word inside the given SRAM area after such an "incomplete" write.

Besides AN5342, there is also a FAQ article for 'H7, with an example code snippet on this topic.

Also note, that AXI SRAM ECC granularity is 64-bits, as observed by user CHead.

There is also a less important consequence of the read-modify-write mechanism for less-than-a-word-wide writes: after reset, before the ECC-protected SRAM has been fully initialized, as such writes are preceded by a read, they may trigger an ECC error. Initialization has to be performed by aligned writes of complete words, this avoids the read thus ECC check.