Resume an update after a power cut
Keep download progress in an append-only flash journal, and find where to resume even after a torn write. A hard embedded C problem (OTA updates and…
hard · OTA updates and rollback · ota · flash · power-loss · journaling
An update downloads for minutes, and the power can fail at any moment. After each chunk is written and verified, the updater appends a record to a journal in flash: the offset reached so far, followed by a check word. On boot it reads the journal to resume where it stopped.
A power cut while a record is being programmed leaves a torn record: some bits programmed, some still 1, so its check word does not match.
Write:
journal_append(offset): program a record into the first erased (all 0xFF) slot and returntrue, or returnfalseif the journal is full.resume_offset(): scan the records from the start. Stop at the first record that is erased, torn (check word does not match), or whose offset is not larger than the previous valid one. Return the offset in the last valid record, or 0 if there is none.
Use flash_program. Build words from bytes in little-endian order.
Starter code
bool journal_append(uint32_t offset) {
static int n;
uint8_t r[REC_SIZE];
memcpy(r, &offset, 4);
memset(r + 4, 0, 4);
flash_program((uint32_t)(n++ * REC_SIZE), r, REC_SIZE);
return true;
}
uint32_t resume_offset(void) {
uint32_t last = 0;
for (int i = 0; i < REC_MAX; i++) {
uint32_t off;
memcpy(&off, &journal[i * REC_SIZE], 4);
if (off == 0xFFFFFFFFu) break;
last = off;
}
return last;
}Example tests
Three chunks recorded, then a reboot
erase();
journal_append(512);
journal_append(1024);
journal_append(1536);
resume();
printf("%d programs\n", programs);Expected output:
resume at 1536
3 programsA torn record at the end
erase();
journal_append(512);
journal_append(1024);
torn(2, 1536, 5);
resume();Expected output:
resume at 1024Learn it first
- OTA updates and rollback · A/B slots, delta updates, rollback and signing.
More OTA updates and rollback problems
- Pick the slot to boot · Boot a new update on trial, and roll back if it never confirms itself.
- Is this image safe to jump to? · Check a firmware image's header, bounds, CRC and vector table before a bootloader starts it.
- Receive an update in chunks · Write update chunks to the spare slot in order, ignore resends, refuse gaps and overruns, and check the CRC at the end.
- Anti-rollback with one-time fuses · Refuse old, vulnerable firmware by its security version, counted in one-time-programmable fuses.
- Thermostat fleet: boot the update or roll back · Decide which firmware slot to boot, trying a new update a few times before rolling back.