STM32F7 CPU_ENABLE_Cache SCB_EnableDCache() corrupts stack?
Working on a bootloader on the STM32F745 and starting from example code there was the function call CPU_CACHE_Enable.
In the original examples, this is called right at the start of main(). I had moved this function call later as I (thought) I wanted to selectively jump to the application first.
I spent a lengthy debug session a few days back trying to understand why a variable in main() was becoming corrupted.
Over-simplified example.
extern int a;
main (void)
{
if (a == 1) { <...this code runs....> }
CPU_CACHE_Enable();
if (a == 1) { <...this code DOES NOT run...> }
}What I found was that the compiler was storing the address of the variable in R4 and assuming the R4 would be preserved across the function call, as per the ARM spec.
On entry to CPU_CACHE_Enable, R4 is pushed to the stack. However, the inline code SCB_EnableDCache is executed which invalidates and enables the cache. This stomps on the location where R4 got pushed. On exit, CPU_CACHE_Enable pops R4 back again, but it is garbage and the subsequent use of R4 as an address pointer returns the wrong data.
Maybe there is some, but I haven't seen any notes in the documentation to warn developers of this possibility. I have worked around it by enabling the cache in my startup code instead and adding a comment about the stack corruption.
Is this expected behaviour or am I doing something wrong? If this is normal, then could I suggest that warning comments be added to help others avoid my mistake.
James