Projects / Data logger / Phase 4
Phase 4 of 4 · about 2.5 hours
Survive a power cut
You end with a log in flash that survives a reset, and a test on your laptop that cuts the power at a thousand random moments and shows the log never loses a reading it said it saved.
A logger exists to keep readings, and RAM forgets them all at power-off. Flash keeps them, but it is awkward to write, and the power can go off halfway through a write. This phase is about doing it safely.
Step 4.1: How flash behaves (about 20 minutes)
Flash has rules that RAM does not:
- Erasing sets every bit in a whole sector to 1. You cannot erase less than a sector. On the F401, sectors 0 to 3 are 16 KB each.
- Programming can only change 1s into 0s. To write a word, it must still be all 1s, so in practice you write each word once per erase.
- Erasing is slow. A 16 KB sector takes a few hundred milliseconds, and the F401 has one flash bank, so the core stalls while it erases if it needs to read flash, which it does to fetch instructions.
- Each sector survives about 10,000 erases before it may start to fail.
- If the power goes during a write, the word may end up partly written. If it goes during an erase, the sector is partly erased.
The design that fits these rules is an append-only log: write new records after old ones, never go back to change one, and erase only when a sector is full. We use two sectors. Records fill one, then we erase the other and fill that, so the newest records are always kept and the oldest sector's worth is given up at each switch.
Each record is four words: an id that counts up across resets, the time since boot, the temperature, and a CRC, a checksum over the other three. A record is real only if its CRC matches. A record cut off by a power failure, or the junk in a half-erased sector, fails that check, so we ignore it.
The program has to stay out of the log's way. Change the FLASH line in link.ld so the program uses only sectors 0 and 1:
/* Flash sectors 0 and 1 hold the program. Sectors 2 and 3 hold the log. */
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 32K
Our firmware is under 3 KB, so 32 KB leaves plenty of room. If it ever grows past that, the linker will refuse to build it, which is much better than overwriting your log.
Step 4.2: A flash you can test (about 20 minutes)
QEMU cannot write to its flash, and testing power cuts on real hardware means pulling a cable a thousand times. So we hide flash behind four functions, and write three versions: the real one for the board, a RAM one for QEMU, and one for the laptop test that can lose power on command. Create flash.h:
/*
* Two flash sectors for the log. Erasing a sector sets every bit to 1.
* Programming can only turn 1s into 0s, so a word can be written once per erase.
*/
#ifndef FLASH_H
#define FLASH_H
#include <stdbool.h>
#include <stdint.h>
#define FLASH_SECTORS 2
uint32_t flash_sector_words(void);
const volatile uint32_t *flash_sector(int sector); /* read it like memory */
bool flash_erase(int sector);
bool flash_program(int sector, uint32_t word, uint32_t value);
#endif
The CRC is a standard one, the CRC-32 used by zip files. Create crc32.h:
#ifndef CRC32_H
#define CRC32_H
#include <stddef.h>
#include <stdint.h>
uint32_t crc32(const void *data, size_t len);
#endif
And crc32.c:
/* The CRC-32 used by zip and Ethernet, one bit at a time: small and slow, which is fine here. */
#include "crc32.h"
uint32_t crc32(const void *data, size_t len)
{
const uint8_t *p = data;
uint32_t crc = 0xFFFFFFFFu;
while (len--) {
crc ^= *p++;
for (int bit = 0; bit < 8; bit++)
crc = (crc >> 1) ^ (0xEDB88320u & (0u - (crc & 1u)));
}
return ~crc;
}
0u - (crc & 1u) is all ones when the low bit is set and all zeros when it is not, which avoids an if inside the loop. A table-driven CRC is about eight times faster, and we do not need that speed for four words a second.
Now the RAM flash for QEMU. Create flash_ram.c:
/* Pretend flash in RAM, for QEMU, which cannot write its flash. It obeys the same rules. */
#include "flash.h"
#define WORDS 256u /* 1 KB sectors: 64 records each, so you can watch them fill */
/* In .noinit, so the reset handler leaves it alone. QEMU starts RAM at zero: not erased. */
__attribute__((section(".noinit")))
static uint32_t sectors[FLASH_SECTORS][WORDS];
uint32_t flash_sector_words(void)
{
return WORDS;
}
const volatile uint32_t *flash_sector(int sector)
{
return sectors[sector];
}
bool flash_erase(int sector)
{
for (uint32_t i = 0; i < WORDS; i++)
sectors[sector][i] = 0xFFFFFFFFu;
return true;
}
bool flash_program(int sector, uint32_t word, uint32_t value)
{
sectors[sector][word] &= value; /* like flash, it can only clear bits */
return sectors[sector][word] == value;
}
flash_program uses &=, so writing to a word that is not erased gives the wrong result, exactly like real flash. The sectors are only 1 KB, 64 records each, so you can watch the log switch sectors in a few seconds.
The array lives in a section called .noinit, which the reset handler does not zero. QEMU keeps the contents of RAM when you reset the machine, so this pretend flash survives a reset, which lets you test recovery in QEMU. Add the section to link.ld, after .bss:
/* Not zeroed at reset. QEMU keeps RAM across a reset, so its pretend flash survives one. */
.noinit (NOLOAD) : { *(.noinit*) } > RAM
NOLOAD means the section takes room in RAM but nothing is stored for it in the program file.
Step 4.3: The log itself (about 40 minutes)
Create store.h:
/* Readings kept in flash, so they survive a reset or a power cut. */
#ifndef STORE_H
#define STORE_H
#include <stdbool.h>
#include <stdint.h>
typedef struct {
uint32_t id; /* counts up across resets */
uint32_t ms; /* time since that boot */
int32_t centi;
uint32_t crc; /* CRC-32 of the three words above, written last */
} record_t;
void store_mount(void);
bool store_append(uint32_t ms, int32_t centi);
uint32_t store_count(void);
void store_each(void (*fn)(const record_t *r));
#endif
And store.c:
/*
* An append-only log over two flash sectors. Records go into the active sector until it is
* full, then the other sector is erased and becomes active. The oldest sector's worth of
* readings is lost at each switch, never the newest.
*/
#include "crc32.h"
#include "flash.h"
#include "store.h"
#define RECORD_WORDS 4u
static int active;
static uint32_t next_slot; /* the first unused slot in the active sector */
static uint32_t next_id;
static uint32_t valid_count;
static uint32_t slots(void)
{
return flash_sector_words() / RECORD_WORDS;
}
static void read_slot(int sector, uint32_t slot, record_t *r)
{
const volatile uint32_t *w = flash_sector(sector) + slot * RECORD_WORDS;
r->id = w[0];
r->ms = w[1];
r->centi = (int32_t)w[2];
r->crc = w[3];
}
static bool slot_empty(const record_t *r)
{
return r->id == 0xFFFFFFFFu && r->ms == 0xFFFFFFFFu && (uint32_t)r->centi == 0xFFFFFFFFu &&
r->crc == 0xFFFFFFFFu;
}
static bool record_valid(const record_t *r)
{
return !slot_empty(r) && r->crc == crc32(r, 3 * sizeof(uint32_t));
}
void store_mount(void)
{
bool found = false;
uint32_t newest = 0;
valid_count = 0;
for (int s = 0; s < FLASH_SECTORS; s++) {
for (uint32_t i = 0; i < slots(); i++) {
record_t r;
read_slot(s, i, &r);
if (!record_valid(&r))
continue;
valid_count++;
if (!found || r.id > newest) {
found = true;
newest = r.id;
active = s;
}
}
}
if (!found) {
/* Nothing worth keeping: start clean. */
active = 0;
flash_erase(0);
next_slot = 0;
next_id = 0;
valid_count = 0;
return;
}
/* Write after the last used slot, even if that slot holds half a record. */
next_slot = slots();
while (next_slot > 0) {
record_t r;
read_slot(active, next_slot - 1, &r);
if (!slot_empty(&r))
break;
next_slot--;
}
next_id = newest + 1;
}
/* Count the valid records in a sector, to keep valid_count right when it is erased. */
static uint32_t count_valid(int sector)
{
uint32_t n = 0;
for (uint32_t i = 0; i < slots(); i++) {
record_t r;
read_slot(sector, i, &r);
if (record_valid(&r))
n++;
}
return n;
}
bool store_append(uint32_t ms, int32_t centi)
{
if (next_slot == slots()) {
int other = 1 - active;
valid_count -= count_valid(other);
if (!flash_erase(other))
return false;
active = other;
next_slot = 0;
}
record_t r = {.id = next_id, .ms = ms, .centi = centi};
r.crc = crc32(&r, 3 * sizeof(uint32_t));
uint32_t base = next_slot * RECORD_WORDS;
next_slot++; /* this slot is used now, whatever happens next */
bool ok = flash_program(active, base + 0, r.id) && flash_program(active, base + 1, r.ms) &&
flash_program(active, base + 2, (uint32_t)r.centi) &&
flash_program(active, base + 3, r.crc); /* the CRC goes last: it commits the record */
if (ok) {
next_id++;
valid_count++;
}
return ok;
}
uint32_t store_count(void)
{
return valid_count;
}
void store_each(void (*fn)(const record_t *r))
{
/* The other sector holds older records, so it goes first. */
for (int k = 1; k <= FLASH_SECTORS; k++) {
int s = (active + k) % FLASH_SECTORS;
for (uint32_t i = 0; i < slots(); i++) {
record_t r;
read_slot(s, i, &r);
if (record_valid(&r))
fn(&r);
}
}
}
store_mount runs once at boot and works out where things stand from what is in flash, because nothing in RAM survived. It finds the valid record with the highest id, which says which sector was being written. Then it walks back from the end of that sector to find the first unused slot. It looks for a slot that is not empty rather than one that is valid, because a slot holding half a record has been partly programmed and cannot be written again until the sector is erased. So we skip it.
store_append writes the four words and moves next_slot on before it knows whether the writes worked, for the same reason. A failed write still used the slot.
If no valid record exists anywhere, as on a brand new chip, store_mount erases sector 0 and starts at id 0.
Step 4.4: Pull the plug a thousand times (about 30 minutes)
Now the test that makes this phase worth doing. It gives the store a flash that loses power after a random number of operations. When that happens, the word being written gets a random mix of its old and new bits, and an erase stops halfway. Then the test powers back up, mounts the store, and checks two promises:
- Every record it reads back is one we really wrote, with the right contents, and in order.
- The newest record that
store_appendsaid was saved is still there.
Create tests/test_store.c:
/*
* Cut the power at a random moment, a thousand times, and check that the log never
* loses a record it said was saved and never returns one it did not save.
*/
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include "../flash.h"
#include "../store.h"
#define WORDS 64u /* tiny sectors: 16 records, so the log switches sectors often */
static uint32_t sectors[FLASH_SECTORS][WORDS];
static long budget = -1; /* flash operations left before the power goes; -1 means never */
static jmp_buf power_cut;
/* Count down one operation. At zero, damage what was in progress and "lose power". */
static void spend(uint32_t *word, uint32_t value)
{
if (budget < 0 || budget-- > 0)
return;
if (word)
*word &= value | (uint32_t)rand(); /* some of the bits got programmed */
longjmp(power_cut, 1);
}
uint32_t flash_sector_words(void) { return WORDS; }
const volatile uint32_t *flash_sector(int s) { return sectors[s]; }
bool flash_erase(int s)
{
for (uint32_t i = 0; i < WORDS; i++) {
spend(§ors[s][i], 0xFFFFFFFFu); /* a cut here leaves the sector half erased */
sectors[s][i] = 0xFFFFFFFFu;
}
return true;
}
bool flash_program(int s, uint32_t w, uint32_t value)
{
spend(§ors[s][w], value);
sectors[s][w] &= value;
return sectors[s][w] == value;
}
/* What we expect each record to hold, worked out from its id. */
static uint32_t ms_for(uint32_t id) { return id * 1000u; }
static int32_t centi_for(uint32_t id) { return (int32_t)(id % 9000u) - 2000; }
static int failures;
static long last_seen;
static uint32_t seen;
static void check_record(const record_t *r)
{
if ((long)r->id <= last_seen || r->ms != ms_for(r->id) || r->centi != centi_for(r->id)) {
printf("FAIL: bad record id %u\n", r->id);
failures++;
}
last_seen = (long)r->id;
seen++;
}
static void read_back(long committed)
{
last_seen = -1;
seen = 0;
store_each(check_record);
/* The newest sector's worth, and at least the latest record, must still be there. */
if (last_seen < committed) {
printf("FAIL: newest record %ld, but %ld was committed\n", last_seen, committed);
failures++;
}
if (seen != store_count()) {
printf("FAIL: store_count %u, but read back %u\n", store_count(), seen);
failures++;
}
}
int main(void)
{
srand(1);
for (uint32_t s = 0; s < FLASH_SECTORS; s++)
for (uint32_t i = 0; i < WORDS; i++)
sectors[s][i] = (uint32_t)rand(); /* a brand new chip: anything at all */
long committed = -1; /* id of the newest record store_append said was saved */
int cuts = 0;
for (int trial = 0; trial < 1000; trial++) {
budget = rand() % 400;
if (setjmp(power_cut) == 0) {
store_mount();
for (;;) {
uint32_t id = (uint32_t)(committed + 1);
if (store_append(ms_for(id), centi_for(id)))
committed = id;
}
}
cuts++;
budget = -1; /* power is back: mount and check, with no more cuts */
store_mount();
read_back(committed);
}
printf("store: %d power cuts, %ld records written, %s\n", cuts, committed + 1,
failures ? "FAILED" : "nothing lost");
return failures != 0;
}
setjmp and longjmp do the power cut. setjmp marks a place, and longjmp jumps straight back to it from deep inside flash_program, abandoning everything in between, the way a power failure abandons the code that was running. The flash array keeps whatever state it was in.
Each record's contents are worked out from its id, so the test can tell a real record from junk. The sectors start full of random numbers, like a chip whose flash holds whatever was there before.
Add it to the Makefile's test target, and add test_store to TESTS:
gcc -std=c11 -Wall -Wextra -o build/host/test_store tests/test_store.c store.c crc32.c
make test
fmt: all passed
temp: all passed
ring: all passed
store: 1000 power cuts, 22681 records written, nothing lost
A test like this is only worth something if it can fail. Break the store on purpose: in record_valid, delete the CRC check, so the line reads return !slot_empty(r);. Run the test again:
FAIL: bad record id 2145174084
FAIL: bad record id 2145174085
FAIL: bad record id 2145174086
...
store: 1000 power cuts, 22551 records written, FAILED
The full output has nearly 24,000 failures. Without the CRC, the random junk the flash started with, half-written records and half-erased sectors all come back as readings. Put the check back.
Step 4.5: Wire it in, and reset QEMU (about 20 minutes)
The console needs two changes. In console.c, include store.h instead of log.h. In show_status, report the store's count:
uart_puts(", stored ");
uart_put_u32(store_count());
And replace dump so it prints records from flash:
static void print_record(const record_t *r)
{
uart_puts("#");
uart_put_u32(r->id);
uart_puts(" t=");
uart_put_u32(r->ms);
uart_puts(" ms temp=");
uart_put_centi(r->centi);
uart_puts(" C\n");
}
static void dump(void)
{
store_each(print_record);
}
Replace main.c:
#include "adc.h"
#include "board.h"
#include "console.h"
#include "sampler.h"
#include "store.h"
#include "ticks.h"
#include "uart.h"
int main(void)
{
board_init();
uart_init();
ticks_init();
adc_init();
store_mount();
uart_puts("logger: booted, ");
uart_put_u32(store_count());
uart_puts(" readings in flash\n> ");
for (;;) {
sample_t s;
while (sampler_next(&s)) {
if (!store_append(s.ms, s.centi))
uart_puts("store: write failed\n");
if (console_live())
console_print_sample(&s);
led_toggle();
}
/* One character per pass, so samples are saved between commands. */
int c = uart_getc();
if (c >= 0)
console_feed((char)c);
else
__asm volatile("wfi"); /* nothing to do: sleep until the next interrupt */
}
}
Delete log.c and log.h. Now the Makefile picks a flash driver for each board. Here it is in full:
BOARD ?= qemu
BUILD = build/$(BOARD)
CC = arm-none-eabi-gcc
CFLAGS = -mcpu=cortex-m4 -mthumb -Os -g -std=c11 -Wall -Wextra -ffreestanding
LDFLAGS = -nostdlib -T link.ld -Wl,--gc-sections -lgcc
ifeq ($(BOARD),qemu)
CFLAGS += -DBOARD_QEMU
FLASH_SRC = flash_ram.c
else ifeq ($(BOARD),nucleo)
CFLAGS += -DBOARD_NUCLEO
FLASH_SRC = flash_stm32.c
else
$(error BOARD must be qemu or nucleo)
endif
SRC = startup.c board.c uart.c ticks.c adc.c fmt.c temp.c sampler.c crc32.c store.c $(FLASH_SRC) console.c main.c
TESTS = test_fmt test_temp test_ring test_store
$(BUILD)/logger.elf: $(SRC) $(wildcard *.h) link.ld Makefile
mkdir -p $(BUILD)
$(CC) $(CFLAGS) $(SRC) $(LDFLAGS) -o $@
arm-none-eabi-size $@
$(BUILD)/logger.bin: $(BUILD)/logger.elf
arm-none-eabi-objcopy -O binary $< $@
bin: $(BUILD)/logger.bin
run: $(BUILD)/logger.elf
qemu-system-arm -M netduinoplus2 -nographic -kernel $<
test:
mkdir -p build/host
gcc -std=c11 -Wall -Wextra -o build/host/test_fmt tests/test_fmt.c fmt.c
gcc -std=c11 -Wall -Wextra -o build/host/test_temp tests/test_temp.c temp.c
gcc -std=c11 -Wall -Wextra -o build/host/test_ring tests/test_ring.c
gcc -std=c11 -Wall -Wextra -o build/host/test_store tests/test_store.c store.c crc32.c
for t in $(TESTS); do ./build/host/$$t || exit 1; done
clean:
rm -rf build
.PHONY: bin run test clean
Build and run. Set a fast rate so the 64-record sectors fill quickly, wait a couple of seconds, and ask:
logger: booted, 0 readings in flash
> rate 10
ok
> status
uptime 1638 ms, rate 10 ms, taken 149, stored 85, dropped 0
> dump
#64 t=790 ms temp=-132.58 C
#65 t=800 ms temp=-130.32 C
#66 t=810 ms temp=-128.06 C
taken 149 and stored 85: the log has switched sectors twice. Record 0 to 63 filled sector 0, 64 to 127 filled sector 1, and then sector 0 was erased for 128 onwards. The oldest record left is #64.
Now the real test. Type rate 100 and wait two seconds. Then press Ctrl-A, let go, and press C. That opens QEMU's monitor. Type system_reset and press Enter, then press Ctrl-A, C again to get back to the logger:
logger: booted, 0 readings in flash
> rate 100
ok
> status
uptime 2611 ms, rate 100 ms, taken 22, stored 22, dropped 0
> logger: booted, 26 readings in flash
> status
uptime 497 ms, rate 1000 ms, taken 0, stored 26, dropped 0
> dump
#0 t=451 ms temp=-277.09 C
#1 t=551 ms temp=-274.83 C
...
#25 t=2951 ms temp=-220.64 C
The chip reset: the uptime started again and the rate went back to its default. The readings did not go anywhere, and the next one will be #26.
Step 4.6: The real flash, on the board (about 20 minutes)
Create flash_stm32.c:
/* The real flash on an STM32F401: sectors 2 and 3, 16 KB each. */
#include "board.h"
#include "flash.h"
#define FLASH_KEYR REG32(0x40023C04u)
#define FLASH_SR REG32(0x40023C0Cu)
#define FLASH_CR REG32(0x40023C10u)
#define SR_BSY (1u << 16)
#define SR_ERRORS 0xF2u /* PGSERR, PGPERR, PGAERR, WRPERR and OPERR */
#define CR_PG (1u << 0)
#define CR_SER (1u << 1)
#define CR_SNB(n) ((uint32_t)(n) << 3)
#define CR_PSIZE_32 (2u << 8) /* write 32 bits at a time: needs 2.7 to 3.6 V */
#define CR_STRT (1u << 16)
#define CR_LOCK (1u << 31)
static const uint32_t sector_number[FLASH_SECTORS] = {2, 3};
static const uint32_t sector_base[FLASH_SECTORS] = {0x08008000u, 0x0800C000u};
static void wait_ready(void)
{
while (FLASH_SR & SR_BSY) {
}
}
static void unlock(void)
{
wait_ready();
if (FLASH_CR & CR_LOCK) {
FLASH_KEYR = 0x45670123u; /* the two keys, in this order */
FLASH_KEYR = 0xCDEF89ABu;
}
FLASH_SR = SR_ERRORS; /* clear old errors: they are cleared by writing 1 */
}
/* Lock again, and report whether the operation went wrong. */
static bool finish(void)
{
wait_ready();
FLASH_CR = CR_LOCK;
return (FLASH_SR & SR_ERRORS) == 0;
}
uint32_t flash_sector_words(void)
{
return 16u * 1024u / 4u;
}
const volatile uint32_t *flash_sector(int sector)
{
return (const volatile uint32_t *)sector_base[sector];
}
bool flash_erase(int sector)
{
unlock();
FLASH_CR = CR_SER | CR_SNB(sector_number[sector]) | CR_PSIZE_32;
FLASH_CR |= CR_STRT; /* the CPU stalls on any flash read until the erase ends */
return finish();
}
bool flash_program(int sector, uint32_t word, uint32_t value)
{
unlock();
FLASH_CR = CR_PG | CR_PSIZE_32;
((volatile uint32_t *)sector_base[sector])[word] = value;
return finish();
}
The flash controller is locked after reset, so stray writes cannot damage the program. Writing two magic keys to FLASH_KEYR, in order, unlocks it. To erase, set SER and the sector number, then STRT, and wait while BSY is set. To program, set PG and write the word to its address as if it were RAM. finish locks the controller again and checks the error flags.
PSIZE sets how many bits are programmed at once. 32 bits needs a supply between 2.7 and 3.6 volts, and the Nucleo runs at 3.3 volts.
On the board: make BOARD=nucleo bin and copy the file to the board as before. Wait a minute, type status, then unplug the USB cable, plug it back in, and open the serial port again. status should show the readings from before you pulled the cable, and dump lists them.
Two things will be different from QEMU. Each sector holds 1024 records instead of 64. And at each sector switch, the erase stalls the core for a few hundred milliseconds, SysTick interrupts are missed, and the clock falls behind by that much. You will see a jump in t= there. The keep going list says how a real logger avoids that.
Pitfall: count your erases. With two 16 KB sectors, each one is erased once every 2048 records. At one reading a second, that is once every 34 minutes, and 10,000 erases last about 237 days. At one reading every 10 ms, they last about 57 hours. Pick the rate from how long the logger must live, and then make the log bigger if you have to.
Phase 4 done
The logger now keeps its readings through a reset or a power cut, and you have a test that shows it, with a thousand power cuts, without touching a cable. That answers the question from the start: what happens when the power goes off in the middle of a write. You built the whole logger yourself, from the first instruction after reset to a log in flash.