From 58355cfe3ebfdd1975ce4c076a8601f81d0b7357 Mon Sep 17 00:00:00 2001 From: Jiu-xiao <2592509183@qq.com> Date: Mon, 16 Nov 2026 01:25:25 +0000 Subject: [PATCH 1/4] fix(stm32): H7 Flash reads return 0 for a word with an ECC double error On H7 a flash word whose program or erase was cut by a reset or a power loss fails its ECC check, and reading it raises a bus error. STM32Flash read through the plain copy of the base class, so the first read of such a word ended in the fault handler, on every boot. STM32Flash::Read now reads flash word by flash word. For each word it masks all interrupts (FAULTMASK), sets CCR.BFHFNMIGN so that the bus error raises no exception, and tests DBECCERR afterwards. A word with the flag set is filled with 0 in the buffer, and Read returns ErrorCode::OK. With the bus error ignored the load does not deliver the contents of the word but what earlier loads left behind; right after a read of blank flash that is mostly 0xFFFFFFFF, which a reader takes for erased flash. Zeros are neither erased flash nor complete data, so DatabaseRaw and DatabaseRawSequential handle the word as the half-written unit it is, with their existing power-loss logic. A double error caused by real damage reads the same and is not told apart. The comparison before programming in Write reads the same way and returns ErrorCode::CHECK_ERR without programming when the target word cannot be read; the word can be written again after an erase. The ECC flags stay set once raised, and the HAL takes a flag that is still set for a failed program or erase: after one read of a word with a corrected single error, the next HAL_FLASH_Program returned HAL_ERROR without programming. The driver clears SNECCERR and DBECCERR after each flash word it reads and before each erase or program. Other families keep the plain copy. --- driver/st/stm32_flash.cpp | 116 ++++++++++++++++++++++++++++++++++++++ driver/st/stm32_flash.hpp | 32 +++++++++++ 2 files changed, 148 insertions(+) diff --git a/driver/st/stm32_flash.cpp b/driver/st/stm32_flash.cpp index 55137e268..34bd1aff8 100644 --- a/driver/st/stm32_flash.cpp +++ b/driver/st/stm32_flash.cpp @@ -6,6 +6,82 @@ using namespace LibXR; namespace { +#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR) +/** + * @brief 清除 ECC 错误标志 / Clear the ECC error flags + * @note 读到单位错误(已纠正)或双位错误的 Flash 字都会置位,直到软件清除。HAL 在编程和 + * 擦除前后把仍然置位的 ECC 标志当作操作失败,所以读完和擦写前都要清掉。 + * Reading a flash word with a single error (corrected) or a double error sets a + * flag that stays until software clears it. The HAL takes an ECC flag that is + * still set before or after a program or erase for a failed operation, so the + * flags are cleared after a read and before an erase or program. + */ +void ClearEccFlags() +{ + FLASH->CCR1 = FLASH_CCR_CLR_SNECCERR | FLASH_CCR_CLR_DBECCERR; +#if defined(DUAL_BANK) + FLASH->CCR2 = FLASH_CCR_CLR_SNECCERR | FLASH_CCR_CLR_DBECCERR; +#endif +} + +/** @brief 是否有双位 ECC 错误标志 / Whether a double ECC error flag is set */ +bool HasEccDoubleError() +{ +#if defined(DUAL_BANK) + return ((FLASH->SR1 | FLASH->SR2) & FLASH_SR_DBECCERR) != 0U; +#else + return (FLASH->SR1 & FLASH_SR_DBECCERR) != 0U; +#endif +} + +/** + * @brief 读取落在同一个 Flash 字内的若干字节 / Read bytes that lie inside one flash word + * @param dst 目标缓冲区 / Destination buffer + * @param address Flash 地址 / Flash address + * @param size 字节数 / Byte count + * @return 该字读不出来(双位 ECC 错误)时返回 false,`dst` 的内容无意义 + * Returns false when the word cannot be read (double ECC error); `dst` then + * holds no meaningful data + * @note 执行优先级为 -1(FAULTMASK)且 CCR.BFHFNMIGN 置位时,读操作的总线错误不产生 + * 异常;这时读到的不是该字的内容,而是之前读操作留下的值,所以由 DBECCERR 判断。 + * At execution priority -1 (FAULTMASK) with CCR.BFHFNMIGN set, a bus error on a + * load raises no exception; the load then delivers what earlier loads left behind, + * not the contents of the word, so DBECCERR decides. + */ +bool ReadFlashWord(uint8_t* dst, uint32_t address, size_t size) +{ + const uint32_t faultmask = __get_FAULTMASK(); + __set_FAULTMASK(1U); + const uint32_t ccr = SCB->CCR; + SCB->CCR = ccr | SCB_CCR_BFHFNMIGN_Msk; + __DSB(); + __ISB(); + ClearEccFlags(); + Memory::FastCopy(dst, reinterpret_cast(address), size); + __DSB(); + __ISB(); + const bool failed = HasEccDoubleError(); + ClearEccFlags(); + if (failed) + { + SCB->CFSR = SCB_CFSR_BUSFAULTSR_Msk; + SCB->SHCSR &= ~SCB_SHCSR_BUSFAULTPENDED_Msk; +#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + // 不让出错的这次读取留在数据缓存里。 + // Keep the failed read out of the data cache. + SCB_InvalidateDCache_by_Addr( + reinterpret_cast(address & ~(STM32FlashMinWriteSize() - 1U)), + static_cast(STM32FlashMinWriteSize())); +#endif + } + SCB->CCR = ccr; + __DSB(); + __ISB(); + __set_FAULTMASK(faultmask); + return !failed; +} +#endif + /** @brief Flash 擦写期间的缓存状态与写锁管理 / Cache state and write lock for Flash * operations. */ class FlashOperationGuard @@ -45,6 +121,9 @@ class FlashOperationGuard if (d_cache_enabled_) SCB_DisableDCache(); #endif HAL_FLASH_Unlock(); +#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR) + ClearEccFlags(); +#endif } ~FlashOperationGuard() @@ -252,12 +331,25 @@ ErrorCode STM32Flash::Write(size_t offset, ConstRawData data) Memory::FastSet(flash_word_buffer, 0xFF, sizeof(flash_word_buffer)); Memory::FastCopy(flash_word_buffer, src + written, chunk_size); +#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR) + uint8_t current[MIN_WRITE_SIZE]; + if (!ReadFlashWord(current, addr + written, chunk_size)) + { + return ErrorCode::CHECK_ERR; + } + if (Memory::FastCmp(current, src + written, chunk_size) == 0) + { + written += chunk_size; + continue; + } +#else if (Memory::FastCmp(reinterpret_cast(addr + written), src + written, chunk_size) == 0) { written += chunk_size; continue; } +#endif if (HAL_FLASH_Program(program_type_, addr + written, reinterpret_cast(flash_word_buffer)) != HAL_OK) @@ -295,6 +387,30 @@ ErrorCode STM32Flash::Write(size_t offset, ConstRawData data) return ErrorCode::OK; } +#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR) +ErrorCode STM32Flash::Read(size_t offset, RawData data) +{ + ASSERT(offset + data.size_ <= Size()); + + auto* dst = static_cast(data.addr_); + const uint32_t begin = base_address_ + offset; + + for (size_t done = 0; done < data.size_;) + { + const uint32_t address = begin + done; + const size_t chunk = LibXR::min(MIN_WRITE_SIZE - (address % MIN_WRITE_SIZE), + data.size_ - done); + if (!ReadFlashWord(dst + done, address, chunk)) + { + Memory::FastSet(dst + done, 0, chunk); + } + done += chunk; + } + + return ErrorCode::OK; +} +#endif + bool STM32Flash::IsInRange(uint32_t addr, size_t size) const { const uint32_t BEGIN = base_address_; diff --git a/driver/st/stm32_flash.hpp b/driver/st/stm32_flash.hpp index fbcce5e2c..d547a5a5b 100644 --- a/driver/st/stm32_flash.hpp +++ b/driver/st/stm32_flash.hpp @@ -115,6 +115,14 @@ typename std::enable_if::value>::type SetBanks(T& init, uint32_t #endif +// H7:读到双位 ECC 错误的 Flash 字时产生总线错误,并置位 FLASH_SR 的 DBECCERR。 +// H7: reading a flash word with a double ECC error raises a bus error and sets DBECCERR +// in FLASH_SR. +#if defined(FLASH_SR_DBECCERR) && defined(FLASH_CCR_CLR_DBECCERR) && \ + defined(FLASH_CCR_CLR_SNECCERR) && defined(SCB_CCR_BFHFNMIGN_Msk) +#define LIBXR_STM32_FLASH_ECC_BUS_ERROR 1 +#endif + /** * @brief STM32 闪存驱动实现 / STM32 flash driver implementation * @pre 擦写调用及相关缓存控制由调用方串行化;等待期间 HAL tick 必须能推进。 @@ -133,6 +141,26 @@ typename std::enable_if::value>::type SetBanks(T& init, uint32_t * from the address; H5, H7 and the families with a Page field erase by the number within * the bank, F2/F4/F7 by the sector number across both banks. Bank swap (SWAP_BANK, BFB2 * and similar option bytes) is not supported. + * @note H7 上编程或擦除被掉电打断后,被打断的 Flash 字 ECC 校验不过。`Read` 按 Flash 字 + * 读取,读每个字时屏蔽全部中断并忽略总线错误,读完检查 DBECCERR;出错的字在缓冲区里填 0, + * `Read` 仍返回 `ErrorCode::OK`。读到的 0 既不是擦除态也不是完整数据,调用方按写了一半的 + * 内容处理;真实损坏造成的双位错误读起来相同,不作区分。`Write` 编程前的比较同样读取, + * 目标字读不出来时不编程,返回 `ErrorCode::CHECK_ERR`,擦除后才能再写。其他系列的 `Read` + * 是基类的直接拷贝。 + * On H7 a flash word whose program or erase was cut by a power loss fails its ECC check. + * `Read` reads flash word by flash word, masks all interrupts and ignores the bus error + * for each word, and tests DBECCERR afterwards; a failing word is filled with 0 in the + * buffer and `Read` still returns `ErrorCode::OK`. The zeros are neither erased flash nor + * complete data, so the caller handles them as half-written contents; a double error + * caused by real damage reads the same and is not told apart. The comparison before + * programming in `Write` reads the same way and returns `ErrorCode::CHECK_ERR` without + * programming when the target word cannot be read; the word can be written again after + * an erase. On other families `Read` is the plain copy of the base class. + * @note H7 的 ECC 标志(单位错误已纠正、双位错误)置位后一直保持,HAL 把它们当作编程或 + * 擦除失败。驱动在每次读完一个 Flash 字之后、每次擦写开始之前清除这两个标志。 + * The ECC flags of H7 (single error corrected, double error) stay set once raised, and + * the HAL takes them for a failed program or erase. The driver clears both after each + * flash word it reads and before each erase or program. */ class STM32Flash : public Flash { @@ -167,6 +195,10 @@ class STM32Flash : public Flash ErrorCode Write(size_t offset, ConstRawData data) override; +#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR) + ErrorCode Read(size_t offset, RawData data) override; +#endif + private: const FlashRegion* regions_; uint32_t base_address_; From e71a67025b3cb770c24693ee62c8e555ac018a97 Mon Sep 17 00:00:00 2001 From: Jiu-xiao <2592509183@qq.com> Date: Mon, 16 Nov 2026 01:25:25 +0000 Subject: [PATCH 2/4] test(database): power-cut cases with a cut unit that reads as 0 PowerCutFlash gains a third mode that models ECC Flash such as H7: the cut unit, or the whole page of a cut erase, cannot be read afterwards. Read fills it with 0 and returns OK as STM32Flash does, programming it returns CHECK_ERR, and a completed erase makes it readable again. RunPowerCutCases runs every cut in the three modes. DatabaseRaw and DatabaseRawSequential pass the new mode without a source change: no cut leads to a program of an unreadable unit, and none to a second program of a written unit. --- .../database/linux_database_test_common.hpp | 49 +++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/test/automatic/middleware/database/linux_database_test_common.hpp b/test/automatic/middleware/database/linux_database_test_common.hpp index ef466d14c..eff5a57fc 100644 --- a/test/automatic/middleware/database/linux_database_test_common.hpp +++ b/test/automatic/middleware/database/linux_database_test_common.hpp @@ -384,6 +384,12 @@ struct PowerCutShared size_t budget = std::numeric_limits::max(); /// 掉电落在下一次操作中间 / The cut lands inside the next operation bool torn = false; + /// 掉电落在下一次操作中间,被打断的单元(擦除时是整页)之后读不出来 + /// The cut lands inside the next operation and the cut unit (the whole page for an + /// erase) cannot be read afterwards + bool unreadable = false; + /// 读不出来的字节 / Bytes that cannot be read + std::array unreadable_bytes{}; /// 擦除被打断时每一位回到 1 的概率为 1/2^n;0 表示擦除不会被打断在中间 /// Each bit returns to 1 with probability 1/2^n when an erase is cut; 0 means an /// erase is never cut part-way @@ -418,6 +424,14 @@ struct PowerCutShared * some of its bits back to 1. * Programming a unit that is neither erased nor equal to the new content counts in * `violations`: ECC Flash cannot do it. + * + * `unreadable` 模拟带 ECC 的 Flash(如 H7):被打断的单元、被打断的擦除所在的整页之后 + * 读不出来,`Read` 像 STM32Flash 一样把这些字节填 0 并返回 `ErrorCode::OK`,对它们编程 + * 返回 `ErrorCode::CHECK_ERR`;擦除完成后恢复可读。 + * `unreadable` models ECC Flash such as H7: the cut unit, or the whole page of a cut + * erase, cannot be read afterwards; `Read` fills those bytes with 0 and returns + * `ErrorCode::OK` as STM32Flash does, programming them returns `ErrorCode::CHECK_ERR`, + * and a completed erase makes them readable again. */ class PowerCutFlash : public Flash { @@ -437,6 +451,10 @@ class PowerCutFlash : public Flash { if (shared_.operations == shared_.budget) { + if (shared_.unreadable) + { + std::memset(shared_.unreadable_bytes.data() + page, 1, MinEraseSize()); + } if (shared_.torn && shared_.torn_erase_rounds > 0) { // 只有少量位回到 1,块头或校验往往还读作有效。 @@ -460,11 +478,23 @@ class PowerCutFlash : public Flash _exit(0); } std::memset(shared_.image.data() + page, 0xFF, MinEraseSize()); + std::memset(shared_.unreadable_bytes.data() + page, 0, MinEraseSize()); shared_.operations++; } return ErrorCode::OK; } + ErrorCode Read(size_t offset, RawData data) override + { + TEST_ASSERT(offset + data.size_ <= shared_.image.size()); + auto* dst = static_cast(data.addr_); + for (size_t i = 0; i < data.size_; ++i) + { + dst[i] = shared_.unreadable_bytes[offset + i] != 0 ? 0 : shared_.image[offset + i]; + } + return ErrorCode::OK; + } + ErrorCode Write(size_t offset, ConstRawData data) override { const size_t unit = MinWriteSize(); @@ -474,13 +504,21 @@ class PowerCutFlash : public Flash for (size_t i = 0; i < data.size_; i += unit) { uint8_t* dst = shared_.image.data() + offset + i; + if (shared_.unreadable_bytes[offset + i] != 0) + { + return ErrorCode::CHECK_ERR; + } if (std::memcmp(dst, src + i, unit) == 0) { continue; } if (shared_.operations == shared_.budget) { - if (shared_.torn) + if (shared_.unreadable) + { + std::memset(shared_.unreadable_bytes.data() + offset + i, 1, unit); + } + if (shared_.torn || shared_.unreadable) { for (size_t j = 0; j < unit; ++j) { @@ -646,12 +684,17 @@ void RunPowerCutCases(OpenDatabase open, size_t min_erase_size, size_t min_write bool finished = false; for (size_t budget = 0; !finished; ++budget) { - for (bool torn : {false, true}) + // 0:操作之间掉电;1:操作被打断在中间;2:被打断的单元或页之后读不出来。 + // 0: cut between operations; 1: cut part-way through an operation; 2: the cut unit + // or page cannot be read afterwards. + for (int mode : {0, 1, 2}) { shared->image.fill(0xFF); + shared->unreadable_bytes.fill(0); shared->operations = 0; shared->budget = budget; - shared->torn = torn; + shared->torn = mode == 1; + shared->unreadable = mode == 2; shared->torn_erase_rounds = torn_erase_rounds; shared->violations = 0; shared->step = -1; From 59dbe3b39fdc9dc5fef333de6c31d68291c61cf3 Mon Sep 17 00:00:00 2001 From: Jiu-xiao <2592509183@qq.com> Date: Mon, 16 Nov 2026 02:35:57 +0000 Subject: [PATCH 3/4] fix(stm32): libxr_stm32_flash_ecc_nmi() for the families that raise an NMI On G0, G4, L4, L5, WB, WL, U0, U5, WBA, H5 and U3 a Flash unit whose program or erase was cut by a power loss raises an NMI when it is read. The NMI cannot be masked, and the NMI_Handler CubeMX generates is an endless loop, so a database that reads such a unit at start-up stops there on every boot. libxr_stm32_flash_ecc_nmi() (stm32_flash_nmi.h, callable from C) clears the double error flag and the single error flag and returns true when the double error flag was set; NMI_Handler calls it in its user code section and returns on true. The interrupted read then goes on and delivers the half-written contents of the unit, which DatabaseRaw and DatabaseRawSequential handle with their existing power-loss logic. The single error flag is cleared as well because a later double error raises no NMI while it is set. On H5 the instruction cache is invalidated, as its reference manual asks. Three register layouts are recognised by their CMSIS names (one ECCR, with ECCD2/ECCC2 and ECC2R where they exist; H5; U3); with any other device header the function returns false. Measured on an STM32G431: one double word is busy for 85.9 us. A cut between about 17 us and 41.9 us leaves the low 36 bits written and the high 28 bits blank; about half of these cells raise the NMI, the others only set the single error flag. With the handler returning, the load delivers that content and never reads as blank. The written flag of DatabaseRaw was either unwritten or complete in 96 of 96 cuts. A page erase cut at 10 % of its time or later reads blank without a flag. --- driver/st/stm32_flash.hpp | 7 +++++ driver/st/stm32_flash_nmi.c | 60 +++++++++++++++++++++++++++++++++++++ driver/st/stm32_flash_nmi.h | 53 ++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 driver/st/stm32_flash_nmi.c create mode 100644 driver/st/stm32_flash_nmi.h diff --git a/driver/st/stm32_flash.hpp b/driver/st/stm32_flash.hpp index d547a5a5b..de66f8c9f 100644 --- a/driver/st/stm32_flash.hpp +++ b/driver/st/stm32_flash.hpp @@ -161,6 +161,13 @@ typename std::enable_if::value>::type SetBanks(T& init, uint32_t * The ECC flags of H7 (single error corrected, double error) stay set once raised, and * the HAL takes them for a failed program or erase. The driver clears both after each * flash word it reads and before each erase or program. + * @note G0、G4、L4、L5、WB、WL、U0、U5、WBA、H5、U3 读到这样的单元时产生 NMI,读到的是 + * 写了一半的内容;`NMI_Handler` 需要调用 `libxr_stm32_flash_ecc_nmi()` + * (stm32_flash_nmi.h),否则停在 CubeMX 生成的死循环里。 + * On G0, G4, L4, L5, WB, WL, U0, U5, WBA, H5 and U3 reading such a unit raises an NMI and + * delivers the half-written contents; `NMI_Handler` has to call + * `libxr_stm32_flash_ecc_nmi()` (stm32_flash_nmi.h), otherwise it stays in the endless + * loop CubeMX generates. */ class STM32Flash : public Flash { diff --git a/driver/st/stm32_flash_nmi.c b/driver/st/stm32_flash_nmi.c new file mode 100644 index 000000000..a81a6d9e9 --- /dev/null +++ b/driver/st/stm32_flash_nmi.c @@ -0,0 +1,60 @@ +#include "stm32_flash_nmi.h" + +#include "main.h" + +bool libxr_stm32_flash_ecc_nmi(void) +{ +#if defined(FLASH_ECCR_OTP_ECC) && defined(FLASH_ECCR_ECCD) && defined(FLASH_ECCR_ECCC) + /* H5:检测寄存器和纠正寄存器分开,位名沿用 FLASH_ECCR_。 + * H5: separate detection and correction registers; the bit names keep FLASH_ECCR_. */ + if ((FLASH->ECCDETR & FLASH_ECCR_ECCD) == 0U) + { + return false; + } + FLASH->ECCDETR |= FLASH_ECCR_ECCD; + FLASH->ECCCORR |= FLASH_ECCR_ECCC; +#if defined(ICACHE) && defined(ICACHE_CR_CACHEINV) + ICACHE->CR |= ICACHE_CR_CACHEINV; +#endif + return true; +#elif defined(FLASH_ECCDR_ECCD) && defined(FLASH_ECCCR_ECCC) + /* U3:检测寄存器 ECCDR,纠正寄存器 ECCCR。 + * U3: detection register ECCDR, correction register ECCCR. */ + if ((FLASH->ECCDR & FLASH_ECCDR_ECCD) == 0U) + { + return false; + } + FLASH->ECCDR |= FLASH_ECCDR_ECCD; + FLASH->ECCCR |= FLASH_ECCCR_ECCC; + return true; +#elif defined(FLASH_ECCR_ECCD) && defined(FLASH_ECCR_ECCC) + /* G0、G4、L4、L5、WB、WL、U0、U5、WBA:两个标志在同一个 ECCR 里,写 1 清除;部分型号 + * 另有 128 位读取高半部分的标志(ECCD2/ECCC2)或第二个 bank 的寄存器(ECC2R)。 + * G0, G4, L4, L5, WB, WL, U0, U5, WBA: both flags are in one ECCR and are cleared by + * writing 1; some parts add the flags of the upper half of a 128-bit read (ECCD2/ECCC2) + * or a register for the second bank (ECC2R). */ + bool handled = false; +#if defined(FLASH_ECCR_ECCD2) && defined(FLASH_ECCR_ECCC2) + const uint32_t detected = FLASH_ECCR_ECCD | FLASH_ECCR_ECCD2; + const uint32_t flags = detected | FLASH_ECCR_ECCC | FLASH_ECCR_ECCC2; +#else + const uint32_t detected = FLASH_ECCR_ECCD; + const uint32_t flags = detected | FLASH_ECCR_ECCC; +#endif + if ((FLASH->ECCR & detected) != 0U) + { + FLASH->ECCR |= flags; + handled = true; + } +#if defined(FLASH_ECC2R_ECCD) && defined(FLASH_ECC2R_ECCC) + if ((FLASH->ECC2R & FLASH_ECC2R_ECCD) != 0U) + { + FLASH->ECC2R |= FLASH_ECC2R_ECCD | FLASH_ECC2R_ECCC; + handled = true; + } +#endif + return handled; +#else + return false; +#endif +} diff --git a/driver/st/stm32_flash_nmi.h b/driver/st/stm32_flash_nmi.h new file mode 100644 index 000000000..45276b47d --- /dev/null +++ b/driver/st/stm32_flash_nmi.h @@ -0,0 +1,53 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * @brief 在 NMI 处理函数中处理 Flash 的双位 ECC 错误 + * Handle the Flash double ECC error in the NMI handler. + * @return 双位 ECC 错误标志已置位并已清除时返回 `true`,NMI 来自其他原因时返回 + * `false` + * `true` when the double ECC error flag was set and has been cleared, + * `false` when the NMI has another cause. + * @note 编程或擦除被掉电打断的单元 ECC 校验不过。G0、G4、L4、L5、WB、WL、U0、U5、 + * WBA、H5、U3 读到这样的单元时产生 NMI,NMI 不可屏蔽,而 CubeMX 生成的 + * `NMI_Handler` 是死循环,于是每次启动都停在里面。在它的用户代码区调用本函数: + * A unit whose program or erase was cut by a power loss fails its ECC check. + * On G0, G4, L4, L5, WB, WL, U0, U5, WBA, H5 and U3 reading such a unit + * raises an NMI, which cannot be masked, and the `NMI_Handler` CubeMX + * generates is an endless loop, so every start ends there. Call this + * function in its user code section: + * @code + * void NMI_Handler(void) + * { + * // USER CODE BEGIN NonMaskableInt_IRQn 0 + * if (libxr_stm32_flash_ecc_nmi()) + * { + * return; + * } + * // USER CODE END NonMaskableInt_IRQn 0 + * ... + * } + * @endcode + * @note 返回 `true` 后被打断的读操作继续执行,读到的是该单元写了一半的内容,由调用方 + * (如 `DatabaseRaw`)按未完成的写入处理;真实损坏造成的双位错误同样返回, + * 不作区分。单位错误标志一并清除:它置位期间,后续的双位错误不再产生 NMI。 + * H5 上同时使指令缓存失效。没有这种 NMI 的系列上本函数恒返回 `false`。 + * After `true` the interrupted read goes on and delivers the half-written + * contents of the unit, which the caller (`DatabaseRaw`, for example) + * handles as an unfinished write; a double error caused by real damage + * returns the same way and is not told apart. The single error flag is + * cleared as well: while it is set, a later double error raises no NMI. On + * H5 the instruction cache is invalidated too. On families without this NMI + * the function always returns `false`. + */ + bool libxr_stm32_flash_ecc_nmi(void); + +#ifdef __cplusplus +} +#endif From 261b09a35b46cc8b3691fcb4cba2af4b9d51d19d Mon Sep 17 00:00:00 2001 From: Jiu-xiao <2592509183@qq.com> Date: Mon, 16 Nov 2026 02:52:42 +0000 Subject: [PATCH 4/4] fix(stm32): H7R/S Flash programs whole flash words and its ECC read is covered The H7R/S HAL offers byte, half-word, word, double-word and quad-word programming. STM32Flash took the smallest type a HAL defines, so on H7R/S MIN_WRITE_SIZE was 1 and every byte was a forced write of the whole 128-bit flash word with its ECC; a second byte into the same flash word writes a word that is not blank, which RM0477 says can leave an inconsistent ECC. Write also sized its buffer as MIN_WRITE_SIZE / 4 words, zero here, and copied one byte into it. When a HAL defines both the byte and the quad-word type, the driver now uses the quad-word: MIN_WRITE_SIZE is 16 and the program type is FLASH_TYPEPROGRAM_QUADWORD. Only the H7R/S HAL defines both. H7R/S reports a double ECC error of the user flash with a bus error like H7 (RM0477), but its flags are SNECCERRF and DBECCERRF in FLASH_ISR, cleared through FLASH_ICR, so the H7 path did not recognise it and Read stayed the plain copy. LIBXR_STM32_FLASH_ECC_BUS_ERROR is now also defined for these names, and the two flag helpers use FLASH_ISR and FLASH_ICR there. Read, the comparison in Write and the read of one flash word are the same code as on H7. Compiled against the H7S3, H7R3, H7S7 and H7R7 headers; not run on hardware. --- driver/st/stm32_flash.cpp | 8 ++++++- driver/st/stm32_flash.hpp | 49 ++++++++++++++++++++++++++------------- 2 files changed, 40 insertions(+), 17 deletions(-) diff --git a/driver/st/stm32_flash.cpp b/driver/st/stm32_flash.cpp index 34bd1aff8..30495b343 100644 --- a/driver/st/stm32_flash.cpp +++ b/driver/st/stm32_flash.cpp @@ -18,16 +18,22 @@ namespace */ void ClearEccFlags() { +#if defined(FLASH_ICR_DBECCERRF) + FLASH->ICR = FLASH_ICR_SNECCERRF | FLASH_ICR_DBECCERRF; +#else FLASH->CCR1 = FLASH_CCR_CLR_SNECCERR | FLASH_CCR_CLR_DBECCERR; #if defined(DUAL_BANK) FLASH->CCR2 = FLASH_CCR_CLR_SNECCERR | FLASH_CCR_CLR_DBECCERR; #endif +#endif } /** @brief 是否有双位 ECC 错误标志 / Whether a double ECC error flag is set */ bool HasEccDoubleError() { -#if defined(DUAL_BANK) +#if defined(FLASH_ISR_DBECCERRF) + return (FLASH->ISR & FLASH_ISR_DBECCERRF) != 0U; +#elif defined(DUAL_BANK) return ((FLASH->SR1 | FLASH->SR2) & FLASH_SR_DBECCERR) != 0U; #else return (FLASH->SR1 & FLASH_SR_DBECCERR) != 0U; diff --git a/driver/st/stm32_flash.hpp b/driver/st/stm32_flash.hpp index de66f8c9f..691ef33f3 100644 --- a/driver/st/stm32_flash.hpp +++ b/driver/st/stm32_flash.hpp @@ -43,7 +43,14 @@ inline uint32_t STM32FlashBankOf(uint32_t) { return 1; } // NOLINTNEXTLINE constexpr size_t STM32FlashMinWriteSize() { -#ifdef FLASH_TYPEPROGRAM_BYTE +#if defined(FLASH_TYPEPROGRAM_BYTE) && defined(FLASH_TYPEPROGRAM_QUADWORD) + // H7R/S:小于四字的编程类型是对整个 128 位 Flash 字的强制写入,而一个 Flash 字连同 + // ECC 只能写一次,所以按四字编程。 + // H7R/S: the program types smaller than a quad-word are forced writes of the whole + // 128-bit flash word, and a flash word with its ECC can be written only once, so the + // driver programs quad-words. + return 16; +#elif defined(FLASH_TYPEPROGRAM_BYTE) return 1; #elif defined(FLASH_TYPEPROGRAM_HALFWORD) return 2; @@ -116,10 +123,15 @@ typename std::enable_if::value>::type SetBanks(T& init, uint32_t #endif // H7:读到双位 ECC 错误的 Flash 字时产生总线错误,并置位 FLASH_SR 的 DBECCERR。 +// H7R/S 相同,标志是 FLASH_ISR 的 DBECCERRF,由 FLASH_ICR 清除。 // H7: reading a flash word with a double ECC error raises a bus error and sets DBECCERR -// in FLASH_SR. -#if defined(FLASH_SR_DBECCERR) && defined(FLASH_CCR_CLR_DBECCERR) && \ - defined(FLASH_CCR_CLR_SNECCERR) && defined(SCB_CCR_BFHFNMIGN_Msk) +// in FLASH_SR. H7R/S does the same; its flag is DBECCERRF in FLASH_ISR, cleared through +// FLASH_ICR. +#if defined(SCB_CCR_BFHFNMIGN_Msk) && \ + ((defined(FLASH_SR_DBECCERR) && defined(FLASH_CCR_CLR_DBECCERR) && \ + defined(FLASH_CCR_CLR_SNECCERR)) || \ + (defined(FLASH_ISR_DBECCERRF) && defined(FLASH_ICR_DBECCERRF) && \ + defined(FLASH_ICR_SNECCERRF))) #define LIBXR_STM32_FLASH_ECC_BUS_ERROR 1 #endif @@ -141,26 +153,29 @@ typename std::enable_if::value>::type SetBanks(T& init, uint32_t * from the address; H5, H7 and the families with a Page field erase by the number within * the bank, F2/F4/F7 by the sector number across both banks. Bank swap (SWAP_BANK, BFB2 * and similar option bytes) is not supported. - * @note H7 上编程或擦除被掉电打断后,被打断的 Flash 字 ECC 校验不过。`Read` 按 Flash 字 - * 读取,读每个字时屏蔽全部中断并忽略总线错误,读完检查 DBECCERR;出错的字在缓冲区里填 0, + * @note H7 和 H7R/S 上编程或擦除被掉电打断后,被打断的 Flash 字 ECC 校验不过。`Read` 按 + * Flash 字读取,读每个字时屏蔽全部中断并忽略总线错误,读完检查双位错误标志(H7 的 + * DBECCERR,H7R/S 的 DBECCERRF);出错的字在缓冲区里填 0, * `Read` 仍返回 `ErrorCode::OK`。读到的 0 既不是擦除态也不是完整数据,调用方按写了一半的 * 内容处理;真实损坏造成的双位错误读起来相同,不作区分。`Write` 编程前的比较同样读取, * 目标字读不出来时不编程,返回 `ErrorCode::CHECK_ERR`,擦除后才能再写。其他系列的 `Read` * 是基类的直接拷贝。 - * On H7 a flash word whose program or erase was cut by a power loss fails its ECC check. - * `Read` reads flash word by flash word, masks all interrupts and ignores the bus error - * for each word, and tests DBECCERR afterwards; a failing word is filled with 0 in the - * buffer and `Read` still returns `ErrorCode::OK`. The zeros are neither erased flash nor + * On H7 and H7R/S a flash word whose program or erase was cut by a power loss fails its + * ECC check. `Read` reads flash word by flash word, masks all interrupts and ignores the + * bus error for each word, and tests the double error flag afterwards (DBECCERR on H7, + * DBECCERRF on H7R/S); a failing word is filled with 0 in the buffer and `Read` still + * returns `ErrorCode::OK`. The zeros are neither erased flash nor * complete data, so the caller handles them as half-written contents; a double error * caused by real damage reads the same and is not told apart. The comparison before * programming in `Write` reads the same way and returns `ErrorCode::CHECK_ERR` without * programming when the target word cannot be read; the word can be written again after * an erase. On other families `Read` is the plain copy of the base class. - * @note H7 的 ECC 标志(单位错误已纠正、双位错误)置位后一直保持,HAL 把它们当作编程或 - * 擦除失败。驱动在每次读完一个 Flash 字之后、每次擦写开始之前清除这两个标志。 - * The ECC flags of H7 (single error corrected, double error) stay set once raised, and - * the HAL takes them for a failed program or erase. The driver clears both after each - * flash word it reads and before each erase or program. + * @note 这两个系列的 ECC 标志(单位错误已纠正、双位错误)置位后一直保持,H7 的 HAL 把 + * 它们当作编程或擦除失败。驱动在每次读完一个 Flash 字之后、每次擦写开始之前清除这两个 + * 标志。 + * The ECC flags of both families (single error corrected, double error) stay set once + * raised, and the H7 HAL takes them for a failed program or erase. The driver clears both + * after each flash word it reads and before each erase or program. * @note G0、G4、L4、L5、WB、WL、U0、U5、WBA、H5、U3 读到这样的单元时产生 NMI,读到的是 * 写了一半的内容;`NMI_Handler` 需要调用 `libxr_stm32_flash_ecc_nmi()` * (stm32_flash_nmi.h),否则停在 CubeMX 生成的死循环里。 @@ -214,7 +229,9 @@ class STM32Flash : public Flash static constexpr uint32_t DetermineProgramType() { -#ifdef FLASH_TYPEPROGRAM_BYTE +#if defined(FLASH_TYPEPROGRAM_BYTE) && defined(FLASH_TYPEPROGRAM_QUADWORD) + return FLASH_TYPEPROGRAM_QUADWORD; +#elif defined(FLASH_TYPEPROGRAM_BYTE) return FLASH_TYPEPROGRAM_BYTE; #elif defined(FLASH_TYPEPROGRAM_HALFWORD) return FLASH_TYPEPROGRAM_HALFWORD;