Simvik

Load the newest valid settings

Choose between two settings records by magic, CRC and a wrapping sequence number. A medium embedded C problem (Checksums and CRCs), run and graded in the…

medium · Checksums and CRCs · crc · storage · flash

Settings are saved alternately into two flash slots, so a power cut during a save can only damage the slot being written. At boot, firmware must pick the record to trust:

  • a record is valid if its magic is 0xC0F1 and its crc equals record_crc() of it,
  • of the valid records, the one with the newer seq wins,
  • seq is a 32-bit counter that wraps: after 0xFFFFFFFF comes 0. Compare with (int32_t)(a - b) > 0, which is right as long as the two are less than 2^31 apart.

Write pick_slot(slots): return 0 or 1, or -1 if neither slot is valid.

Starter code

int pick_slot(const record_t slots[2]) {
  return slots[1].seq > slots[0].seq ? 1 : 0;
}

Example tests

Both valid

record_t s[2] = { make(100, 4), make(200, 5) };
show(s);

Expected output:

slot 1: value 200

The newer one was cut off mid-save

record_t s[2] = { make(100, 4), make(200, 5) };
s[1].value = 0xFFFF;   /* the write never finished */
show(s);

Expected output:

slot 0: value 100

Learn it first

  • Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.

More Checksums and CRCs problems