Simvik

A record that survives a reset

Count boots in RAM that keeps its contents through a reset but not a power cut, trusting the record only when it checks out. A medium embedded C problem…

medium · Fault injection: resets, brown-outs and flipped bits · reset · ram · integrity

RAM keeps its contents through a reset, so a boot counter can live in a record the startup code does not touch. At power-on that RAM holds anything, so the record carries a check:

typedef struct { uint32_t magic; uint32_t boots; uint32_t check; } boot_record_t;

Write boot_count(r), called once at every boot. If r->magic is not BOOT_MAGIC or r->check is not ~r->boots, the record is not valid: start it again with boots = 0 (and the magic). Then count this boot and update check. Return the new count.

Starter code

uint32_t boot_count(boot_record_t *r) {
  if (r->magic != BOOT_MAGIC) {
    r->magic = BOOT_MAGIC;
    r->boots = 0;
  }
  r->boots++;
  return r->boots;
}

Example tests

Power-on, then two resets

boot_record_t r = { 0x5A5A5A5Au, 77, 12 };
show(&r);
show(&r);
show(&r);

Expected output:

boots 1 check ok 1
boots 2 check ok 1
boots 3 check ok 1

Learn it first

More Fault injection: resets, brown-outs and flipped bits problems

  • Decode the reset cause · Name the reset an STM32F4 came out of from RCC->CSR, when several flags are set at once.