Embedded HandbookApps
All sections › II. Core and system mechanisms
STM32F103, STM32F407, STM32G071, STM32L476 · level intermediate · 32 min read
Open in the interactive handbook

11д. EEPROM emulation in internal Flash: journal writes, wear leveling, power-loss resilience

Section 11.5 shows how to erase a page and write halfwords to it, 11.8 shows a journal into which a whole settings structure is written, 11.9 shows the G0 double words. This section takes the next step: a key-value store, like a real EEPROM, where each variable changes on its own and at any moment. Why Flash is awkward for this, how the two-page scheme with headers works, what happens if power is lost at any step of a write or a transfer, how to estimate service life, why on the F4 everything comes down to the sector size, and what erasing does to program execution and interrupts.

Groundwork: alg.c is the emulation itself, with no tie to hardware; Flash access goes through three platform functions. host.c is built with gcc 12.2.0 (stm-sys:1) and puts a model in place of Flash: erasing sets all bits to 1, programming only clears bits to 0 and only into an erased double word. The model makes 5000 random writes, and before each one the power is cut at every step in turn — with partially written bits — after which a "power-up" checks every key; another 200000 writes without cuts count the erases. The same alg.c is built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F, Cortex-M3 and Cortex-M0, and the register-level variant for the F103 for Cortex-M3. Nothing was checked on silicon: neither the erase time nor the behaviour of real cells on a power cut.

What the documentation calls it

Original Meaning
EEPROM emulation in Flash EEPROM emulation in Flash: variables by key in a journal on pages
page transfer page transfer: live values are rewritten onto a clean page
page header, generation counter page header with a generation number: which page is newer
torn write, interrupted programming torn write: power was lost in the middle of programming
commit point commit point: the step after which the new state can no longer roll back
blank check blank check: every word of the page equals 0xFFFFFFFF
program/erase endurance endurance: how many erase cycles a page withstands
flash stall flash stall: the core waits while Flash is busy erasing or programming
ECC double word double word with an error-correcting code: written once

In plain words. Flash cannot be rewritten one cell at a time: only a whole page can be erased. So a new value is not put over the old one but appended after it, like a line in a notebook. The last line is the one that counts. When the notebook is full, the latest values are copied into a clean one and the old one is erased.


11д.1 Why internal Flash is not EEPROM

A real EEPROM, external over I²C or built into some series, erases and writes each byte separately. Microcontroller Flash has three restrictions.

Erasing is by page or sector only. An erased cell reads as ones: byte 0xFF, word 0xFFFFFFFF. Programming can only clear ones to zeros. To bring even one bit back to 1, the whole page is erased: 1 KB or 2 KB on the F103 (depending on the size), 2 KB on the G0 and L4, and on the F4 a sector of 16 to 128 KB.

Programming is in portions of a fixed width. The F1 writes halfwords. The F4 writes bytes, halfwords or words depending on the supply voltage (at 2.7…3.6 V, words). The G0 and L4 write only double words, 64 bits at a time.

On the G0 and L4 re-programming is not allowed. Each double word is stored together with an error-correcting code (ECC), and one more zero cannot be added to an already written word: the Flash controller answers with a programming error. The F1 and F4 have no ECC, and writing over to clear additional bits is physically possible — schemes that change a page's state by appending to the same word rely on that. The scheme in this section does not do that: every double word is written once, and it works the same on all four families.

Hence the layout of the emulation: all records are 8 bytes, aligned to 8 bytes, and each one goes into a still erased place.


11д.2 Endurance: how many times you can erase

Every erase wears the cells. STM32 series documentation usually gives a guaranteed endurance of the order of 10 thousand erase cycles per page (sector) at a given temperature; some series give more for part of the memory. Look up the exact number and conditions in your device's documentation. Programming without erasing hardly spends endurance — erasing does.

The naive way, "erase the page and write the value again" on every save, exhausts 10 thousand cycles in 10 thousand saves — that is, in a week if a parameter is saved once a minute. A journal divides the erases by the number of records that fit on a page; two pages erased in turn divide by two more. That is wear leveling in its simplest form.


11д.3 Two pages, a header and a record

Two pages are given to the emulation. Each is split into 8-byte slots. Slot 0 is the header, the rest are records:

#define EE_SLOTS (EE_PAGE_BYTES / 8u) /* слот 0 — заголовок, 1…EE_SLOTS-1 — записи */
#define EE_KEYS 16u                   /* ключи 0…EE_KEYS-1 */
#define EE_ERASED 0xFFFFFFFFu

A record is two words: the low one carries the key in its upper 16 bits and the value in the lower ones, the high one is the inverted copy of the low one. A record is valid when the second word equals the inverse of the first:

static int slot_free(const uint32_t *s) { return s[0] == EE_ERASED && s[1] == EE_ERASED; }
static int slot_ok(const uint32_t *s) { return s[1] == ~s[0]; } /* недописанная запись сюда не пройдёт */

The inverted copy works no worse than a CRC here, and this is why. A torn record is one in which some of the bits that should have become zeros are still ones. In the first word the extra ones sit where the correct value has zeros, in the second where the correct value has ones. The equality "second = inverse of first" then fails for any set of unwritten bits except the empty one. An erased slot is not valid either: the inverse of 0xFFFFFFFF is zero, not 0xFFFFFFFF.

