Pick the slot to boot
Boot a new update on trial, and roll back if it never confirms itself. A medium embedded C problem (OTA updates and rollback), run and graded in the browser.
medium · OTA updates and rollback · ota · bootloader · rollback
With A/B updates, new firmware is written to the slot not running, marked PENDING, and booted on trial. The new firmware must confirm itself (mark the slot GOOD) once it has started properly. If it keeps failing before confirming, the bootloader rolls back.
Write choose_slot(s), called by the bootloader on every boot, for two slots s[0] and s[1]:
- If a slot is PENDING: if its
attemptshas reachedMAX_ATTEMPTS, mark it BAD (rollback) and go on to step 2; otherwise incrementattemptsand boot it. - Otherwise boot the GOOD slot with the higher version (slot 0 if equal).
- If no slot can be booted, return -1 (recovery mode).
Starter code
int choose_slot(slot_t *s) {
for (int i = 0; i < 2; i++) if (s[i].state == SLOT_PENDING) return i;
return s[1].version > s[0].version ? 1 : 0;
}Example tests
A new update boots on trial
slot_t s[2] = { { SLOT_GOOD, 4, 0 }, { SLOT_PENDING, 5, 0 } };
boot(s);Expected output:
boot 1 (A: good v4, B: pending v5, tries 1)An update that never confirms is rolled back
slot_t s[2] = { { SLOT_GOOD, 4, 0 }, { SLOT_PENDING, 5, 0 } };
for (int i = 0; i < 5; i++) boot(s);Expected output:
boot 1 (A: good v4, B: pending v5, tries 1)
boot 1 (A: good v4, B: pending v5, tries 2)
boot 1 (A: good v4, B: pending v5, tries 3)
boot 0 (A: good v4, B: bad v5, tries 3)
boot 0 (A: good v4, B: bad v5, tries 3)Learn it first
- OTA updates and rollback · A/B slots, delta updates, rollback and signing.
More OTA updates and rollback problems
- 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.
- 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.
- 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.