Fault injection: resets, brown-outs and flipped bits
Reading the reset cause, RAM that survives a reset, brown-outs, single event upsets and injecting faults on purpose.
The question every boot must answer
A product in the field restarts for reasons you did not plan: the supply sagged when a motor started, the watchdog bit because a driver waited for ever, a technician pressed the reset button, the firmware called NVIC_SystemReset() after an update. Each calls for a different reaction. After a watchdog reset you log a fault and perhaps enter a safe mode; after a brown-out you check that a half-finished flash write is not trusted; after a power-on you start from the defaults.
Firmware that does not ask "why did I restart?" treats all of these alike, and the commonest bug in long-lived devices follows: a fault that resets the chip every few hours, invisible because the device always comes back.
Reading the reset cause
Every MCU latches the cause in a register that survives the reset itself:
| Chip | Register | Flags |
|---|---|---|
| ATmega328P | MCUSR | PORF power-on, EXTRF reset pin, BORF brown-out, WDRF watchdog |
| STM32F4 | RCC->CSR | PORRSTF, PINRSTF, BORRSTF, SFTRSTF software, IWDGRSTF, WWDGRSTF, LPWRRSTF |
| STM32F0, F1 | RCC->CSR | as the F4, but no separate BORRSTF: a brown-out is a power-on reset (PORRSTF) |
Three details catch everyone:
- Several flags at once. On an STM32F4 a power-on reset sets
PORRSTFandBORRSTF, and every internal reset (watchdog, software) also pulls the NRST pin low, soPINRSTFis set beside it. Test the most specific flag first: watchdog, software, power-on, brown-out, and the pin last. - The flags accumulate. They stay set until you clear them (
RMVFon an STM32, writing 0 toMCUSRon an AVR). Read them once, early, then clear them, or the next boot sees this boot's causes too. - The bootloader may clear them first. The Arduino Uno's bootloader reads and clears
MCUSRbefore the sketch runs; Optiboot passes the value in a register, so the sketch must fetch it from there.
#include <stdio.h>
#include <stdint.h>
/* RCC->CSR's reset flags on an STM32F4 (RM0390 6.3.27). */
#define BORRSTF (1u << 25)
#define PINRSTF (1u << 26)
#define PORRSTF (1u << 27)
#define SFTRSTF (1u << 28)
#define IWDGRSTF (1u << 29)
static const char *reset_cause(uint32_t csr) {
if (csr & IWDGRSTF) return "watchdog";
if (csr & SFTRSTF) return "software";
if (csr & PORRSTF) return "power-on";
if (csr & BORRSTF) return "brown-out";
if (csr & PINRSTF) return "reset pin";
return "unknown";
}
int main(void) {
const uint32_t seen[] = { PORRSTF | BORRSTF | PINRSTF, BORRSTF | PINRSTF, IWDGRSTF | PINRSTF, SFTRSTF | PINRSTF, PINRSTF };
for (int i = 0; i < 5; i++) printf("CSR %08X: %s\n", (unsigned)seen[i], reset_cause(seen[i]));
return 0;
}
What survives a reset
A reset restarts the core and the peripherals, but it does not erase RAM: the SRAM cells hold their contents as long as the supply stays above the retention voltage, which is well below the brown-out level. So after a watchdog reset, a software reset or a short brown-out, the variables of the previous run are still there; only the C startup code overwrites them (it copies .data and zeroes .bss).
That makes RAM the cheapest place for things that must survive a reset but not a power cut: a boot counter, the last fault code, a "the update was on trial" flag, an attempt counter. Put them where the startup code does not touch them: a section the linker script marks NOLOAD (often called .noinit), or a fixed address beyond the program's own RAM. Then check them before trusting them, because at power-on that RAM holds random values:
typedef struct { uint32_t magic; uint32_t boots; uint32_t check; } boot_record_t;
#define BOOT ((volatile boot_record_t *)0x20010000u) /* beyond .data, .bss, the heap and the stack */
void boot_count(void) {
if (BOOT->magic != 0xB0071234u || BOOT->check != ~BOOT->boots) { /* random after power-on: start again */
BOOT->magic = 0xB0071234u;
BOOT->boots = 0;
}
BOOT->boots++;
BOOT->check = ~BOOT->boots;
}
A magic number alone is weak: random RAM matches a 32-bit magic once in four billion power-ons, but a firmware bug that writes the record half way matches it every time. The inverted copy (or a CRC over the record) catches a torn or partly overwritten record too.
Brown-outs
A brown-out is a dip in the supply that is too short to be a power cut and too deep to run through: a motor starting, a GSM modem's 2 A transmit burst on a weak battery, a connector that bounces. Below the minimum operating voltage the core may execute garbage: skip instructions, misread flash, write the wrong value to the wrong place. The brown-out detector (BOR, BOD) holds the chip in reset while the supply is below its threshold, so the code never runs out of specification.
What it does not do is finish what was interrupted. After a brown-out:
- A flash or EEPROM write may be half done. A sector erased but not rewritten reads 0xFF; a word half programmed reads neither old nor new. Never overwrite the only copy of anything: write the new record beside the old one, with a sequence number and a CRC, and let the boot code pick the newest valid one.
- A multi-byte RAM update may be torn: the first half of a 32-bit counter written, the second not. A checked record shows it.
- External chips may not have reset with the MCU: an I2C sensor in the middle of a byte, an SPI flash still busy, a modem in an unknown state. Re-initialise them explicitly; see the next lesson for the I2C bus.
Set the brown-out threshold above the lowest voltage at which everything on the board works (the flash, the sensors, the radio), not just the core. On an AVR it is a fuse; on an STM32F4 the option byte BOR_LEV, off by default on many parts.
Flipped bits
A bit in RAM flips on its own now and then. Cosmic-ray neutrons and the alpha particles of packaging materials cause single event upsets; at sea level a small MCU's SRAM sees about one per several years, an aircraft's thousands of times more, and a marginal supply or a hot chip makes it worse. Chips for safety work have ECC RAM that corrects single bits; most MCUs have none, or parity on part of their RAM only.
Firmware defends the data that matters:
| Data | Defence |
|---|---|
| A configuration in RAM | a CRC, checked periodically, restored from flash on a mismatch |
| A safety-critical variable (a valve's commanded state) | stored twice, the second inverted; compared on every use |
| The stack | a canary word at its far end, checked by the idle loop |
| The code in flash | a CRC of the image at boot, or periodically (IEC 60730 class B) |
| RAM itself | a march test at boot, over RAM not yet in use |
#include <stdio.h>
#include <stdint.h>
/* A value kept with its inverse: one flipped bit in either copy is caught. */
typedef struct { uint32_t value, inverse; } safe_u32;
static void safe_set(safe_u32 *s, uint32_t v) { s->value = v; s->inverse = ~v; }
static int safe_get(const safe_u32 *s, uint32_t *out) {
if ((s->value ^ s->inverse) != 0xFFFFFFFFu) return -1; /* corrupted: the caller goes to its safe state */
*out = s->value;
return 0;
}
int main(void) {
safe_u32 setpoint;
uint32_t v = 0;
safe_set(&setpoint, 750);
printf("read: %d, value %u\n", safe_get(&setpoint, &v), (unsigned)v);
setpoint.value ^= 1u << 3; /* a single event upset */
printf("after a flip: %d\n", safe_get(&setpoint, &v));
return 0;
}
Injecting faults on purpose
You cannot wait for the field to test this code. Fault injection makes the faults happen on demand:
- Brown-outs with a programmable supply that dips on a trigger, or a MOSFET that cuts the supply for a few milliseconds.
- Resets at random moments, from a test rig that pulls NRST, so that every half-finished operation is exercised.
- Bit flips with a debugger that writes RAM while the program runs, or in a simulator.
- Hangs by a test command that blocks, to prove the watchdog is configured and kicked from the right place.
The simulator here does all four: a board's settings offer a brown-out, a RAM bit flip and a stuck pin at a chosen time, and a test can inject brownout, bitflip (an address and a bit) and glitch inputs at any moment. Run your recovery code under them before it meets a real supply.
Going deeper
Interview question: Your device resets in the field every few days and comes back up working. How would you find out why?
Answer: First make the firmware record it: read the reset-cause register at the very start of main, before anything clears it, and log the cause with an uptime and a boot counter kept in a no-init RAM record (checked with a magic and an inverted copy) or appended to flash. A watchdog reset says the code hung or a loop overran its budget, so add a record of where it was (the last state, the task that failed to check in, or the stacked PC from a fault handler). A brown-out says the supply sagged, so look at the battery, the regulator and large loads switching on, and measure with a scope triggered on the dip. A software reset points at a deliberate reset path, such as an error handler or an update. Then reproduce it on the bench by injecting the suspected fault: dips in the supply, random resets, a blocked driver.
Interview question: What is a brown-out detector for, and what problems remain after a brown-out reset?
Answer: It holds the MCU in reset while the supply is below a threshold, so the core never executes at a voltage where it could misread flash or skip instructions. It does not undo what the dip interrupted: a flash or EEPROM write may be half done, a multi-byte variable torn, and external chips such as I2C sensors may not have reset with the MCU. So the firmware keeps two copies of persistent records with sequence numbers and CRCs, re-initialises peripherals and external devices explicitly at boot, and the threshold is set above the lowest voltage at which every part of the board works, not just the core.
Interview question: How do you protect important data in RAM against single event upsets on an MCU without ECC?
Answer: By redundancy that the code checks. A configuration block gets a CRC that is checked periodically and restored from flash on a mismatch. A critical variable is stored twice, the second copy inverted, and both are compared on every read, going to a safe state when they disagree. Stacks get canaries, the code in flash a CRC check at boot or periodically, and RAM a march test at start-up. The checks have to run often enough that a flipped bit is caught before it is acted on, and the fault is logged so field data shows whether it happens.
Explain it: In your own words, explain why a record kept in RAM across resets needs both a magic number and a check value, and what each one catches.
Answer: At power-on RAM holds random values, and after a reset it holds whatever the last run left, so the boot code cannot trust a record just because it is there. The magic number says "this is a record of mine at all": random RAM almost never matches it. The check value, an inverted copy or a CRC over the record, says "and it was written completely and has not changed since": a record half updated when the reset came, or one with a flipped bit, still has the right magic but fails the check. With both, the code keeps a record that survived a reset and rebuilds one that did not.