The header is a generation number and its inverted copy. A page is valid only if its header is written completely:

static int page_gen(unsigned p, uint32_t *gen)
{
    const uint32_t *h = slot(p, 0);
    if (h[0] == EE_ERASED || !slot_ok(h))
        return 0; /* заголовка нет или он недописан */
    *gen = h[0];
    return 1;
}

The classic scheme keeps the page state in the header — "erased", "receiving", "valid" — and changes it by appending zeros to the same word. On the G0 and L4 that is impossible (11д.1), so here a generation replaces the state: the new page gets a number one greater, and the header is written last, when all the data is in place. Of two valid pages the one with the greater generation is in force.

The whole module takes 688 bytes of code on Cortex-M4F, 676 on Cortex-M3 and 724 on Cortex-M0. The state in RAM is 12 bytes: the active page number, the first free slot and the generation.


11д.4 Reading and power-up

The latest value of a key is the first valid record with that key when the page is scanned from the end:

static int find(unsigned p, unsigned end, uint16_t key, uint16_t *val)
{
    for (unsigned i = end; i-- > 1u;) {
        const uint32_t *s = slot(p, i);
        if (slot_ok(s) && (s[0] >> 16) == key) {
            *val = (uint16_t)s[0];
            return 1;
        }
    }
    return 0;
}

Scanning from the end means up to 127 comparisons on a 1 KB page. If there are many reads, a "key → value" table is built in RAM once at power-up and updated on every write; the journal in Flash stays the same.

At power-up ee_init decides which page is in force and puts the second one in order:

int ee_init(ee_t *e)
{
    uint32_t g0 = 0, g1 = 0;
    int v0 = page_gen(0, &g0), v1 = page_gen(1, &g1);
    if (!v0 && !v1) { /* годной страницы нет: первое включение — разметить страницу 0 */
        if (make_blank(0) || make_blank(1) || ee_prog(slot(0, 0), 1u, ~1u))
            return -1;
        e->act = 0;
        e->gen = 1;
        e->next = 1;
        return 0;
    }
    e->act = (v0 && (!v1 || (int32_t)(g0 - g1) > 0)) ? 0u : 1u; /* обе годны — новее та, где поколение больше */
    e->gen = e->act ? g1 : g0;
    if (make_blank(e->act ^ 1u)) /* вторая: недописанный перенос или недостёртая старая */
        return -1;
    e->next = EE_SLOTS;
    while (e->next > 1u && slot_free(slot(e->act, e->next - 1u)))
        e->next--;
    return 0;
}

Three decisions here matter. The second page is blank-checked as a whole, not by its header: after a cut in the middle of an erase the header may already read as 0xFFFFFFFF while the data further on does not yet. Generations are compared through a signed difference so that the counter wrapping past 2³² does not break the choice. The first free slot is searched from the end of the page: a torn record is neither free nor valid, it is simply stepped over.


11д.5 Writing and page transfer

An ordinary write is one double-word program into the first free slot. A value equal to the current one is not written at all — that saves endurance for free:

int ee_write(ee_t *e, uint16_t key, uint16_t val)
{
    uint16_t old;
    if (key >= EE_KEYS)
        return -1;
    if (find(e->act, e->next, key, &old) && old == val)
        return 0; /* то же значение — слот не тратить */
    if (e->next < EE_SLOTS) {
        uint32_t lo = (uint32_t)key << 16 | val;
        if (ee_prog(slot(e->act, e->next), lo, ~lo))
            return -1;
        e->next++;
        return 0;
    }
    return transfer(e, key, val);
}

When there are no free slots, the live values are transferred to the second page. The key being written is transferred straight away with its new value — that saves a slot and makes the transfer and the write a single action:

static int transfer(ee_t *e, uint16_t key, uint16_t val)
{
    unsigned to = e->act ^ 1u, n = 1;
    if (make_blank(to))
        return -1;
    for (uint16_t k = 0; k < EE_KEYS; k++) {
        uint16_t v;
        if (k == key)
            v = val;
        else if (!find(e->act, e->next, k, &v))
            continue;
        uint32_t lo = (uint32_t)k << 16 | v;
        if (ee_prog(slot(to, n), lo, ~lo))
            return -1;
        n++;
    }
    if (ee_prog(slot(to, 0), e->gen + 1u, ~(e->gen + 1u))) /* точка фиксации переноса */
        return -1;
    if (ee_erase(e->act))
        return -1;
    e->act = to;
    e->gen++;
    e->next = n;
    return 0;
}

The order of the steps is the main point of the section: first the copy, then the header, then erasing the old page. Until the new page's header is written, the old page is in force, and it is untouched. Once the header is written, the new page is in force and the old one is no longer needed. Erasing the old page is cleanup, not part of the commit.

There must be fewer keys than slots: after a transfer on a 1 KB page with 16 keys, 127 − 16 = 111 free slots remain. If there are as many keys as slots, a transfer frees none.

In the run without cuts the longest write — with a transfer — took 18 steps: 16 key records, the header and the erase. Over 5000 writes a transfer happened 44 times.


11д.6 A power cut at every step

