Simvik

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 return true, or return false if 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 programs

A torn record at the end

erase();
journal_append(512);
journal_append(1024);
torn(2, 1536, 5);
resume();

Expected output:

resume at 1024

Learn it first

More OTA updates and rollback problems