---
title: Bootloaders and firmware updates
heading: Replacing a device's program in the field without ever leaving it unable to start
eyebrow: C12 · Lesson 44 · Bootloaders and firmware updates
xp: 40
---

::: hook
Every device shipped with a bug needs a way to receive new firmware, often over a serial link, USB or radio, from a user who will unplug it at the worst moment. The program that makes this possible is the **bootloader**: a small, rarely changed piece of code at the reset address that decides which application to run, checks that it's intact, and can rewrite the rest of the flash. Lesson 43's rules for flash apply with higher stakes: erasing takes whole pages and tens of milliseconds, and a power cut halfway through an erase must not leave a device that can't boot. The standard answer is two copies of the application and a commit flag written last.
:::

::: play
- The time to update a 200 KB image, split into transfer, erase and programming, against the link's speed in bits per second. The flash has 4 KB pages that take 20 ms to erase and 256-byte rows that take 0.5 ms to program.
- Over a slow UART, transfer dominates; over USB or a fast link, the flash itself becomes the limit, about 1.4 s however fast the data arrives.
:::

```sim plot
view: graph
x: b = 9600..12000000 log
y: t = 0.1..300 log
slider: K = 32..512 step 16 = 200
plot: K*1024*10/b + ceil(K/4)*0.02 + K*4*0.0005 | label: total, s
plot: K*1024*10/b | dashed | color: ch2 | label: transfer, s
plot: ceil(K/4)*0.02 + K*4*0.0005 + 0*b | color: ch3 | label: erase and program, s
readout: at 115 200 baud, s = K*1024*10/115200 + ceil(K/4)*0.02 + K*4*0.0005
```

::: predict
## A device has one application slot. Its bootloader erases the slot and then writes the new image as it arrives over a radio link. Power fails halfway through. What happens at the next reset?

- [ ] The old application runs
- [ ] The new application runs, missing its second half
- [x] There's no valid application; unless the bootloader checks for that and waits for a new download, the device is dead
- [ ] The flash restores itself

::: reveal
The old image was erased before the new one was complete, so neither exists. A bootloader that jumps blindly to the slot executes garbage. A careful one verifies a checksum before jumping and stays in update mode if it fails, which saves the device, but only if the update channel is still reachable. Designs that can't risk that keep two slots, so a complete, verified image always exists.
:::
:::

::: nameit
## What a bootloader does

At reset, the bootloader runs first. It:

1. checks whether an update is requested (a flag in flash, a button held at power-up, a command over the link);
2. if so, receives the new image, erasing and programming flash page by page;
3. verifies the application's integrity, with a CRC (lesson 33) or, for **secure boot**, a cryptographic signature checked against a public key stored in the bootloader;
4. sets the processor's vector table and stack pointer for the application, and jumps to it.

The bootloader is kept small and almost never updated itself, because a failed bootloader update is the one mistake that can't be repaired in the field.

## Flash in practice

Flash erases in pages (often 1 to 128 KB) to all 1s, programs in smaller rows or words, and endures 10 000 to 100 000 erase cycles. An update of $S$ bytes takes about

$$t \approx \frac{10S}{\text{baud}} + \left\lceil\frac{S}{P}\right\rceil t_{erase} + \frac{S}{R}t_{prog}$$

for a UART with 10 bits per byte, page size $P$ and row size $R$.

## A/B updates

Divide the application area into two slots. The bootloader runs whichever slot is marked active. An update writes the inactive slot, verifies it, and only then flips a small **commit record** to mark it active, one atomic write as in lesson 43's power-safe records. A power failure at any moment leaves at least one valid, committed image. Many systems add a **trial boot**: the new image must confirm itself (for example, after its self-test passes) within a few boots, or the watchdog's resets (lesson 41) make the bootloader roll back. The cost is flash: each slot can be only half the space left after the bootloader and records.

## Linking for a bootloader

The application is linked to start at its slot's address, not at the reset vector, with its own vector table there. On processors that can relocate the vector table, the bootloader points it at the application before jumping; on others, the bootloader forwards interrupts.
:::

::: example
## A microcontroller has 512 KB of flash. The bootloader takes 32 KB and the commit records 4 KB. How large can an application be with A/B slots, and with a single slot?

::: solution
1. **Space left for the application.**
   $$512 - 32 - 4 = 476\ \text{KB}$$
2. **A/B slots.** Two slots share it, 238 KB each.
3. **A single slot.** It could use all 476 KB, twice as much, which is the price of never being unbootable.
4. **Compromises.** Some designs compromise with compression or with a small recovery image instead of a full second copy.

**Answer:** 238 KB with A/B slots, and 476 KB with a single slot.
:::
:::

::: example
## A 200 KB image is sent over a 115 200-baud UART into flash with 4 KB pages (20 ms erase) and 256-byte rows (0.5 ms to program). How long does the update take?