The Flash model in host.c behaves like the real thing: erasing sets all bits to 1, programming only clears bits, programming a non-erased double word is an error. A power cut at step c is a step that completed partially, and the program stopping. For a write, partially means a random part of the required bits has been cleared; for an erase, a random part of the bits on the whole page has been set.

Before each of the 5000 random writes the model first counts its steps, then cuts the power at each of them in turn, in five kinds: the step did nothing, three different random partially written states, and "the step completed fully". After each cut there is a power-up and a check of all 16 keys: every key except the one being written must return the last committed value, and the one being written either the old or the new value, nothing else. Then the model also cuts the power-up itself at each of its steps, powers up again and checks that the outcome is the same.

What was checked count
write steps at which power was cut 5748
cuts (steps × 5 kinds) 28740
cuts inside the power-up after a cut 3872
power-ups with a check of all keys 32612
recovery errors 0
programs into a non-erased double word 0

Two pages of EEPROM emulation: on the left the active page 0 of generation 7 — the header "7 and its inverted copy", records of keys 2, 5, 2, a torn record of key 3 and a record of key 0, then free slots; on the right page 1, onto which during a transfer the live keys 0, 2, 5 and the new value of key 7 are copied first, and the header "8 and its inverted copy" is written last, after which page 0 is erased; below — what the power-up decides on a cut before the header is written, in the middle of it, in the middle of the erase and in the middle of an ordinary write, and the model's result: 5748 steps, 28740 cuts, not a single error

Of the 28740 cuts, in 5220 cases the power-up read the new value of the key being written, in 23520 the old one. New — when the cut fell on the erase of the old page or the write step completed fully, old — in all the others. That is what "the write is atomic" means: it either happened or it did not.

Why it works out this way, by transfer step:


11д.7 Wear estimate

One page is erased on every second transfer. A transfer happens once per S − K + 1 writes, where S is the records per page and K the live keys: the transfer takes K slots, and the last write itself goes into the transfer. So, until each of the two pages has used up N cycles:

total writes = 2 × N × (S − K + 1), years = 2 × N × (S − K + 1) / (writes per day × 365).

The model checked the formula: 200000 writes without cuts on a 1 KB page (S = 127, K = 16) gave 893 erases of page 0 and 892 of page 1, 1785 in total. The formula gives 1 + (200000 − 128) / 112 = 1785 (dropping the fraction): the first 127 writes fill the page, after that a transfer comes on every 112th.

For N = 10000 and 16 keys:

Space for the journal records per page writes per erase years at 1000 writes per day years at 100000 writes per day
page 1 KB (F103C8) 127 112 6.1 0.06
page 2 KB (G0, L4) 255 240 13.2 0.13
sector 16 KB (F4) 2047 2032 111.3 1.11
sector 128 KB (F4) 16383 16368 896.9 8.97

1000 writes per day is a value every minute and a half: two 1 KB pages will last about 6 years. 100000 per day is once a second: here even a 16 KB sector lasts a year. Hence the rule: EEPROM emulation is for settings and rarely changing counters. A counter that changes every second is kept in battery-backed RAM, in backup-domain registers or in an external FRAM, and flushed to Flash once every few minutes or on power loss.

An 8-byte record carries 2 bytes of useful value — a quarter of the space. If values are longer, the record is made wider, but the formula is the same: S is how many records fit on a page.


11д.8 F4: big sectors

On the F405 and F407 Flash is divided into sectors of unequal size: four of 16 KB, one of 64 KB, the rest of 128 KB. Only a whole sector is erased. The last two 128 KB sectors mean a quarter of a megabyte of Flash for a few variables and an erase that takes a noticeable fraction of a second and more (times from the documentation are in 11.8).

The usual solution is sectors 1 and 2 of 16 KB. Sector 0 holds the vector table and the start of the program, so in the linker script (11.3) the program region is split: the vectors in sector 0, then a 32 KB gap, then the rest of the code from sector 3. According to the table in 11д.7 a 16 KB sector is enough with a huge endurance margin; the loss is 32 KB at the start of Flash.

If even that is inconvenient, on the F4 the variables are kept outside Flash: in the 4 KB battery-backed backup SRAM of the F405/F407 or in an external EEPROM/FRAM. The G0 and L4 with their 2 KB pages do not have this problem.


11д.9 Erasing and program execution

While Flash is being erased or programmed, it cannot be read. On devices with one bank (F103, F407, most G0) any fetch of an instruction or a constant from Flash during that time simply waits: the core stalls until the erase is over. The program does not crash, but during all that time nothing located in Flash runs — interrupt handlers included. Interrupt latency grows to the page erase time.

Options:

Erasing from RAM in the register-level variant for the F103:

__attribute__((section(".RamFunc"), noinline)) int ee_erase(unsigned p)
{
    if (FL_CR & CR_LOCK) {
        FL_KEYR = 0x45670123u;
        FL_KEYR = 0xCDEF89ABu;
    }
    FL_SR = SR_PGERR | SR_WRPRTERR | SR_EOP;
    FL_CR |= CR_PER;
    FL_AR = EE_BASE + p * EE_PAGE_BYTES;
    FL_CR |= CR_STRT;
    while (FL_SR & SR_BSY) {
    }
    FL_CR &= ~CR_PER;
    FL_CR |= CR_LOCK;
    return (FL_SR & (SR_PGERR | SR_WRPRTERR)) ? -1 : 0;
}

