From 93ee866f72cb81b0630bc0ba02eda0f81f754c2d Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 16 Oct 2026 15:14:40 +0100 Subject: [PATCH] stm32u5: accept secure alias addresses in hal_flash_write/erase With TZEN=1 the PKCS#11 keyvault sits at its secure alias (_flash_keyvault is 0x0C040000 with stm32u5-wolfcrypt-tz.config), and pkcs11_store.c passes those addresses to hal_flash_erase() and hal_flash_write(). Both only accepted 0x08000000 to FLASH_TOP and returned 0 for anything else, so every vault commit was silently dropped and C_InitToken failed with CKR_FUNCTION_FAILED. Map a secure alias address to its 0x08 address first, as stm32h5.c does. --- hal/stm32u5.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/hal/stm32u5.c b/hal/stm32u5.c index c67e85ba5b..845ffffce2 100644 --- a/hal/stm32u5.c +++ b/hal/stm32u5.c @@ -62,6 +62,17 @@ void RAMFUNCTION hal_flash_clear_errors(uint8_t bank) } +#if (TZ_SECURE()) +/* Map a secure alias address (0x0C...) to the 0x08... address the bank + * checks below expect. Both aliases name the same flash page. */ +static uint32_t RAMFUNCTION flash_addr_unalias(uint32_t address) +{ + if ((address & FLASH_SECURE_MMAP_BASE) == FLASH_SECURE_MMAP_BASE) + address = (address & ~FLASH_SECURE_MMAP_BASE) | FLASHMEM_ADDRESS_SPACE; + return address; +} +#endif + int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) { int i = 0; @@ -71,6 +82,9 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len) volatile uint32_t *sr, *cr; hal_flash_clear_errors(0); +#if (TZ_SECURE()) + address = flash_addr_unalias(address); +#endif dst = (uint32_t*)address; #if (TZ_SECURE()) @@ -199,6 +213,9 @@ int RAMFUNCTION hal_flash_erase(uint32_t address, int len) hal_flash_clear_errors(0); if (len == 0) return -1; +#if (TZ_SECURE()) + address = flash_addr_unalias(address); +#endif if (address < ARCH_FLASH_OFFSET) return -1;