Skip to content

fix(stm32): a flash unit cut by a power loss no longer stops every boot - #365

Merged
Jiu-xiao merged 4 commits into
devfrom
fix/h7-flash-ecc-read
Nov 16, 2026
Merged

Jiu-xiao merged 4 commits into
devfrom
fix/h7-flash-ecc-read

Conversation

@Jiu-xiao

@Jiu-xiao Jiu-xiao commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

On STM32 families whose flash has ECC, a unit whose program or erase was cut by a reset or a power loss fails its ECC check. Reading it raises a bus error on H7 and H7R/S and an NMI on G0, G4, L4, L5, WB, WL, U0, U5, WBA, H5 and U3. DatabaseRaw reads the cut unit on every start, so the firmware ended in a fault handler on every boot until the flash was erased from outside.

This pull request makes the read survive on both groups. The two databases then take the unit for the half-written unit it is and recover with their existing power-loss logic; their sources and the Flash interface are not changed.

Group What the driver does What the reader gets
H7, H7R/S (bus error) STM32Flash::Read ignores the bus error for one flash word and tests the double error flag zeros for that word
G0, G4, L4, L5, WB, WL, U0, U5, WBA, H5, U3 (NMI) libxr_stm32_flash_ecc_nmi(), called from NMI_Handler, clears the flags and returns the half-written contents of the unit

H7 and H7R/S

What a cut leaves

Measured on an STM32H723 board (MC02) with a bare-metal bench that starts a program or an erase from RAM and issues a system reset after a chosen delay:

  • One flash word (32 bytes) takes 107 us to program. A cut between 7.6 us and 73.4 us leaves a word that raises a bus error on every read, with DBECCERR set (299 of 458 cuts in the sweep); earlier cuts read as blank, later ones as the complete data.
  • A sector erase cut in the middle of the erase phase leaves all 4096 flash words of the sector in that state.
  • With the bus error ignored, the load does not deliver the contents of the word. Read right after a blank word, 7 of the 8 words of a cut unit read as 0xFFFFFFFF in 52 of 52 cut units. A reader that looks only at the data takes the unit for erased flash.

Change (STM32Flash, selected by FLASH_SR_DBECCERR or FLASH_ISR_DBECCERRF, and SCB_CCR_BFHFNMIGN_Msk)

  • Read is overridden and 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. Read returns ErrorCode::OK, as before.
  • 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.
  • SNECCERR and DBECCERR are cleared after each flash word that is read and before each erase or program. This is a separate defect that the hardware test exposed and that dev has without this change: the flags stay set once raised, and the H7 HAL takes a flag that is still set for a failed operation. After one read of a word with a corrected single error, the next HAL_FLASH_Program returned HAL_ERROR (pFlash.ErrorCode = 0x02000000) without programming, and the database stopped in REQUIRE.
  • H7R/S runs the same code with DBECCERRF and SNECCERRF in FLASH_ISR, cleared through FLASH_ICR. Its flash word is 128 bits with one ECC code (RM0477). Its HAL does not test the ECC flags after an operation, so the clearing changes nothing for it.
  • H7R/S write unit, a defect of dev found while adding the above: its HAL offers byte, half-word, word, double-word and quad-word programming, and STM32Flash took the smallest type a HAL defines. MIN_WRITE_SIZE was therefore 1, 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), and Write copied one byte into a buffer of MIN_WRITE_SIZE / 4 = 0 words. 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. Of the 19 ST HALs checked only H7R/S defines both, so no other family changes.

Zeros are neither erased flash nor complete data. DatabaseRaw already treats such content as a write that a power loss cut: non-erased bytes after the chain lead to a recycle, a flag that is not erased reads as written, and a block header or checksum that does not match makes the block invalid. DatabaseRawSequential does the same through its header and checksum.

NMI families

What a cut leaves

Measured on an STM32G431 with the same kind of bench; its NMI_Handler clears ECCD and ECCC and returns:

  • One double word (8 bytes) is busy for 85.9 us. A cut up to 15.75 us reads blank without an ECC flag and programs normally afterwards. A cut between 17.7 us and 41.3 us (26 of 98 cuts) leaves the low 36 bits written and the high 28 bits blank: the 72-bit cell is written in two halves. 12 of these 26 raise the NMI, 14 only set ECCC. A cut from 43.3 us on reads as the complete data.
  • With the handler returning, the load delivers that half-written content: never blank in 12 of 12, and the program goes on.
  • The written flag of DatabaseRaw (all ones, low nibble of the last byte cleared) lies in the second half. In 96 cuts, 75 of them between 40.25 us and 44.75 us in steps of 0.375 us, the cell was either unwritten (no ECC flag, accepts the same program again in 26 of 26) or complete; no intermediate state.
  • A page erase (22.0 ms) cut at 2 % of its time leaves 6 double words that raise the NMI; cut at 10 % or later the whole page reads blank without a flag.
  • Programming a half-written double word again is rejected with PROGERR (9 of 9); programming all zeros over it is accepted and reads back as zeros without a flag (8 of 8).