The Cortex-M3 build showed that ee_erase (100 bytes) went into the .RamFunc section and the rest — 800 bytes, of which ee_prog is 136 bytes — into .text. The linker script generated by CubeIDE copies .RamFunc to RAM together with .data; in your own script you have to list this section yourself. The function calls nothing from Flash — the unlock is written right into it. If it called a function in Flash, the core would stall on the very first fetch.

Programming a double word also stalls fetching, but briefly — microseconds against milliseconds for an erase — so ee_prog is left in Flash.


11д.10 HAL by family

The platform part is three functions. Through HAL they differ from family to family in how the erased area is specified and which program type is allowed. Erasing:

int ee_erase(unsigned p)
{
    FLASH_EraseInitTypeDef er = {0};
    uint32_t bad = 0;
#if defined(STM32F1)
    er.TypeErase = FLASH_TYPEERASE_PAGES;
    er.PageAddress = EE_BASE + p * EE_PAGE_BYTES;
    er.NbPages = 1;
#elif defined(STM32F4)
    er.TypeErase = FLASH_TYPEERASE_SECTORS;
    er.Sector = EE_SECTOR0 + p; /* малые секторы 1 и 2 по 16 КБ */
    er.NbSectors = 1;
    er.VoltageRange = FLASH_VOLTAGE_RANGE_3; /* 2,7…3,6 В: стирание и запись словами */
#else /* G0, L4: номер страницы от начала Flash */
    er.TypeErase = FLASH_TYPEERASE_PAGES;
    er.Banks = FLASH_BANK_1;
    er.Page = (EE_BASE - FLASH_BASE) / FLASH_PAGE_SIZE + p * (EE_PAGE_BYTES / FLASH_PAGE_SIZE);
    er.NbPages = EE_PAGE_BYTES / FLASH_PAGE_SIZE;
#endif
    HAL_FLASH_Unlock();
    HAL_StatusTypeDef st = HAL_FLASHEx_Erase(&er, &bad);
    HAL_FLASH_Lock();
    return st == HAL_OK ? 0 : -1;
}

On the F1 a page is given by address, on the G0 and L4 by number, on the F4 by sector number and voltage range. Programming:

#if defined(STM32F1)
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a, lo); /* HAL пишет двумя полусловами */
    if (st == HAL_OK)
        st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a + 4u, hi);
#elif defined(STM32F4)
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a, lo);
    if (st == HAL_OK)
        st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a + 4u, hi);
#else /* G0, L4: только двойное слово, один раз — ECC не даёт дописывать */
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, a, (uint64_t)hi << 32 | lo);
#endif

FLASH_TYPEPROGRAM_DOUBLEWORD exists on the F4 too, but there it needs an external programming voltage on the VPP pin; with a normal supply, words. On the F1, HAL performs the WORD type as two halfword writes. The order matters to the scheme: first the word with the key and value, then the inverted copy. A cut between them leaves the record invalid, as it should.

The register-level variant for the F103 writes four halfwords in a row:

int ee_prog(uint32_t *dst, uint32_t lo, uint32_t hi)
{
    volatile uint16_t *d = (volatile uint16_t *)dst;
    const uint16_t h[4] = {(uint16_t)lo, (uint16_t)(lo >> 16), (uint16_t)hi, (uint16_t)(hi >> 16)};
    if (FL_CR & CR_LOCK) {
        FL_KEYR = 0x45670123u;
        FL_KEYR = 0xCDEF89ABu;
    }
    FL_SR = SR_PGERR | SR_WRPRTERR | SR_EOP;
    FL_CR |= CR_PG;
    for (unsigned i = 0; i < 4u; i++) { /* сначала значение с ключом, потом обратная копия */
        d[i] = h[i];
        while (FL_SR & SR_BSY) {
        }
    }
    FL_CR &= ~CR_PG;
    FL_CR |= CR_LOCK;
    return (FL_SR & (SR_PGERR | SR_WRPRTERR)) ? -1 : 0;
}

Sizes of the emulation functions:

Function code bytes M4F code bytes M3 code bytes M0 frame
ee_init 302 302 308 16
ee_write 322 312 342 40
ee_read 60 60 70 24

The compiler inlined the transfer, the search and the blank check into these three functions. The HAL variant was not built — there is no HAL in the image; the register-level one was built for Cortex-M3 without warnings.

ST also has a ready-made emulation — an example for each family in the Cube packages. It follows the classic scheme with page states; the one taken apart here is the same principle with a generation instead of a state. Use in a project — section 198у.4, duplicate storage of settings — 36в.5.


11д.11 Pitfalls

Erasing the page on every save. 10 thousand saves and the endurance is gone, and a cut between the erase and the write loses everything. A journal on two pages.

Writing the new page's header first. Then a cut in the middle of copying leaves a "valid" page with half the keys. The header last, after all the data.

Blank-checking by the header alone. A partially erased page can start with 0xFFFFFFFF. Before use, check the whole page and finish the erase.

A record without an integrity check. A torn record looks like a random value. An inverted copy or a CRC in every record.

