On a STM32F767 (216MHz PLL clock, overdrive), I've been experiencing some weird crashes (but not random) depending on various gcc version or
optimization or code load address (Flash AXIM or ITCM). Until I figured out this change in os/hal/ports/STM32/STM32F7xx/hal_lld.c:
diff --git os/hal/ports/STM32/STM32F7xx/hal_lld.c os/hal/ports/STM32/STM32F7xx/hal_lld.c
index 53398d411..f6ced1d84 100644
--- os/hal/ports/STM32/STM32F7xx/hal_lld.c
+++ os/hal/ports/STM32/STM32F7xx/hal_lld.c
@@ -288,6 +288,8 @@ void stm32_clock_init(void) {
/* Flash setup.*/
FLASH->ACR = FLASH_ACR_ARTEN | FLASH_ACR_PRFTEN | STM32_FLASHBITS;
+ while ((FLASH->ACR & FLASH_ACR_LATENCY) != STM32_FLASHBITS)
+ ;
/* Switching to the configured clock source if it is different from HSI.*/
#if (STM32_SW != STM32_SW_HSI)
This adds a check (and more importantly a wait) after altering the flash wait states settings.
Otherwise, the crashing code would fault right when returning from the stm32_clock_init() function (basically when gcc generates a pop {...,pc}. That's why, depending on the gcc version/optimization, it was working sometimes (the pop is not always generated in the code).
I think this makes sense considering the programming manual: (I'm quoting section 3.7 Flash registers of the RM0410 Reference manual):
> Increasing the CPU frequency
> 1. Program the new number of wait states to the LATENCY bits in the FLASH_ACR
> register
> 2. Check that the new number of wait states is taken into account to access the Flash
> memory by reading the FLASH_ACR register
> 3. Modify the CPU clock source by writing the SW bits in the RCC_CFGR register
Step 2. was missing.
What do you think about this change? I'm not sure about other STM32 devices, but probably other chips might benefit of the change as well.