Page 1 of 1

Issue in STM32 stm32_clock_init with flash wait states

Posted: Tue Jun 18, 2019 1:47 pm
by tho
Hi,

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.

Re: Issue in STM32 stm32_clock_init with flash wait states

Posted: Tue Jun 18, 2019 1:50 pm
by Giovanni
Hi,

Thanks for the patch, this is definitely a bug and also other platforms should be checked.

Moving this topic in "bug reports".

Giovanni

Re: Issue in STM32 stm32_clock_init with flash wait states

Posted: Tue Jun 18, 2019 2:37 pm
by tho
Thanks!

The manual I was quoting applies for sure to STM32F76xxx and STM32F77xxx.
I also just checked in RM0090 for STM32F405/415, STM32F407/417, STM32F427/437 and STM32F429/439, and there is exactly the same paragraph.

I guess it applies to all STM32, but anyway the patch does not hurt if the delay it not required.

Re: Issue in STM32 stm32_clock_init with flash wait states

Posted: Sun Jun 30, 2019 8:16 am
by Giovanni
Hi,

Fixed as bug #1035.

Giovanni