Storing of QSPI buffer causing data corruption and hard faults

There’s a possibillity that your code is totally fine, but you’ll still run into a bus fault or something similar. You might be running into several unrelated issues here as it seems like you describe more than one symptom. You’d have to read parts of STM32H7 MCU reference manual for specific fault type explanation and some advanced topics (cache, MPU, memory barriers). It’s a fairly complex microcontroller with things like instructions / data caching and prefetched code executon with branch prediction and more fun stuff, so some errors are simply because you’re doing something that goes against normal patterns it’s designed to handle gracefully.

If your QSPI flash memory is configured to be cacheable by MPU settings, you would have to invalidate cache after writing, since writes happen when it’s not in memory mapped mode, so cached values from previous reads may persist. Cache is not aware that underlying contents have changed when you were sending flash command to reprogram the chip. An alternative is to configure QSPI access to be non-cacheable, but you’ll lose some read performance (might be acceptable or not depending on how you use flash).

Troubleshooting bus faults is more complicated, but I would guess that code prefetch might be the culprit here. In order to run your code at maximum speed, MCU can start in advance - while the hardware is still dealing with QSPI and you can’t fetch data from it. Or some of your code can be reorder if it gives theoretically the same results from computations (and become unsafe for things like switching QSPI peripheral modes). This can be resolved by adding ISB/DSB instruction via “__ISB”/“__DSB” macros (defined in CMSIS, IIRC) to ensure that memory barriers are added in required places. This would force MCU to finish with previous code/data access before continuing after the barrier.

However I’ve only needed to use barriers once and it was required for dynamic code loading, not sure if QSPI mode switching would require it or not.

1 Like