So on G4 the reader needs no signal from the driver and no zero fill: what it reads is neither blank nor complete.

Change

  • New driver/st/stm32_flash_nmi.h and .c: bool libxr_stm32_flash_ecc_nmi(void), callable from C. When the double error flag is set it clears that flag and the single error flag and returns true; otherwise it returns false. The single error flag is cleared as well because a later double error raises no NMI while it is set (RM0351). On H5 the instruction cache is invalidated, as RM0481 asks.
  • Three register layouts are recognised by their CMSIS names: one ECCR (G0, G4, L4, L5, WB, WL, U0, U5, WBA; with ECCD2/ECCC2 and ECC2R where they exist), H5 (ECCDETR/ECCCORR), U3 (ECCDR/ECCCR). With any other device header the function returns false.
  • The call is one line in the user code section CubeMX keeps:
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */
  if (libxr_stm32_flash_ecc_nmi())
  {
    return;
  }
  /* USER CODE END NonMaskableInt_IRQn 0 */
  ...
}

Nothing changes for a project until its NMI_Handler has this line. Other NMI causes keep the existing handling.

Tests

  • PowerCutFlash has a third mode that models the H7 case: the cut unit, or the whole page of a cut erase, cannot be read afterwards; Read fills it with 0 and returns OK, programming it returns CHECK_ERR, and a completed erase makes it readable again. RunPowerCutCases runs every cut in the three modes. The G4 case, half-written content, is the existing second mode. Both databases pass all three without a source change.

Behaviour changes

Where Before Now
STM32Flash::Read on H7 and H7R/S, word with an ECC double error bus error OK, the word reads as 0; all interrupts are masked for the copy of one flash word
STM32Flash::Write on H7 and H7R/S, target word with an ECC double error bus error in the comparison CHECK_ERR, nothing is programmed
STM32Flash erase / program on H7 after a read that set an ECC flag FAILED the stale flag is cleared, the operation runs
DatabaseRaw::Init and DatabaseRawSequential::Init on H7 and H7R/S, unit cut by a power loss bus error recovered by the existing logic
STM32Flash::MIN_WRITE_SIZE and program type on H7R/S 1, byte with forced write 16, quad-word; DatabaseRaw<STM32Flash::MIN_WRITE_SIZE> gets a different layout there
NMI families, project whose NMI_Handler calls the new function endless loop in NMI_Handler the read returns the half-written unit, the databases recover
NMI families, project without the call endless loop in NMI_Handler unchanged
Double error from real damage in stored data fault handler the word reads as 0 (H7, H7R/S) or as its raw content (NMI families), no error is reported

Cost: stm32_flash.o grows from 880 to 1128 bytes of text on STM32H723 and from 872 to 1136 on STM32H7S3 (-Os); in the bench (64 MHz, D-cache on) the read of one 32-byte word takes 119 cycles against 47 for a plain copy. The NMI function is 28 bytes on G4 and 60 on H5.