As many keys as slots. A transfer frees no space — endless transfers. Noticeably fewer keys than slots.

Writing over on the G0 and L4. Zeros cannot be added to a written double word — a programming error. Each double word, once.

A torn double word on the G0 and L4. A cut in the middle of a write can leave a word whose ECC does not match. Reading such a word raises the ECC double-error flag and an NMI. The NMI handler must recognise a Flash ECC error, clear the flag and let the power-up treat the slot as invalid. The model does not have this — it checks only the logic of the scheme.

Writing during a supply dip. Programming below the allowed voltage leaves weakly written cells. Do not write when the voltage detector (PVD) reports a dip; on power loss, manage only one short write.

A big F4 sector for two variables. 128 KB per sector and a long erase. Sectors 1 and 2 of 16 KB, or storage outside Flash.

Erasing stalls handlers. On a single-bank device an interrupt waits for the erase to end. A watchdog with a margin; urgent code in RAM.

A function in .RamFunc calls a function in Flash. The core stalls on the very first fetch, and RAM gives nothing. Everything needed during the erase goes inside.

Emulation inside the program area. The linker put code into the same pages, and the first erase wipes the program. Cut the pages out in the linker script (11.3).


11д.12 Summary

Full source code

alg.c — the EEPROM emulation, the register-level variant for the F103 and the HAL variant.

/* Раздел 11д: эмуляция EEPROM на двух страницах Flash. Запись — 8 байт: ключ, значение и
 * обратная копия. Страница годна, только если в слоте 0 стоит заголовок «поколение и его
 * обратная копия»; заголовок новой страницы пишется последним, после переноса живых ключей. */
#include <stdint.h>
#include <stddef.h>

#ifndef EE_PAGE_BYTES
#define EE_PAGE_BYTES 1024u           /* страница F103C8: 1 КБ */
#endif
#define EE_SLOTS (EE_PAGE_BYTES / 8u) /* слот 0 — заголовок, 1…EE_SLOTS-1 — записи */
#define EE_KEYS 16u                   /* ключи 0…EE_KEYS-1 */
#define EE_ERASED 0xFFFFFFFFu

/* платформа: адрес страницы p (0 или 1), стирание страницы, запись двойного слова */
uint32_t *ee_page(unsigned p);
int ee_erase(unsigned p);
int ee_prog(uint32_t *dst, uint32_t lo, uint32_t hi);

typedef struct {
    unsigned act;  /* активная страница */
    unsigned next; /* первый свободный слот */
    uint32_t gen;  /* поколение активной страницы */
} ee_t;

static uint32_t *slot(unsigned p, unsigned i) { return ee_page(p) + 2u * i; }
static int slot_free(const uint32_t *s) { return s[0] == EE_ERASED && s[1] == EE_ERASED; }
static int slot_ok(const uint32_t *s) { return s[1] == ~s[0]; } /* недописанная запись сюда не пройдёт */

static int page_gen(unsigned p, uint32_t *gen)
{
    const uint32_t *h = slot(p, 0);
    if (h[0] == EE_ERASED || !slot_ok(h))
        return 0; /* заголовка нет или он недописан */
    *gen = h[0];
    return 1;
}

static int page_blank(unsigned p)
{
    const uint32_t *w = ee_page(p);
    for (unsigned i = 0; i < EE_PAGE_BYTES / 4u; i++)
        if (w[i] != EE_ERASED)
            return 0;
    return 1;
}

static int make_blank(unsigned p) { return page_blank(p) ? 0 : ee_erase(p); }

/* последнее годное значение ключа на странице: поиск с конца */
static int find(unsigned p, unsigned end, uint16_t key, uint16_t *val)
{
    for (unsigned i = end; i-- > 1u;) {
        const uint32_t *s = slot(p, i);
        if (slot_ok(s) && (s[0] >> 16) == key) {
            *val = (uint16_t)s[0];
            return 1;
        }
    }
    return 0;
}

int ee_init(ee_t *e)
{
    uint32_t g0 = 0, g1 = 0;
    int v0 = page_gen(0, &g0), v1 = page_gen(1, &g1);
    if (!v0 && !v1) { /* годной страницы нет: первое включение — разметить страницу 0 */
        if (make_blank(0) || make_blank(1) || ee_prog(slot(0, 0), 1u, ~1u))
            return -1;
        e->act = 0;
        e->gen = 1;
        e->next = 1;
        return 0;
    }
    e->act = (v0 && (!v1 || (int32_t)(g0 - g1) > 0)) ? 0u : 1u; /* обе годны — новее та, где поколение больше */
    e->gen = e->act ? g1 : g0;
    if (make_blank(e->act ^ 1u)) /* вторая: недописанный перенос или недостёртая старая */
        return -1;
    e->next = EE_SLOTS;
    while (e->next > 1u && slot_free(slot(e->act, e->next - 1u)))
        e->next--;
    return 0;
}

int ee_read(const ee_t *e, uint16_t key, uint16_t *val) { return find(e->act, e->next, key, val); }

/* страница кончилась: живые ключи — на чистую страницу (новый ключ — сразу с новым значением),
 * заголовок последним, затем стереть старую */
