Storing settings in flash to recover from interrupted writes
Device settings, calibration data and counters usually live in on-chip flash or an external flash chip. Flash has two properties that make this hard: you can only change a bit from 1 to 0 by writing, and getting it back to 1 requires erasing a whole sector. And power can disappear at any moment, including halfway through an erase.
The failure you must design for
Suppose you keep a single copy and update it by erasing first. If the supply drops after the erase but before the new data lands, the device has no configuration at all. If you overwrite in place, a cut leaves you with half of the old record and half of the new one. Either way the device wakes up with garbage and, worse, might not notice.
The pattern: two slots, a sequence number and a CRC
- Reserve two flash slots, A and B.
- Each record holds a sequence number, the payload and a CRC over both.
- To save, erase the slot that does not hold the newest valid record, then write the new record there with a sequence number one higher. Write the payload, then CRC, then the sequence field last; the erased sequence value is reserved.
- To load, check both slots. A slot is valid only if its CRC matches (and it is not blank). Use the valid one with the newest sequence number.
After an initial successful save, the old record stays intact while the other slot is updated, provided they occupy independent erase units and a failed operation cannot damage the other slot. CRC validation is probabilistic, not a guarantee against every corruption.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
Proving it by cutting power at every byte
Reasoning about this is error-prone, so test it: simulate flash that erases to 0xFF and can only clear bits, then cut power after every possible number of byte operations, including partway through the erase, and check that the load always returns either the old or the new record. The test repeats this with each slot as the target and with the sequence counter about to wrap.
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#define SLOT_SIZE 32u
#define PAYLOAD 16u
typedef struct { uint32_t seq; uint8_t data[PAYLOAD]; } cfg_t; /* record = seq + data + crc32 */
static uint8_t flash[2][SLOT_SIZE];
static long ops_left; /* power fails when this reaches 0; negative = never */
static bool op(void) { if (ops_left < 0) return true; if (ops_left == 0) return false; ops_left--; return true; }
static uint32_t crc32(const uint8_t *p, size_t n)
{
uint32_t c = 0xFFFFFFFFu;
while (n--) {
c ^= *p++;
for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1u)));
}
return ~c;
}
static void put32(uint8_t *p, uint32_t v) { p[0]=(uint8_t)v; p[1]=(uint8_t)(v>>8); p[2]=(uint8_t)(v>>16); p[3]=(uint8_t)(v>>24); }
static uint32_t get32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1]<<8) | ((uint32_t)p[2]<<16) | ((uint32_t)p[3]<<24); }
/* sector erase, modelled byte by byte so a power cut can land in the middle of it */
static bool flash_erase(int s) { for (unsigned i = 0; i < SLOT_SIZE; i++) { if (!op()) return false; flash[s][i] = 0xFF; } return true; }
/* program: can only clear bits */
static bool flash_prog(int s, unsigned off, const uint8_t *src, unsigned n)
{
for (unsigned i = 0; i < n; i++) { if (!op()) return false; flash[s][off + i] &= src[i]; }
return true;
}
static bool slot_valid(int s, cfg_t *out)
{
uint32_t seq = get32(&flash[s][0]);
if (seq == 0xFFFFFFFFu) return false; /* blank */
if (get32(&flash[s][4 + PAYLOAD]) != crc32(flash[s], 4 + PAYLOAD)) return false;
out->seq = seq; memcpy(out->data, &flash[s][4], PAYLOAD);
return true;
}
/* returns the slot holding the newest valid record, or -1 */
static int cfg_load(cfg_t *out)
{
cfg_t a, b; bool va = slot_valid(0, &a), vb = slot_valid(1, &b);
if (va && vb) { if ((uint32_t)(a.seq - b.seq) != 0u && (uint32_t)(a.seq - b.seq) < UINT32_C(0x80000000)) { *out = a; return 0; } *out = b; return 1; } /* serial-number order: assumes distance < half the range */
if (va) { *out = a; return 0; }
if (vb) { *out = b; return 1; }
return -1;
}
static void cfg_save(const uint8_t *data)
{
cfg_t cur; int newest = cfg_load(&cur);
uint32_t seq = (newest >= 0) ? cur.seq + 1u : 1u;
if (seq == 0xFFFFFFFFu) seq = 0u; /* 0xFFFFFFFF means "blank", so never use it */
int target = (newest == 0) ? 1 : 0; /* overwrite the slot that is NOT the newest */
uint8_t rec[4 + PAYLOAD + 4];
put32(rec, seq); memcpy(rec + 4, data, PAYLOAD); put32(rec + 4 + PAYLOAD, crc32(rec, 4 + PAYLOAD));
if (!flash_erase(target)) return;
if (!flash_prog(target, 4, rec + 4, PAYLOAD)) return; /* payload first */
if (!flash_prog(target, 4 + PAYLOAD, rec + 4 + PAYLOAD, 4)) return; /* CRC */
(void)flash_prog(target, 0, rec, 4); /* sequence number last */
}
int main(void)
{
if (crc32((const uint8_t *)"123456789", 9) != 0xCBF43926u) { puts("FAIL crc vector"); return 1; }
const long total_ops = SLOT_SIZE + PAYLOAD + 4 + 4; /* erase + payload + CRC + sequence */
unsigned cases = 0, kept_old = 0, got_new = 0;
/* prior = how many saves happened first, so both slots take a turn as the target;
start_seq = where the counter begins, including right before it wraps */
const uint32_t starts[] = {1u, 0xFFFFFFFEu};
for (unsigned si = 0; si < 2; si++) {
for (unsigned prior = 1; prior <= 3; prior++) {
for (long cut = 0; cut <= total_ops; cut++) { /* cut == total_ops means no cut */
memset(flash, 0xFF, sizeof flash);
uint8_t d[PAYLOAD];
ops_left = -1;
if (si == 1) { /* seed slot 0 so seq wraps during the test */
uint8_t rec[4 + PAYLOAD + 4]; memset(d, 0, PAYLOAD);
put32(rec, starts[si] - 1u); memcpy(rec + 4, d, PAYLOAD); put32(rec + 4 + PAYLOAD, crc32(rec, 4 + PAYLOAD));
memcpy(flash[0], rec, sizeof rec);
}
for (unsigned i = 1; i <= prior; i++) { memset(d, (int)(0x10 + i), PAYLOAD); cfg_save(d); }
uint8_t oldv[PAYLOAD], newv[PAYLOAD];
memset(oldv, (int)(0x10 + prior), PAYLOAD); memset(newv, 0x99, PAYLOAD);
ops_left = cut; cfg_save(newv); ops_left = -1;
cfg_t got;
if (cfg_load(&got) < 0) { printf("FAIL: nothing loadable (cut %ld)\n", cut); return 1; }
bool is_old = memcmp(got.data, oldv, PAYLOAD) == 0, is_new = memcmp(got.data, newv, PAYLOAD) == 0;
if (!is_old && !is_new) { printf("FAIL: garbage (cut %ld)\n", cut); return 1; }
if (cut == total_ops && !is_new) { puts("FAIL: complete save not visible"); return 1; }
cases++; kept_old += is_old; got_new += is_new;
}
}
}
printf("%ld byte operations per save; power cut after each one, plus a clean save\n", total_ops);
printf("%u cases (both slots as target, sequence wrap included)\n", cases);
printf("old record kept %u times, new record %u times, garbage 0 times\n", kept_old, got_new);
return 0;
}
56 byte operations per save; power cut after each one, plus a clean save 342 cases (both slots as target, sequence wrap included) old record kept 336 times, new record 6 times, garbage 0 times
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
The test checks every cut point in this byte-operation model. Programming the sequence last means an interrupted record is rejected if the sequence is blank or the CRC does not match. CRC collisions are possible, and real programming units may tear differently. The unsigned modular sequence comparison handles wrap provided valid records are less than half the counter range apart; equal or exactly half-range values have no unambiguous newer record. The normal alternating-slot protocol keeps successive valid records close.
The wrap-around part of the test exists because of a real bug in a first draft of this design: the value 0xFFFFFFFF is what an erased sequence field looks like, so the counter must skip it. The save function does, and the comparison still orders the records correctly across the jump.
What about wear?
Each flash sector survives a limited number of erase cycles. Typical on-chip figures range from about 10,000 to 100,000, but read your datasheet, as it depends on the part and sometimes on temperature. Two slots already halves the wear per sector compared with always rewriting the same one. If you save often (counters, logs), rotate across more slots, or use a log-structured scheme that appends records and only erases a sector when it is full. Also avoid saving on every change; batch or debounce writes.
Production checklist
- Use separate erase units and respect the part's minimum program size, alignment, ECC and power-fail behavior. Write payload, CRC, then sequence (or a separate commit unit) in that order only where the datasheet permits it.
- Handle "both slots invalid" with sane defaults, and report it.
- Version your record layout, and serialize fields explicitly (see struct padding).
- Check whether your flash controller needs the CPU to stall during erase, and what that does to your interrupts.
- Test power-fail on the real hardware too, with a switchable supply, not only in simulation.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.