Verification

  • Host tests, GNU 13: Debug with dev asserts, Release with dev asserts, Release without, each 10/10 (test_linux_can skipped, as on dev).
  • driver/st/stm32_flash.cpp compiles without a diagnostic against the HAL headers of STM32H723, H743, H745 (CM7) and H7B3 (GNU Arm 14.2.1), and against ST's HAL and CMSIS headers of STM32H7S3, H7R3, H7S7 and H7R7, where the Read override is present. A complete STM32H723 firmware (FreeRTOS, CubeMX project of the MC02 BSP) builds with this branch.
  • driver/st/stm32_flash_nmi.c compiles with -Wall -Wextra -Werror against 18 CMSIS device headers: G0B1, G071, G431, G474, L476, L4R5, L552, U575, WB55, WL55, U083, WBA52, U385, H563 and H503 take a branch that touches the expected registers; F103, F407 and H723 return false.
  • clang-format 21.1.8 passes. Doxygen 1.12.0: 933 warnings, equal to the baseline.
  • Hardware, STM32H723 (MC02), bench: the read sequence of the driver with I-cache and D-cache on reports 51 of 52 cut words as unreadable on three consecutive reads, reports none of 46 good words, and leaves the neighbouring words readable in 98 of 98 trials; no exception, no lock-up. The remaining word is one of the unstable ones described below.
  • Hardware, STM32H723, whole firmware (BSP clocks at 550 MHz, FreeRTOS, both caches on, STM32Flash and DatabaseRaw<32>, independent watchdog reset after a pseudo-random time, the database has to hold the acknowledged updates or one more), made with the first revision of this branch, in which Read returned CHECK_ERR and DatabaseRaw accepted it during Init; the read sequence and the flag clearing are the same now, the runs were not repeated. Run 1, before the ECC flag clearing: 45 cuts pass, then the start after cut 46 stops in REQUIRE with FLASH_SR1 = 0x02000000. Run 2, with the flag clearing: 100 of 100 cuts pass, 1540 updates; a cut left an ECC-error unit for the database to read in one of the 101 starts.
  • Hardware, STM32G431, bench: the figures above (98 program cuts and 12 erase cuts with pseudo-random data, 96 program cuts with the flag pattern).
  • Hardware, STM32G431, whole firmware (HSI16, FreeRTOS, HAL, STM32Flash and DatabaseRaw<8> on 16 pages, NMI_Handler with the line above, independent watchdog reset after 0.25 ms to 50 ms): 50 of 50 cuts pass, 265 updates, 51 starts all complete. The function handled 11 NMIs in 6 starts, all while the test's own log was read through STM32Flash::Read; the database met none.

Not covered

  • Of the NMI families only G431 was measured. The others compile; that their flash delivers half-written content after the handler returns is taken from the G431 result, not measured. C5 has no public CMSIS header and is not handled.
  • H7R/S is compiled only, the new write unit included. That an ignored bus error behaves there as on H7 (the load delivers stale data and the flag is set) is taken from RM0477 and from the H7 result, not measured.
  • BSPs have to add the line to their NMI_Handler; none is changed here.
  • The dual-bank path of H7 (SR2 / CCR2) and the H743, H745 and H7B3 builds are compiled only. The STM32 build matrix was not run.
  • On neither board did the whole-firmware run make the database itself read a cut unit more than once (H7: once in 146 cuts; G431: not at all in 50); its coverage of such a unit is the host test.
  • H7: a cut flag unit inside the key chain of DatabaseRaw stays in the main block until the next recycle and is zero-filled on every read until then.
  • H7: unstable words. A cut close to the start or the end of the fault window (and, in the bench, around 24.5 us) can leave a word that reads with an ECC error at one time and without at another. Seen in 1 of 52 cut words with the caches on.
  • G4: the flag cell changes from unwritten to complete within less than 0.375 us; what a cut inside that step leaves is not resolved. ECCC suppressing a later NMI was not tested.

Part of xrobot-org/XRobot-Dev-Roadmap#34

@greptile-apps

greptile-apps Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable defects were found.

Summary

The PR turns H7 flash ECC read failures into ErrorCode::CHECK_ERR and lets both database backends recover from unreadable units during startup.

  • H7 flash reads report unreadable words instead of faulting.
  • Raw database startup rebuilds blocks that contain unreadable flash units.
  • Sequential database startup restores blocks with unreadable markers.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Read an H7 flash word] --> B{ECC double error?}
  B -->|No| C[Return flash contents]
  B -->|Yes| D[Fill requested bytes with zero]
  D --> E[Return CHECK_ERR]
  E --> F{Database startup?}
  F -->|Yes| G[Restore, rebuild, or reject the block]
  F -->|No| H[Keep normal reads strict]
Loading

Reviews (1) · Last reviewed commit: "fix(database): Init accepts units left u..." · Reviewed by Greptile

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.
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.
@Jiu-xiao
Jiu-xiao force-pushed the fix/h7-flash-ecc-read branch from 9618628 to e71a670 Compare November 16, 2026 01:25
@Jiu-xiao Jiu-xiao changed the title fix(stm32, database): an H7 flash word cut by a power loss no longer stops every boot fix(stm32): an H7 flash word cut by a power loss no longer stops every boot Nov 16, 2026
…n 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.
@Jiu-xiao Jiu-xiao changed the title fix(stm32): an H7 flash word cut by a power loss no longer stops every boot fix(stm32): a flash unit cut by a power loss no longer stops every boot Nov 16, 2026
…s 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.
@Jiu-xiao
Jiu-xiao merged commit 905ac57 into dev Nov 16, 2026
7 checks passed
@Jiu-xiao
Jiu-xiao deleted the fix/h7-flash-ecc-read branch November 16, 2026 03:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant