From b75b93fd3239696e889bf78511551051be7cc032 Mon Sep 17 00:00:00 2001 From: jsanchez-2g Date: Thu, 3 Sep 2026 09:22:11 -0500 Subject: [PATCH] stm32g0: Fix erase bank selection after bank swap The flash page number follows the logical memory mapping, but BKER selects a physical flash bank. Account for the nSWAP_BANK option when selecting BKER so erasing a logical address targets the corresponding physical bank after a swap. Assisted-by: OpenAI Codex Signed-off-by: jsanchez-2g --- arch/arm/src/common/stm32/stm32_flash_m0_g0c0.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/arch/arm/src/common/stm32/stm32_flash_m0_g0c0.c b/arch/arm/src/common/stm32/stm32_flash_m0_g0c0.c index ec3a06037fb..7b4d5e1e5e9 100644 --- a/arch/arm/src/common/stm32/stm32_flash_m0_g0c0.c +++ b/arch/arm/src/common/stm32/stm32_flash_m0_g0c0.c @@ -373,6 +373,7 @@ static void flash_lock_cr(void) static bool flash_unlock_opt(void) { bool was_locked = false; + flash_unlock_cr(); if (getreg32(STM32_FLASH_CR) & FLASH_CR_OPTLOCK) @@ -688,6 +689,9 @@ ssize_t up_progmem_eraseblock(size_t block) { int ret; size_t block_address; +#ifdef FLASH_DUAL_BANK + bool bank2; +#endif ret = flash_verify_blocknum(block); if (ret < 0) @@ -729,7 +733,17 @@ ssize_t up_progmem_eraseblock(size_t block) * match the correct bank. */ - if (block >= flash_bank2_priv.stblock) + /* BKER selects a physical bank, while block numbers follow the memory map. + * Reverse the bank selection when the banks are swapped in the memory map. + */ + + bank2 = block >= flash_bank2_priv.stblock; + if ((getreg32(STM32_FLASH_OPTR) & FLASH_OPTR_NSWAP_BANK) == 0) + { + bank2 = !bank2; + } + + if (bank2) { modifyreg32(STM32_FLASH_CR, 0, FLASH_CR_BKER); }