::: solution
1. **Transfer.**
   $$\begin{aligned} t &= \frac{200 \times 1024 \times 10}{115\,200}\ \text{s} \\ &= 17.8\ \text{s} \end{aligned}$$
2. **Erase.** $\lceil 200/4\rceil = 50$ pages:
   $$50 \times 20\ \text{ms} = 1.0\ \text{s}$$
3. **Program.** 800 rows:
   $$800 \times 0.5\ \text{ms} = 0.4\ \text{s}$$
4. **Total.** About 19.2 s, almost all of it the link.
5. **Over USB.** Over a 12 Mb/s USB link the transfer would take 0.17 s and the flash's 1.4 s would dominate.

**Answer:** about 19.2 s, almost all of it the link.
:::
:::

::: example
## A device runs a bootloader that checks a CRC-32 over the 200 KB application at every boot, at about 10 cycles per byte on a 48 MHz core. How much does that add to start-up, and how often can it be updated if each update erases each page of the slot once and the flash endures 10 000 cycles?

::: solution
1. **CRC time per boot.**
   $$\begin{aligned} t &= \frac{204\,800 \times 10}{48 \times 10^6}\ \text{s} \\ &= 43\ \text{ms} \end{aligned}$$
   usually acceptable.
2. **Erases per update.** Each update erases every page of one slot once; alternating between two slots, each slot is erased on every second update.
3. **Updates the flash supports.** About 20,000, far more than a product will ever receive.
4. **Where endurance matters.** Endurance is a concern for data logging (lesson 43), and hardly ever for firmware.

**Answer:** 43 ms per boot, and about 20,000 updates.
:::
:::

::: check
given: F = 256 | 512 | 1024; B = 16 | 32 | 64; r = 4 | 8
answer: (F - B - r)/2
unit: KB
tolerance: 0.5%

## A device has {F} KB of flash, a {B} KB bootloader and {r} KB of records. How large can each of two A/B application slots be?

::: right
Right. Half of what's left: {answer}.
:::

::: misses
- [F - B - r] That's a single slot. Two slots split it.
- [F/2] Subtract the bootloader and records first.
- [any] Not yet. $(F - B - r)/2$.
:::
:::

::: check
given: S = 64 | 200 | 480; b = 9600 | 115200 | 921600
answer: S*1024*10/b
unit: s
tolerance: 0.5%

## How long does it take to send a {S} KB image over a UART at {b} baud with 10 bits per byte?

::: right
Right. $10S/\text{baud}$ = {answer}.
:::

::: misses
- [S*1024*8/b] A UART byte takes 10 bits on the wire: start, 8 data, stop.
- [S*1000*10/b] 1 KB is 1024 bytes here.
- [any] Not yet. Bytes × 10 bits ÷ baud.
:::
:::

::: check
given: S = 100 | 210 | 301; P = 8 | 16 | 32; te = 20 | 40
answer: ceil(S/P)*te/1000
unit: s
tolerance: 0.1%

## Erasing room for a {S} KB image in flash with {P} KB pages, each taking {te} ms, takes how long?

::: right
Right. $\lceil S/P\rceil$ pages × {te} ms = {answer}.
:::

::: misses
- [S/P*te/1000] Pages erase whole: round up.
- [any] Not yet. Count whole pages, then multiply.
:::
:::

::: check
given: S = 64 | 256; c = 4 | 10 | 20; f = 16 | 48 | 200
answer: S*1024*c/(f*1e6)*1e3
unit: ms
tolerance: 0.5%

## A bootloader checks a CRC over {S} KB at {c} cycles per byte on a {f} MHz core. How long does that take?

::: right
Right. {answer} at every boot.
:::

::: misses
- [S*1024/(f*1e6)*1e3] Multiply by the {c} cycles each byte costs.
- [any] Not yet. Bytes × cycles per byte ÷ clock.
:::
:::

::: check
kind: parts
given: E = 10000 | 100000; n = 2 | 4

## A data logger shares its flash pages with firmware updates. Each update erases every page of one A/B slot once; the flash endures {E} erase cycles per page.

::: part
answer: 2*E
tolerance: 0.5%

### How many updates can the device take before a slot's pages wear out, alternating slots?

::: misses
- [E] Each slot is erased only on every second update.
- [any] Not yet. Each slot sees half the updates.
:::
:::

::: part
answer: 2*E/(n*365)
tolerance: 0.5%

### At {n} updates per day, how many years is that?

::: misses
- [E/(n*365)] Alternating slots doubles the count.
- [any] Not yet. Updates ÷ updates per year.
:::
:::

::: right
Right. Firmware updates almost never wear out flash; frequent small data writes do.
:::
:::

::: check
kind: choice

## In an A/B update, why is the commit record written only after the new image has been fully written and verified?