static int transfer(ee_t *e, uint16_t key, uint16_t val)
{
    unsigned to = e->act ^ 1u, n = 1;
    if (make_blank(to))
        return -1;
    for (uint16_t k = 0; k < EE_KEYS; k++) {
        uint16_t v;
        if (k == key)
            v = val;
        else if (!find(e->act, e->next, k, &v))
            continue;
        uint32_t lo = (uint32_t)k << 16 | v;
        if (ee_prog(slot(to, n), lo, ~lo))
            return -1;
        n++;
    }
    if (ee_prog(slot(to, 0), e->gen + 1u, ~(e->gen + 1u))) /* точка фиксации переноса */
        return -1;
    if (ee_erase(e->act))
        return -1;
    e->act = to;
    e->gen++;
    e->next = n;
    return 0;
}

int ee_write(ee_t *e, uint16_t key, uint16_t val)
{
    uint16_t old;
    if (key >= EE_KEYS)
        return -1;
    if (find(e->act, e->next, key, &old) && old == val)
        return 0; /* то же значение — слот не тратить */
    if (e->next < EE_SLOTS) {
        uint32_t lo = (uint32_t)key << 16 | val;
        if (ee_prog(slot(e->act, e->next), lo, ~lo))
            return -1;
        e->next++;
        return 0;
    }
    return transfer(e, key, val);
}

#if defined(EE_PORT_F1) /* регистры F103: страницы по 1 КБ, запись полусловами */
#define FL_KEYR (*(volatile uint32_t *)0x40022004u)
#define FL_SR (*(volatile uint32_t *)0x4002200Cu)
#define FL_CR (*(volatile uint32_t *)0x40022010u)
#define FL_AR (*(volatile uint32_t *)0x40022014u)
#define SR_BSY 0x01u
#define SR_PGERR 0x04u
#define SR_WRPRTERR 0x10u
#define SR_EOP 0x20u
#define CR_PG 0x01u
#define CR_PER 0x02u
#define CR_STRT 0x40u
#define CR_LOCK 0x80u
#define EE_BASE 0x0800F800u /* две последние страницы F103C8 */

uint32_t *ee_page(unsigned p) { return (uint32_t *)(EE_BASE + p * EE_PAGE_BYTES); }

/* целиком в ОЗУ: пока страница стирается, ядро ждёт, не выбирая команд из Flash */
__attribute__((section(".RamFunc"), noinline)) int ee_erase(unsigned p)
{
    if (FL_CR & CR_LOCK) {
        FL_KEYR = 0x45670123u;
        FL_KEYR = 0xCDEF89ABu;
    }
    FL_SR = SR_PGERR | SR_WRPRTERR | SR_EOP;
    FL_CR |= CR_PER;
    FL_AR = EE_BASE + p * EE_PAGE_BYTES;
    FL_CR |= CR_STRT;
    while (FL_SR & SR_BSY) {
    }
    FL_CR &= ~CR_PER;
    FL_CR |= CR_LOCK;
    return (FL_SR & (SR_PGERR | SR_WRPRTERR)) ? -1 : 0;
}

int ee_prog(uint32_t *dst, uint32_t lo, uint32_t hi)
{
    volatile uint16_t *d = (volatile uint16_t *)dst;
    const uint16_t h[4] = {(uint16_t)lo, (uint16_t)(lo >> 16), (uint16_t)hi, (uint16_t)(hi >> 16)};
    if (FL_CR & CR_LOCK) {
        FL_KEYR = 0x45670123u;
        FL_KEYR = 0xCDEF89ABu;
    }
    FL_SR = SR_PGERR | SR_WRPRTERR | SR_EOP;
    FL_CR |= CR_PG;
    for (unsigned i = 0; i < 4u; i++) { /* сначала значение с ключом, потом обратная копия */
        d[i] = h[i];
        while (FL_SR & SR_BSY) {
        }
    }
    FL_CR &= ~CR_PG;
    FL_CR |= CR_LOCK;
    return (FL_SR & (SR_PGERR | SR_WRPRTERR)) ? -1 : 0;
}

#elif defined(EE_PORT_HAL) /* то же через HAL: EE_BASE и номера страниц/секторов задаёт проект */
#include "main.h"

uint32_t *ee_page(unsigned p) { return (uint32_t *)(EE_BASE + p * EE_PAGE_BYTES); }

int ee_erase(unsigned p)
{
    FLASH_EraseInitTypeDef er = {0};
    uint32_t bad = 0;
#if defined(STM32F1)
    er.TypeErase = FLASH_TYPEERASE_PAGES;
    er.PageAddress = EE_BASE + p * EE_PAGE_BYTES;
    er.NbPages = 1;
#elif defined(STM32F4)
    er.TypeErase = FLASH_TYPEERASE_SECTORS;
    er.Sector = EE_SECTOR0 + p; /* малые секторы 1 и 2 по 16 КБ */
    er.NbSectors = 1;
    er.VoltageRange = FLASH_VOLTAGE_RANGE_3; /* 2,7…3,6 В: стирание и запись словами */
#else /* G0, L4: номер страницы от начала Flash */
    er.TypeErase = FLASH_TYPEERASE_PAGES;
    er.Banks = FLASH_BANK_1;
    er.Page = (EE_BASE - FLASH_BASE) / FLASH_PAGE_SIZE + p * (EE_PAGE_BYTES / FLASH_PAGE_SIZE);
    er.NbPages = EE_PAGE_BYTES / FLASH_PAGE_SIZE;
#endif
    HAL_FLASH_Unlock();
    HAL_StatusTypeDef st = HAL_FLASHEx_Erase(&er, &bad);
    HAL_FLASH_Lock();
    return st == HAL_OK ? 0 : -1;
}

