Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions driver/st/stm32_flash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,88 @@ 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()
{
#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(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;
#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<const uint8_t*>(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<uint32_t*>(address & ~(STM32FlashMinWriteSize() - 1U)),
static_cast<int32_t>(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
Expand Down Expand Up @@ -45,6 +127,9 @@ class FlashOperationGuard
if (d_cache_enabled_) SCB_DisableDCache();
#endif
HAL_FLASH_Unlock();
#if defined(LIBXR_STM32_FLASH_ECC_BUS_ERROR)
ClearEccFlags();
#endif
}

~FlashOperationGuard()
Expand Down Expand Up @@ -252,12 +337,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<const uint8_t*>(addr + written), src + written,
chunk_size) == 0)
{
written += chunk_size;
continue;
}
#endif

if (HAL_FLASH_Program(program_type_, addr + written,
reinterpret_cast<uint32_t>(flash_word_buffer)) != HAL_OK)
Expand Down Expand Up @@ -295,6 +393,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<uint8_t*>(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<size_t>(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_;
Expand Down
60 changes: 58 additions & 2 deletions driver/st/stm32_flash.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -115,6 +122,19 @@ typename std::enable_if<HasFlashBank<T>::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. 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

/**
* @brief STM32 闪存驱动实现 / STM32 flash driver implementation
* @pre 擦写调用及相关缓存控制由调用方串行化;等待期间 HAL tick 必须能推进。
Expand All @@ -133,6 +153,36 @@ typename std::enable_if<HasFlashBank<T>::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 和 H7R/S 上编程或擦除被掉电打断后,被打断的 Flash 字 ECC 校验不过。`Read` 按
* Flash 字读取,读每个字时屏蔽全部中断并忽略总线错误,读完检查双位错误标志(H7 的
* DBECCERR,H7R/S 的 DBECCERRF);出错的字在缓冲区里填 0,
* `Read` 仍返回 `ErrorCode::OK`。读到的 0 既不是擦除态也不是完整数据,调用方按写了一半的
* 内容处理;真实损坏造成的双位错误读起来相同,不作区分。`Write` 编程前的比较同样读取,
* 目标字读不出来时不编程,返回 `ErrorCode::CHECK_ERR`,擦除后才能再写。其他系列的 `Read`
* 是基类的直接拷贝。
* 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 这两个系列的 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 生成的死循环里。
* 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
{
Expand Down Expand Up @@ -167,6 +217,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_;
Expand All @@ -175,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;
Expand Down
60 changes: 60 additions & 0 deletions driver/st/stm32_flash_nmi.c
Original file line number Diff line number Diff line change
@@ -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
}
53 changes: 53 additions & 0 deletions driver/st/stm32_flash_nmi.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#pragma once

#include <stdbool.h>

#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
Loading
Loading