- [x] So that at every moment some committed image is complete and valid; a power cut before the commit leaves the old image active
- [ ] Because flash can't be written while an image is being verified
- [ ] To save erase cycles
- [ ] Because the bootloader can only read the commit record at reset

::: right
Right. The commit is the single atomic step that switches images. Before it, the old image is still the active one; after it, the new image is complete and verified. There's no moment in between.
:::

::: misses
- [2] Writing and verifying could overlap; the order is about safety.
- [3] The order doesn't change the number of erases.
- [4] When it's read doesn't matter; what matters is that it changes only once the new image is ready.
:::
:::

::: check
kind: python
given: seed = 1 | 2 | 3

## Simulate power failures during A/B updates. State: two slots, each `None` (erased), `'partial'`, or a version number; and `active`, the committed slot index. An update to version `v` runs these steps in order on the inactive slot: `erase` (slot becomes None), `write` (becomes 'partial'), `finish` (becomes v), `commit` (active switches to it). Write `update(state, v, fail_at)` that performs steps until index `fail_at` (0 to 4; 4 means no failure), and `boot(state)` returning the version that would run, or `None` if the active slot isn't a complete version. Starting from slots `[1, None]`, active 0, apply 200 updates with `fail_at = rng.randrange(5)` (`rng = random.Random(seed)`) and version numbers 2, 3, ...; set `bricked` (how many times `boot` returned None after an update) and `final` (the running version at the end).

```python starter
import random
bricked, final = 0, 1
```

```python solution
import random
def update(state, v, fail_at):
    slots, active = state['slots'], state['active']
    other = 1 - active
    steps = ['erase', 'write', 'finish', 'commit']
    for i, s in enumerate(steps):
        if i >= fail_at:
            break
        if s == 'erase': slots[other] = None
        elif s == 'write': slots[other] = 'partial'
        elif s == 'finish': slots[other] = v
        else: state['active'] = other
def boot(state):
    v = state['slots'][state['active']]
    return v if isinstance(v, int) else None
rng = random.Random(seed)
state = {'slots': [1, None], 'active': 0}
bricked, v = 0, 2
for _ in range(200):
    update(state, v, rng.randrange(5))
    if boot(state) is None: bricked += 1
    if boot(state) == v: v += 1
final = boot(state)
```

```python tests
import random
rng = random.Random(seed)
st = {'slots': [1, None], 'active': 0}
v, br = 2, 0
for _ in range(200):
    f = rng.randrange(5)
    o = 1 - st['active']
    for i, s in enumerate(['erase', 'write', 'finish', 'commit']):
        if i >= f: break
        if s == 'erase': st['slots'][o] = None
        elif s == 'write': st['slots'][o] = 'partial'
        elif s == 'finish': st['slots'][o] = v
        else: st['active'] = o
    b = st['slots'][st['active']]
    b = b if isinstance(b, int) else None
    if b is None: br += 1
    if b == v: v += 1
assert bricked == br == 0, "With A/B slots and a final commit, no failure point should leave the device unbootable."
assert final == (st['slots'][st['active']]), f"The device should end on version {st['slots'][st['active']]}."
```

::: right
Right. Whatever step the power fails at, the active slot always holds a complete version, so the count of unbootable states is zero, and interrupted updates simply leave the old version running until a retry succeeds.
:::
:::

::: explain
## A product's firmware update over Bluetooth occasionally fails when users walk away from their phones mid-update. Some devices come back up on the old firmware; a few never boot again. Explain what the bootloader must be doing differently in the two cases, and how to make every device recover.

::: model
The devices that recover must be using an update scheme in which the old image stays intact and active until the new one is fully received and verified: writing a second slot, or at least verifying before overwriting, and switching with a single commit at the end. When the link drops, the commit never happens and the bootloader runs the old image. The devices that never boot again must have erased or overwritten the only application before the transfer completed, and their bootloader then either jumps into an incomplete image or can't reach the update channel. To make all of them recover, use A/B slots with a final atomic commit (or a protected recovery image), have the bootloader verify a CRC or signature before every jump and fall back to the other slot or to update mode on failure, and add a trial-boot rule so a new image that crashes repeatedly is rolled back by the watchdog.
:::
:::

::: practice

::: check
given: F = 128 | 2048; B = 8 | 48
answer: (F - B)/2
unit: KB
tolerance: 0.5%

## With {F} KB of flash and a {B} KB bootloader (no records), how big can each A/B slot be?

::: misses
- [F - B] Two slots share the space.
- [any] $(F - B)/2$.
:::
:::

::: check
given: S = 50 | 500; b = 57600 | 460800
answer: S*1024*10/b
unit: s
tolerance: 0.5%

## How long does a {S} KB transfer take at {b} baud?

::: misses
- [S*1024*8/b] Count 10 bits per byte.
- [any] $10S/\text{baud}$.
:::
:::
:::