int ee_prog(uint32_t *dst, uint32_t lo, uint32_t hi)
{
    uint32_t a = (uint32_t)dst;
    HAL_StatusTypeDef st;
    HAL_FLASH_Unlock();
#if defined(STM32F1)
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a, lo); /* HAL пишет двумя полусловами */
    if (st == HAL_OK)
        st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a + 4u, hi);
#elif defined(STM32F4)
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a, lo);
    if (st == HAL_OK)
        st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, a + 4u, hi);
#else /* G0, L4: только двойное слово, один раз — ECC не даёт дописывать */
    st = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, a, (uint64_t)hi << 32 | lo);
#endif
    HAL_FLASH_Lock();
    return st == HAL_OK ? 0 : -1;
}
#endif

host.c — the Flash model, a power cut at every step and the wear estimate.

/* Раздел 11д: модель Flash на компьютере и обрыв питания на каждом шаге.
 * Стирание — все биты в 1, запись только сбрасывает биты в 0 и только в стёртое двойное слово.
 * Обрыв посреди записи сбрасывает случайную часть нужных битов, посреди стирания — поднимает
 * случайную часть битов; после обрыва — «включение» (ee_init), в том числе с новым обрывом
 * внутри него, и сверка всех ключей с последним зафиксированным значением. */
#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#include "alg.c"

#define WORDS (EE_PAGE_BYTES / 4u)
static uint32_t mem[2][WORDS];
static long ops, cut_at = -1;
static int tear; /* 0 — ничего не успело, 1…3 — случайная часть, 4 — успело целиком */
static jmp_buf jb;
static unsigned long erases[2], dirty_prog;

static uint32_t rs = 2463534242u;
static uint32_t xr(void) { rs ^= rs << 13; rs ^= rs >> 17; rs ^= rs << 5; return rs; }

uint32_t *ee_page(unsigned p) { return mem[p]; }

static uint32_t part(void) { return tear == 0 ? 0u : tear == 4 ? 0xFFFFFFFFu : xr(); } /* какие биты успели */

int ee_erase(unsigned p)
{
    if (ops++ == cut_at) {
        for (unsigned i = 0; i < WORDS; i++)
            mem[p][i] |= part();
        longjmp(jb, 1);
    }
    memset(mem[p], 0xFF, sizeof mem[p]);
    erases[p]++;
    return 0;
}

int ee_prog(uint32_t *d, uint32_t lo, uint32_t hi)
{
    if (d[0] != EE_ERASED || d[1] != EE_ERASED) {
        dirty_prog++; /* настоящая Flash ответила бы ошибкой программирования */
        return -1;
    }
    if (ops++ == cut_at) {
        d[0] &= lo | ~part();
        d[1] &= hi | ~part();
        longjmp(jb, 1);
    }
    d[0] = lo;
    d[1] = hi;
    return 0;
}

/* одна запись с обрывом на шаге c: возврат 1, если обрыв случился */
static int cut_write(ee_t *x, uint16_t k, uint16_t v, long c)
{
    ops = 0;
    cut_at = c;
    if (setjmp(jb))
        return 1;
    ee_write(x, k, v);
    return 0;
}

static int cut_init(ee_t *x, long c)
{
    ops = 0;
    cut_at = c;
    if (setjmp(jb))
        return 1;
    ee_init(x);
    return 0;
}

static uint16_t want[EE_KEYS];
static int have[EE_KEYS];
static unsigned long steps, cuts, init_cuts, boots, fails, got_new, got_old, torn_rec, torn_hdr;

/* после включения: каждый ключ, кроме k, — ровно последнее зафиксированное; k — старое или новое */
static void verify(int k, uint16_t nv, ee_t *e, uint16_t *out)
{
    for (unsigned i = 0; i < EE_KEYS; i++) {
        uint16_t v;
        int r = ee_read(e, (uint16_t)i, &v);
        if ((int)i == k) {
            if (r && v == nv)
                *out = 1;
            else if ((!have[i] && !r) || (have[i] && r && v == want[i]))
                *out = 0;
            else
                fails++;
        } else if (r != have[i] || (r && v != want[i]))
            fails++;
    }
}

/* включение после обрыва: сначала обрываем и сам ee_init на каждом его шаге, потом — полный */
static void reboot_check(int k, uint16_t nv)
{
    static uint32_t m1[2][WORDS];
    static ee_t e;
    memcpy(m1, mem, sizeof mem);
    ops = 0;
    cut_at = -1;
    if (ee_init(&e))
        fails++;
    long n = ops;
    uint16_t res = 2, res2;
    verify(k, nv, &e, &res);
    boots++;
    for (long c = 0; c < n; c++) {
        memcpy(mem, m1, sizeof mem);
        tear = 1 + (int)(xr() % 3u);
        if (!cut_init(&e, c))
            fails++; /* обрыв обязан был случиться */
        init_cuts++;
        ops = 0;
        cut_at = -1;
        if (ee_init(&e))
            fails++;
        res2 = 2;
        verify(k, nv, &e, &res2);
        boots++;
        if (res2 != res)
            fails++; /* повторный обрыв не должен менять исход */
    }
    if (res == 1)
        got_new++;
    else if (res == 0)
        got_old++;
}

