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
magicis 0xC0F1 and itscrcequalsrecord_crc()of it, - of the valid records, the one with the newer
seqwins, seqis 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 200The 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 100Learn it first
- Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.
More Checksums and CRCs problems
- CRC-32 · Compute the CRC-32 used by Ethernet, zip and PNG, bit by bit.
- A table-driven CRC-16 · Build a 256-entry table once, then compute CRC-16/CCITT a byte at a time.
- Fix: the receiver rejects some frames · The checksum covers one byte too many.
- Fix: our CRC matches the wrong tool · A CRC-16 routine has the right polynomial and the wrong initial value.
- Greenhouse: trust only good settings · Decide at start-up whether the settings read back from EEPROM can be used.