static void scan_torn(void)
{
    for (unsigned p = 0; p < 2; p++)
        for (unsigned i = 0; i < EE_SLOTS; i++) {
            const uint32_t *s = &mem[p][2 * i];
            if (!slot_free(s) && !slot_ok(s))
                (*(i ? &torn_rec : &torn_hdr))++;
        }
}

static uint16_t pick_key(void) { return (uint16_t)((xr() & 1u) ? xr() % 4u : xr() % EE_KEYS); } /* ключи 0…3 — частые */

int main(void)
{
    memset(mem, 0xFF, sizeof mem);
    ee_t e;
    ops = 0;
    if (ee_init(&e))
        return 1;
    static uint32_t snap[2][WORDS];
    const int W = 5000;
    unsigned long max_ops = 0, transfers = 0;
    for (int w = 0; w < W; w++) {
        uint16_t k = pick_key(), v = (uint16_t)xr();
        memcpy(snap, mem, sizeof mem);
        static ee_t e1;
        e1 = e;
        ops = 0;
        cut_at = -1;
        ee_write(&e1, k, v); /* сухой прогон: сколько шагов у этой записи */
        long n = ops;
        steps += (unsigned long)n;
        if ((unsigned long)n > max_ops)
            max_ops = (unsigned long)n;
        if (e1.gen != e.gen)
            transfers++;
        for (long c = 0; c < n; c++)
            for (int t = 0; t <= 4; t++) {
                memcpy(mem, snap, sizeof mem);
                e1 = e;
                tear = t;
                if (!cut_write(&e1, k, v, c))
                    fails++;
                cuts++;
                scan_torn();
                reboot_check(k, v);
            }
        memcpy(mem, snap, sizeof mem);
        ops = 0;
        cut_at = -1;
        if (ee_write(&e, k, v))
            fails++;
        want[k] = v;
        have[k] = 1;
    }
    printf("cut_writes=%d cut_steps=%lu cut_runs=%lu init_cuts=%lu boots=%lu fails=%lu dirty_prog=%lu\n", W, steps, cuts, init_cuts, boots,
           fails, dirty_prog);
    printf("cut_new=%lu cut_old=%lu torn_rec=%lu torn_hdr=%lu max_steps=%lu cut_transfers=%lu\n", got_new, got_old, torn_rec, torn_hdr,
           max_ops, transfers);

    /* износ: 200000 записей без обрывов, ключи равномерно, значение всегда новое */
    memset(mem, 0xFF, sizeof mem);
    memset(have, 0, sizeof have);
    erases[0] = erases[1] = 0;
    ee_init(&e);
    const long WW = 200000;
    unsigned first_live = 0;
    for (long w = 0; w < WW; w++) {
        uint16_t k = (uint16_t)(xr() % EE_KEYS), v = (uint16_t)(want[k] + 1u + xr() % 1000u);
        uint32_t g = e.gen;
        if (ee_write(&e, k, v))
            fails++;
        if (e.gen != g && g == 1) {
            for (unsigned i = 0; i < EE_KEYS; i++)
                first_live += (unsigned)(have[i] || i == k);
        }
        want[k] = v;
        have[k] = 1;
    }
    uint16_t v;
    for (unsigned i = 0; i < EE_KEYS; i++)
        if (!ee_read(&e, (uint16_t)i, &v) || v != want[i])
            fails++;
    printf("wear_writes=%ld erase0=%lu erase1=%lu gen=%lu first_live=%u slots=%u fails2=%lu\n", WW, erases[0], erases[1],
           (unsigned long)e.gen, first_live, EE_SLOTS - 1u, fails);

    /* оценка ресурса: годы = 2 * N * (S - K + 1) / (записей в сутки * 365) */
    static const struct { const char *name; unsigned bytes; } P[] = {
        {"страница 1 КБ (F103C8)", 1024}, {"страница 2 КБ (G0, L4)", 2048}, {"сектор 16 КБ (F4)", 16384}, {"сектор 128 КБ (F4)", 131072},
    };
    printf("| Место под журнал | записей на странице | записей на одно стирание | лет при 1000 записей в сутки | лет при 100000 записей в сутки |\n"
           "|---|---|---|---|---|\n");
    for (unsigned i = 0; i < 4; i++) {
        unsigned s = P[i].bytes / 8u - 1u, per = s - EE_KEYS + 1u;
        double y1 = 2.0 * 10000 * per / (1000.0 * 365), y2 = 2.0 * 10000 * per / (100000.0 * 365);
        printf("| %s | %u | %u | %.1f | %.2f |\n", P[i].name, s, per, y1, y2);
    }
    printf("done=1\n");
    return 0;
}

Next: section 12 "Service blocks" — watchdog timers, hardware CRC and the real-time clock.

Open in the interactive handbook