Bootloaders and OTA

A firmware update rewrites the only program that runs the device. Cut the power at the wrong moment and you have a brick. Pick a design, pull the plug, and see which ones survive.

Learn what a bootloader does, what makes a firmware image valid, how dual banks, swaps, test and confirm, signatures and rollback keep a device alive, and how the bytes reach it over UART, USB, BLE and CAN.

Choose a design, then drag the cut slider along the update. Watch the two flash slots and read the verdict. Then we build, piece by piece, every part of a safe update: the jump, the image, the flash rules, the swap, the trial boot, the signature and the link.

You need a rough idea of what flash memory is (memory that keeps its bytes with the power off) and a little C for the code. We build the rest from zero.

Part of the series Firmware from Zero to Expertise. Built from primary sources: the MCUboot design document, the Memfault Interrupt DFU cookbook, the USB DFU 1.1 specification and the nRF52840 product specification.

Pull the plug

0.0 s

A model, not real silicon. The image is 256 kB (64 pages of 4 kB). Erase and write times come from the nRF52840 product specification (85 ms per page erase and 41 µs per 32-bit word write, both listed as limits). The 20 s to receive the image is illustrative, a link at 12.8 kB/s.

Chapter 0

The Update That Can Brick

See why rewriting a device’s only program is the riskiest thing it ever does, and what a brick really is

A smart thermostat hangs on a bedroom wall. At 3 a.m. it starts a firmware update. Halfway through, a storm cuts the power for two seconds. The power returns. The screen stays black, and the thermostat never starts again.

Nothing broke in the hardware. The chip is fine. What broke is the firmware: the program stored in the chip’s flash (memory that keeps its bytes when the power is off). The update erased the old program and had not finished writing the new one. Now the chip has nothing to run.

People call a device in that state a brick, because it is as useful as a brick. This lesson is about never building one.

The cast: image, bootloader, app

Three words carry the whole lesson. An image is a program packed as bytes, ready to be copied into flash. The app is the program that does the device’s job, such as reading a temperature and driving a screen. The bootloader is a small program that runs first, every time the chip starts. It decides which app to run, and it can also install a new one.

An update that arrives wirelessly is called OTA, short for over the air. The wider name for any way of replacing firmware is DFU, device firmware update. The link can be a wire, a USB cable, a radio or a car network. The risk is the same on every link.

Why the update is the dangerous moment

Normal operation never writes the app’s own flash. An update does exactly that. It must erase the old bytes and write new ones, and erasing and writing flash is slow. Chapter 3 gives the numbers: on the nRF52840 chip, one 4 kB page can take up to 85 ms to erase.

There is a second problem. On many chips the processor pauses while flash is being erased or written, if it runs its code from that same flash. The Nordic product specification for the nRF52840 says so for its flash controller. So the app cannot easily rewrite itself while it runs. Something else has to do the work, and that something is usually the bootloader.

Now count the time. A 256 kB image is 64 pages of 4 kB. Erasing them all takes 64 × 85 ms = 5.44 s. Then the new bytes must arrive and be written. Over a slow link that takes tens of seconds. For that whole span, the flash holds something that is neither the old program nor the new one.

Measure the danger window

Two bars show the same update on the same time scale. Red marks the moments when a power cut leaves the device with no working app. Drag the image size and the link speed.

256 kB
12.8 kB/s

A model. Erase uses 85 ms per 4 kB page (nRF52840 product specification, a listed limit). Receiving the image is size divided by link speed, illustrative. The two-bank flag write is one 32-bit word at 41 µs. Hash checking takes 0.3 s here, illustrative.

Look at the in-place bar. Every second of it is red. A cut at any point leaves a half-erased or half-written program. The two-bank bar is green almost everywhere, because the old program stays whole in its own slot while the new one arrives next to it. Only the final switch from old to new is a risk, and that switch is a single 41 µs word write.

That is the whole game. A safe update keeps one complete, checkable image on the device at every instant, and makes the switch from old to new as small a step as the hardware allows.

Two kinds of brick

A soft brick means the app is gone but the bootloader still runs. A person with a cable can often feed it a new image. A hard brick means the bootloader itself is damaged, so the chip cannot even accept a new image over the cable. A good design makes the bootloader tiny, rarely rewritten and, where the chip allows it, write-protected.

In this lesson “brick” means the soft kind: after the cut, no valid app exists and nothing on the device can start one.

The road

We build a safe update piece by piece. Each chapter adds one part, and the hero at the top of the page uses all of them.

  1. What a bootloader does: reset, the vector table, and the jump to the app.
  2. What makes an image valid: the header, the hash, and the commit rule.
  3. Flash rules and the one safe write: erase before write, and the atomic flag.
  4. Four update designs, one power cut: in place, stage and copy, two banks, swap.
  5. Swapping without losing either image: sectors, scratch and the status record.
  6. Test, confirm and roll back: a new image on trial.
  7. Trust: signatures, keys and version counters.
  8. Getting the bytes in: UART, USB DFU, BLE and CAN.
  9. Field guide: numbers, checklist, code and links.

If the word flash is new, read Non-volatile storage and the write that lost power first. It covers the physics of flash in more depth. The security side of this lesson continues in Secure boot and device security.

A worked example: how often does the storm hit?

Take a fleet of 10,000 thermostats. Suppose each one loses power about once in 2,000 hours. That rate is illustrative, not measured. One hour is 3,600 s, so 2,000 hours is 7,200,000 s.

  1. Chance for one device. The in-place danger window is 25.4 s. So the chance that a cut lands inside it is 25.4 / 7,200,000, about 3.5 in a million.
  2. Chance for the fleet. Multiply by 10,000 devices: about 0.035 bricks per rollout.
  3. Over a year. Fifty rollouts give about 1.8 bricked devices.
  4. The two-bank design. The window is 41 µs, so the same sum gives about 0.00000006 bricks per rollout, six in a hundred million.

That looks small, and it is the wrong comfort. A truck visit to fix one thermostat costs far more than the device. And the real rate is not random. Updates run when the battery is low, the radio is busy and the supply sags, so cuts cluster inside the window.

The failure, as symptom, measurement and fix

Symptom. After a rollout, a few devices come back dead, and almost all of them were in poor power conditions.

Measurement. Log the battery voltage at the start of every update, and log whether the update finished. Plot dead devices against that voltage. You will see the dead ones cluster at the low end.

Fix. Two fixes work together. Refuse to start an update below a battery threshold. And choose a design whose danger window is tiny, so the threshold is a second line of defence and not the only one.

On real hardware. Take an nRF52840 DK. Toggle one GPIO pin high when your update code starts erasing and low when the last word is written. Probe the pin with a logic analyzer. The pulse width is your danger window. Repeat with the update streamed in place and with it staged in a second slot, and compare.
An update erases the only copy of the app, then starts writing the new one. The power fails halfway. What is the best description of the device afterwards?

Chapter 1

What a Bootloader Does

Follow the reset, find the app’s first two words, and jump to the program

You press the power button on a laptop. Before any window appears, a small program wakes up, finds the operating system on disk and hands over control. A microcontroller does the same thing in a few microseconds, with far less ceremony.

The idea is simple. The chip must start somewhere, and that place is fixed by the hardware. If that place holds a small, trusted program, that program can choose what to run next. That small program is the bootloader.

What the chip does at reset

This lesson uses an Arm Cortex-M chip, the kind in an STM32 or an nRF52840. When the chip leaves reset (the moment power arrives or the reset pin is released), the processor reads two 32-bit words from the very start of the address space. The first word is the starting value of the stack pointer, the register that tracks where the program’s stack lives in RAM. The second word is the address of the reset handler, the first function to run.

Those two words are the top of the vector table: a list of 32-bit addresses, one for each event the processor can react to. Entry 0 is the stack pointer. Entry 1 is reset. Later entries are for faults and interrupts. Reset to main() walks through this table in full.

Because the processor reads address 0 at reset, the bootloader lives at address 0. It owns the first slice of flash. The app sits right after it.

The jump, step by step

An app also has a vector table, because it is a full program built to run on its own. Its first two words are its stack pointer and its reset handler. The bootloader reads those two words and jumps. The Memfault Interrupt article on writing a bootloader from scratch shows this on a SAMD21 chip with a 16 kB bootloader at 0x00000000 and the app at 0x00004000. We use the same shape.

  1. Read the app’s two words. The stack pointer is at the app base, the reset handler is at base + 4.
  2. Check the app first. Chapter 2 explains how. Never jump into bytes you have not checked.
  3. Shut down what you started. If the bootloader turned on a serial port or a timer, turn it off. The app expects a quiet chip.
  4. Point the vector table at the app. Write the app base into VTOR, the vector table offset register, at address 0xE000ED08.
  5. Load the stack pointer and branch. One instruction writes the main stack pointer. The next one jumps to the reset handler.

Step 4 is the one people forget. The processor looks up every interrupt in the table that VTOR names. At reset VTOR points at address 0, the bootloader’s table. If it still does after the jump, the first timer tick runs the bootloader’s handler, not the app’s. The app crashes in a way that looks random.

Step through the jump

The bar is flash. The bootloader owns the first 16 kB and the app starts at 0x4000. Press Step to run one stage at a time. Turn off Set VTOR to see what the forgotten step does.

A model of the sequence. The addresses are illustrative: SP 0x20040000 is the top of the nRF52840’s 256 kB of RAM; the handler addresses are made up. The 16 kB bootloader size follows the Interrupt article’s SAMD21 example. Entries other than the stack pointer have bit 0 set, the Thumb flag.

Watch the program counter, PC. It starts in the bootloader’s reset handler, wanders through the bootloader’s code, and ends in the app’s reset handler. The address ends in 1 (0x4C1D, not 0x4C1C). That bit is the Thumb flag. Cortex-M chips run only Thumb code, and the manual requires every handler entry in the table, except entry 0, to have bit 0 set.

The same thing in C

Here is the whole jump. The function is naked, so the compiler adds no prologue and the stack pointer is not touched before we replace it.

c#define APP_BASE  0x00004000u
#define VTOR     (*(volatile uint32_t *)0xE000ED08u)

static void start_app(uint32_t pc, uint32_t sp) __attribute__((naked));
static void start_app(uint32_t pc, uint32_t sp) {
    __asm volatile("msr msp, r1\n"   /* r1 = sp: load the main stack pointer */
                     "bx  r0\n");      /* r0 = pc: branch to the reset handler */
}

void boot_app(void) {
    const uint32_t *app = (const uint32_t *)APP_BASE;
    uint32_t app_sp    = app[0];            /* entry 0: initial stack pointer */
    uint32_t app_reset = app[1];            /* entry 1: reset handler, bit 0 set */
    uart_deinit();                          /* hand over a quiet chip */
    VTOR = APP_BASE;                         /* interrupts now use the app's table */
    start_app(app_reset, app_sp);
}

Two details deserve care. First, the vector table must sit at an address aligned to its size, rounded up to a power of two, with a minimum of 128 bytes. The Interrupt example has 44 entries, so 176 bytes, which rounds up to a 256-byte alignment. Second, the Cortex-M0 has no VTOR at all, so on that core the bootloader must copy the app’s table to RAM or the app must be linked to the address the hardware expects.

One program, two linker scripts

The bootloader and the app are separate programs. Each has its own linker script, the file that tells the build tool where in memory each piece of code goes. The bootloader’s script puts code at 0x0, length 0x4000. The app’s script puts code at 0x4000. Both put the vector table first in their region. A shared header file with the two base addresses stops them from drifting apart.

A worked example: read the two words

Say the app image starts at 0x4000 and a hex dump shows these eight bytes: 00 00 04 20 1D 4C 00 00. Cortex-M chips are little endian, so the least significant byte comes first.

  1. Word 0. Bytes 00 00 04 20 read as 0x20040000. That is the top of 256 kB of RAM that starts at 0x20000000. A stack grows down from there.
  2. Word 1. Bytes 1D 4C 00 00 read as 0x00004C1D. Clear bit 0 and the code is at 0x4C1C, which is inside the app.
  3. The Thumb flag. Bit 0 is 1, so the branch stays in Thumb mode. A branch to an even address would fault.

Now you can write a cheap check that stops a bad jump. The stack pointer must point into RAM. The reset address must lie inside the app region and have bit 0 set. If either test fails, do not jump. Show the rescue path instead.

The failure, as symptom, measurement and fix

Symptom. The app runs for a moment and then dies in a hard fault, but only when started from the bootloader. Started alone from a debugger, it works.

Measurement. Stop in the fault handler and read the stacked program counter. If it points below 0x4000, the processor ran a bootloader handler. Print VTOR. If it reads zero, you have found the bug.

Fix. Write VTOR before the jump, or as the first line of the app’s reset handler, and align the app’s table as the manual requires. Also disable interrupts in the bootloader before you switch tables, so no interrupt arrives between the two steps.

On real hardware. On an STM32 Nucleo, link a blink app at 0x08004000 (STM32 flash starts at 0x08000000). Open GDB, stop at the jump, and print $msp and *(uint32_t*)0xE000ED08 before and after. Then comment out the VTOR write and watch the first SysTick interrupt land in the bootloader.
A bootloader jumps to an app with the correct stack pointer and reset handler but never writes VTOR. The app starts, then crashes at its first timer interrupt. Why?

Chapter 2

What Makes an Image Valid

Read the header, check the hash, and see why a half-written image must always look invalid

You copy a large file to a USB stick and pull the stick out too early. The file name is there. The icon looks normal. But the last third of the file is empty, and when you open it the program crashes.

A bootloader has the same problem. Flash can hold a file that looks like firmware and is not. If the bootloader jumps into half a program, it runs garbage. So before it jumps, it must answer one question: is this image complete and unchanged?

An image is a header, a payload and a trailer

The payload is the program itself, the bytes that go into flash. A bare payload tells the bootloader nothing about its own length, version or health. So the build tool wraps it with extra data. MCUboot, an open-source bootloader for small chips, uses this layout.

  1. Header, 32 bytes. It starts with a magic number, a fixed value that says “this is an image”. MCUboot uses 0x96f3b83d. Then come the load address, the header size, the payload size (ih_img_size), flags and the version: major, minor, revision and build number. All fields are little endian.
  2. Payload. The app, starting with its vector table. The header size field says where the payload starts.
  3. Trailer of TLVs. A TLV is a type, a length and a value, one after another. It begins with an info header whose magic is 0x6907. It sits right after the payload, at hdr_size + img_size. One entry is required: type 0x10, the SHA-256 hash.

A hash turns any amount of data into a short fixed-size fingerprint. SHA-256 gives 32 bytes. Change one bit of the input and the fingerprint changes completely. MCUboot’s hash covers the header, the payload and the protected TLVs. The build tool computes it. The bootloader computes it again from what is in flash and compares.

What the hash catches

The hash catches three different failures with one test. A power cut during the write leaves the tail of the image unwritten, so the recomputed hash differs. A flipped bit in flash, from wear or damage, changes the hash. A wrong file that happens to start with the right magic fails too, unless it is exactly the image that was signed.

The magic number alone catches almost nothing. A header can be fully written while the payload is empty. That is why the bootloader checks the cheap things first (magic, sizes) and the hash last.

Try it. The strip below is one small image of 168 bytes: a 32-byte header, a 96-byte payload and a 40-byte trailer. The hash is a real SHA-256 computed in your browser.

Check the image

Each cell is a byte in flash. Hollow cells are still erased (0xFF). Drag Bytes written to cut power during the write, flip a bit, or change the order the header is written.

168 of 168

A model of the MCUboot layout, scaled down: the real header is 32 bytes, the real payload is hundreds of kilobytes. The magic 0x96f3b83d, the TLV info magic 0x6907 and the SHA-256 type 0x10 are from the MCUboot design document. The hash is real SHA-256 over the header and payload.

Start with everything written. All checks pass. Now drag the slider down by a few bytes. The hash check fails, because the tail of the trailer is missing. Drag further and the TLV is missing too. With Header written last on, the header itself disappears first, so the very first check, the magic, already fails. The bootloader never has to hash anything.

Why write the header last

The Memfault Interrupt DFU cookbook uses one rule that makes this easy: write the payload without the header, verify it, then write the header to commit. A partial update has no valid header, so the loader rejects it. The cookbook states the matching rule for its header magic: “If the bytes are not there, the image is not valid!”

The same rule works in reverse for removal. To invalidate an image, zero its header. That is one small write. Erasing 256 kB would take over five seconds and leave the slot half-erased for all that time.

The cost of checking

Hashing the whole image on every boot takes time. The cookbook notes that CRC checks on every boot can slow startup a lot. MCUboot has an option that stores the result of the check in the slot’s trailer so later boots skip it, and its own document warns that this lowers security, because a changed slot would not be checked again. A common compromise is to hash fully after an install and use a cheaper check on later boots. The choice is yours; the cost is real.

One more field matters later. The header carries the version. Chapter 6 uses it to choose between two images, and Chapter 7 uses it to refuse old ones.

c/* the 32-byte MCUboot header (field names from the MCUboot design document) */
struct image_header {
    uint32_t ih_magic;           /* 0x96f3b83d */
    uint32_t ih_load_addr;
    uint16_t ih_hdr_size;        /* where the payload starts */
    uint16_t ih_protect_tlv_size;
    uint32_t ih_img_size;        /* payload length */
    uint32_t ih_flags;
    struct { uint8_t major, minor; uint16_t revision; uint32_t build_num; } ih_ver;
    uint32_t _pad1;
};

bool image_valid(const uint8_t *slot, uint32_t slot_size) {
    const struct image_header *h = (const void *)slot;
    if (h->ih_magic != 0x96f3b83d)                return false;  /* cheap */
    if (h->ih_hdr_size + h->ih_img_size > slot_size)   return false;  /* cheap */
    const uint8_t *tlv = slot + h->ih_hdr_size + h->ih_img_size;
    if (rd16(tlv) != 0x6907)                      return false;  /* TLV info magic */
    const uint8_t *want = find_tlv(tlv, 0x10);           /* the SHA-256 entry */
    uint8_t got[32];
    sha256(slot, h->ih_hdr_size + h->ih_img_size, got);
    return want && memcmp(got, want, 32) == 0;           /* expensive, last */
}

A worked example: where everything sits

Take the small image in the device: a 32-byte header, a 96-byte payload and a trailer. Walk through what the bootloader reads.

  1. Header. Bytes 0 to 3 hold 3d b8 f3 96, which is the magic 0x96f3b83d in little-endian order. Bytes 12 to 15 hold the payload size, 96.
  2. Trailer position. It starts at header size plus payload size: 32 + 96 = 128.
  3. Trailer size. The 4-byte info header (magic 0x6907 and a total length) plus one TLV: a 4-byte entry header and the 32-byte hash. That is 4 + 4 + 32 = 40 bytes.
  4. Hash input. The hash covers bytes 0 to 127: the header and the payload. The SHA-256 function reads them in 64-byte blocks, so 128 bytes plus its padding takes 3 blocks. A real 256 kB image takes 4,097 blocks.
  5. Total. 32 + 96 + 40 = 168 bytes, the number on the slider.

The failure, as symptom, measurement and fix

Symptom. Every update on one batch of boards fails at the last step, while the same file works on the bench.

Measurement. Read the slot back with the debugger. Hash it on your computer and compare it to the hash in the trailer. Find the first byte that differs. If it is the last few bytes of the payload, the final partial word was never written.

Fix. Flash writes are whole words (Chapter 3). Pad the image to the write alignment before you sign it, and make the transfer code flush a partial last word. The imgtool --align option exists for this reason.

On real hardware. Build any app with Zephyr and MCUboot on an nRF52840 DK. Sign it with imgtool sign --header-size ... --align 4 --version 1.0.0 --slot-size ... (these flags are in the MCUboot imgtool documentation). Dump the first 32 bytes of the result with a hex tool and find 3d b8 f3 96, the magic in little-endian order. Then change one payload byte and watch the bootloader refuse the file.
Power fails while the last 20% of a payload is being written. The header and magic number are already in flash. Which check finds the problem?

Chapter 3

Flash Rules and the One Safe Write

Learn how flash accepts writes, and find the single small write that can commit an update

Think of a whiteboard that you can only write on in black marker, and that you can only wipe clean all at once. You can add marks to any spot. You cannot rub out one mark. To change a letter, you wipe the whole board and write it again.

Flash memory works the same way. Every update design in this lesson comes from these rules, so it pays to know them exactly. Non-volatile storage and the write that lost power covers the physics in more depth. Here we need only what shapes an update.

Erase sets bits to 1, writes only clear them

A flash bit is a stored 0 or 1. When flash is erased, every bit becomes 1, so every byte reads 0xFF. The Interrupt bootloader article pads unused flash with 0xFF for this reason. A write (also called a program) can then change a bit from 1 to 0. It can never change 0 back to 1. Only an erase does that.

So writing a new value over an old one gives the bitwise AND of the two. Write 0xA5A5A5A5 over 0x0000FFFF and you get 0x0000A5A5, not what you asked for.

Erase works on a whole page, the smallest erasable block. On the nRF52840 a page is 4 kB. Write works on one 32-bit word at a time. The nRF52840 product specification says only full 32-bit words can be written. To change fewer bits, write a word with 1s in every bit you want to keep.

Erase and write are slow, and the CPU may wait

The same product specification lists the timing limits. A page erase takes up to 85 ms. A 32-bit word write takes up to 41 µs. A page survives about 10,000 erase cycles. A word can be written only twice between erases. And the specification says the CPU is halted if it runs code from flash while the flash controller erases or writes.

Now do the sum for a 256 kB image, step by step.

  1. Pages. 256 kB divided by 4 kB is 64 pages.
  2. Erase. 64 pages at 85 ms is 5.44 s.
  3. Words. 256 kB is 65,536 words of 4 bytes.
  4. Write. 65,536 words at 41 µs is 2.69 s.
  5. Total flash time. 5.44 s + 2.69 s is about 8.1 s, at the specified limits.

These are worst-case limits, and typical parts are faster. The point is the shape: erase costs twice as much as write, and both are far slower than reading. For eight seconds the flash is busy, and for part of that time the CPU may stand still.

Wear

At 10,000 erase cycles per page, a page that is rewritten once a day lasts about 27 years. A page that is rewritten every update, ten times a day, lasts under three. Update designs that erase the same helper area on every step wear it out first. Chapter 5 returns to this.

Write one flash word

The 32 cells are one word. A filled 1 is erased. Press a write button and see the result. Then write and cut power halfway. A question mark is a bit that did not finish.

A model. The AND rule and the 85 ms and 41 µs limits are from flash behaviour and the nRF52840 product specification. Which bits settle after a power cut is illustrative: real partly programmed bits can read either way and can change later.

Try this order. Press Write 0x0000FFFF, then Write 0xA5A5A5A5. The word reads 0x0000A5A5, because the second write could clear bits but not set them. A third write counts against the limit of two writes between erases, and the read-out says so. Press Erase and the word is 0xFFFFFFFF again.

The one write you can trust

Now press the power-failure button. Some bits finish and some show a question mark. This is the key fact for the whole lesson: a write that loses power is not “done” or “not done”. Some bits changed and some did not, and the unsettled ones can read as 1 on one boot and 0 on the next.

That seems to leave no safe step at all. But a single word write is as close as flash gets. It is short: 41 µs. The chance that power fails inside that window is tiny. And you can make the result checkable. If the commit marker is an exact pattern such as 0xC0DEC0DE, a half-written marker simply fails to match. The bootloader then treats the update as not committed and still has the old image.

So the safe pattern has three parts. First, never touch the running image. Second, write and check the new image completely. Third, flip one small marker, a word or two, to say “use the new one”. Every design in the next chapter is a variation on this.

A worked example: a flag that survives a cut

Design a flag word that says “install the new image”. The nRF52840 lets you write a word only twice between erases (Chapter 3), so plan the writes.

  1. Start. The word is erased: 0xFFFFFFFF. It means “nothing requested”.
  2. Request. Write 0xC0DE0000. The result is 0xC0DE0000 since all bits were 1. That is write number 1.
  3. Done. Write 0x00000000. The result is 0x00000000. That is write number 2, the last one allowed.
  4. Reset. An erase of the page brings it back to 0xFFFFFFFF.

Every state clears bits and never needs to set one. Compare the exact pattern, not a single bit. A half-written request such as 0xC0DE0001 matches neither state, so the bootloader treats it as not requested.

The failure, as symptom, measurement and fix

Symptom. After a brownout, the bootloader sometimes starts an install and sometimes does not, with no change in the code.

Measurement. Read the flag word a hundred times in a loop and log every distinct value. A word that was half written can return more than one value.

Fix. Never trust one bit. Compare the exact pattern. If the flag matches no valid state, erase its page and start again from the erased state. Store the complement next to the flag (~value) when you want a second cheap check.

On real hardware. On an nRF52840 DK, toggle a GPIO high before an NVMC page erase and low after. A logic analyzer shows the pulse: up to 85 ms. Do the same around one word write and compare it with 41 µs. Run the app from flash during the erase and watch the CPU stall, then move the erase routine into RAM and see the difference.
A flash word holds 0x0000A5A5. You write 0xFFFF00FF to it, with no erase. What does it hold afterwards?

Chapter 4

Four Update Designs, One Power Cut

Run the same update four ways and count which cuts leave you with a working device

Four engineers must ship the same 256 kB update to the same thermostat. Each one picks a different plan. The storm comes at 3 a.m., and it cuts power at a random moment in each of the four updates. Whose thermostat still works in the morning?

We have the pieces now: a bootloader that jumps (Chapter 1), an image that proves it is complete (Chapter 2), and flash that gives us only one small safe write (Chapter 3). A design is a way of arranging them. The hero at the top of the page already ran all four. This chapter takes them apart.

Design 1: write over the old image

The simplest plan has one slot. The bootloader receives the new image and writes it over the old one: erase the slot, then write the new bytes as they arrive.

It costs the least flash. It also has a danger window as long as the whole update, 25.4 s in our model. A cut at any moment in that window leaves a half-erased or half-written slot, and no other copy exists. The device has no valid app. Teams that ship this design keep the bootloader alive and give it a wired rescue mode, so a technician can recover the device. That works for a dev kit. It does not work for ten thousand thermostats in people’s homes.

Design 2: stage the image, then copy it

Now there are two slots. The new image first lands in the spare slot B while the old app sits untouched in slot A. The bootloader checks B with the hash from Chapter 2. Only then does it erase A and copy B into it.

While B is filling, a cut costs nothing: A still holds the old app. While A is being erased and rewritten, A is damaged, but B holds a complete, checked copy. At the next reset the bootloader sees that A is invalid and B is valid, and it copies again. The copy phase takes 5.44 s to erase plus 2.69 s to write, which is 8.1 s of a 33.9 s update. In that window the device heals itself. It never ends up with nothing.

The price is a spare slot as big as the app, and a bootloader that knows how to resume. There is a second, quieter price: after the copy, the old image is gone. You cannot roll back to it (Chapter 6).

Design 3: two banks and a flag

With two slots, you can skip the copy. The app is built to run from either slot. The new image goes into the idle slot, gets checked, and then one small flag changes, so the next reset starts the other slot. This is called A/B or dual-bank update.

The danger window is the flag write: 41 µs in our model, one 32-bit word, and a checkable exact pattern (Chapter 3). Some chips help in hardware. On STM32L4 parts the user manual describes a bit, FB_MODE in SYSCFG_MEMRMP, that maps the two flash banks in swapped order. MCUboot’s equivalent is its direct-xip mode: both slots are equal, and the bootloader runs the newest valid image in place.

The catch is code placement. An app that runs in place from two different addresses must either be position independent or be built twice, once for each slot. Some chips remap addresses, which makes the same build work in both banks.

Design 4: swap, with a record

The fourth plan keeps the app always in the same slot, the primary, so it is built and linked once. New images arrive in the secondary slot. To install, the bootloader swaps the two slots sector by sector, and writes a small status record as it goes. After a cut, the record says how far the swap got, and the bootloader resumes. Afterwards the old image sits in the secondary slot, ready for a way back.

The cost is time and flash wear: in our model the swap alone is 24.4 s, because each sector is erased and written three times. Chapter 5 explains the record.

Run the update, then cut it

Choose a design and press Play. The red line is the power. Press Cut now, or Random cut to let chance choose. The bars at the bottom show each design’s share of cuts by outcome.

The same model as the hero. The shares are by time: each phase counts for its duration, so a 41 µs flag write is a vanishingly small share. Your own random cuts are counted below the bars. Phase times use the nRF52840 limits (85 ms per page erase, 41 µs per word write) and an illustrative 20 s to receive the image.

Run the in-place design to the end and watch slot A. It goes blank, then fills. There is never a second copy. Switch to stage-and-copy and run it again. Slot B fills first, and when slot A is erased, B is already complete. Now try two banks: slot A never changes until the flag moves.

The comparison

DesignSlots of image sizeWhere a cut hurtsShare of cuts that brickOld image kept?
In place1Any moment of the update100%No
Stage, then copy2Erase and copy of A (8.1 s), heals from B0%No, A is overwritten
Two banks, flag2The flag write (41 µs)0%Yes, in the other bank
Swap with record2, plus scratch or one spare sectorThe swap (24.4 s), resumes from the record0%Yes, in the secondary slot

Read the third column as the thing you must test. Every safe design has a short moment that needs care, and a bootloader that recovers at the next reset. That second part is code, and code can be wrong. The way to check it is to cut power on purpose, thousands of times. Chapter 9 gives a test plan.

The Interrupt DFU cookbook shows a design in the same family: an immutable bootloader, a separate loader that checks and installs the app, and an updater program that can replace the loader itself. The bootloader never updates itself. That is a rule worth copying. The code that fixes everything else should change least.

A worked example: the flash budget

Take a chip with 1 MB of flash, the size of the nRF52840, and an app that is 256 kB.

  1. In place. One 256 kB slot plus a bootloader. About 750 kB stays free for data. It has no safety net.
  2. Stage, then copy. Two 256 kB slots, so 512 kB, plus a bootloader. About 500 kB stays free.
  3. Two banks. The same 512 kB, and the app must run from both addresses.
  4. Swap. Two slots plus a trailer in each, and a scratch sector in the scratch method.

The price of safety is about 256 kB of flash, a quarter of this chip. If your app grows to 400 kB, two slots no longer fit. That is a product decision to make early, because you cannot add a second slot after the board ships.

The failure, as symptom, measurement and fix

Symptom. The team runs 1,000 random power cuts on the bench and sees zero bricks. A year later, a few devices in the field are dead.

Measurement. Work out the odds. The two-bank flag write lasts 41 µs in an update of about 26 s. A random cut lands in it with probability 41e-6 / 25.7, about 1.6 in a million. A thousand random cuts will almost never hit it.

Fix. Do not rely on random cuts. Instrument the flash driver so a test can stop the run at a chosen flash operation: after the 1st erase, after the 2nd write, and so on, for every operation in the update. That sweep reaches the 41 µs moments with certainty.

On real hardware. Use an nRF52840 DK with a switchable supply, or a relay on the USB power line. Start a staged update from a script. Cut the supply at 100 random moments between the start and the reboot. Count how many boots end in v1, in v2 and in a dead board. Your design is only as safe as this count.
In the stage-then-copy design, power fails while slot A is being rewritten from slot B. Why does the device still recover?

Chapter 5

Swapping Without Losing Either Image

Swap two images sector by sector, and see how a status record lets an interrupted swap resume

Two people must swap the contents of two full suitcases, but they have only one spare chair. They cannot empty both suitcases at once. So they work in small steps: move a shirt to the chair, move a book across, move the shirt into the other case. If someone calls them away, they need a note that says where they stopped.

That note is the whole idea of this chapter. A swap bootloader does exactly this with flash sectors, and the note is a status record written into flash.

Why swap at all

The two-bank design in Chapter 4 needs an app that can run from two addresses. Swapping avoids that. The app always runs from the primary slot, so it is linked once. A new image arrives in the secondary slot. The bootloader swaps the two. The old image ends up in the secondary slot, which gives you a way back (Chapter 6).

MCUboot is an open-source bootloader built on this idea. Its design document describes more than one swap method. We follow the original, swap using scratch: a small extra flash area, at least as big as the largest sector being swapped, serves as the spare chair.

One sector, three steps

A sector here means the unit the bootloader erases at one time. For each sector, in order, the swap does this.

  1. Step 1. Copy the secondary sector (the new code) into scratch.
  2. Step 2. Copy the primary sector (the old code) into the secondary slot.
  3. Step 3. Copy scratch (the new code) into the primary slot.

After each step the bootloader writes one small record. The MCUboot document encodes the state of each sector with three one-byte records: state 0 is ff ff ff (nothing done), state 1 is 01 ff ff, state 2 is 01 02 ff and state 3 is 01 02 03. Each record is one write to a spot that was erased and still all ones, so it is the kind of small safe write Chapter 3 described. Each record is padded to the chip’s minimum write size.

Look at why a cut in the middle of a step is harmless. Every step reads from a place that is still intact and writes to a place whose old content is already saved. In step 2, the primary sector is the source, and it is untouched. The secondary sector is the target, and its original is safe in scratch. If power fails during step 2, the target is half-written, the record still says state 1, and the bootloader simply does step 2 again. The same holds for steps 1 and 3.

Cut the swap

Eight sectors, three steps each, 24 steps in all. Drag Steps done to cut power after any step. Turn on In the middle of the next step to cut during a copy. Turn off Status record to see the bootloader lose its place.

10 of 24

A model with 8 sectors instead of 64 so the picture stays readable. The three-record encoding (ff ff ff, 01 ff ff, 01 02 ff, 01 02 03) is from the MCUboot design document. The copy order follows the swap-using-scratch method as described above.

Set the slider to 10 and the record on. Sectors 0, 1 and 2 are fully swapped (9 steps). Sector 3 has finished step 1, so the record reads 01 ff ff. The bootloader will resume at step 2 of sector 3. Now turn the record off. The bootloader sees a primary slot that is part new and part old. Neither slot holds a complete image, and the hash check in Chapter 2 fails for both. The device has lost both firmwares.

Where the record lives: the trailer

The records live in the image trailer, at the very end of each slot. The MCUboot document lists its fields in order: the swap status, the encryption keys, the swap size, a swap-info byte, a copy_done byte, an image_ok byte, and a 16-byte magic value that marks the trailer as valid. For a write size of 8 bytes, the magic begins 77 c2 95 f3. Unused bytes stay 0xFF.

The swap status takes BOOT_MAX_IMG_SECTORS × min-write-size × 3 bytes. The default is 128 sectors. With a 4-byte write size that is 128 × 4 × 3 = 1,536 bytes. The trailer takes space from the slot, so the largest image is the slot size minus the trailer size.

The cost of the spare chair

Count the wear. With one scratch sector, every sector swapped erases scratch once. A 64-sector image erases the scratch page 64 times per update. At 10,000 erase cycles per page, scratch wears out after about 156 updates. That number is derived from the nRF52840 endurance figure and the algorithm, not quoted from MCUboot. It shows why the scratch area is a hot spot, and why MCUboot’s newer methods, swap using offset and swap using move, exist. Using offset, each slot is erased once per swap and each sector needs only 2 records. Using move, each sector needs 3 records and the primary slot is erased twice. The document prefers offset over move.

Time is the other price. In the hero’s model, a 64-sector swap with three erases and three page writes per sector takes 64 × (3 × 85 ms + 3 × 42 ms) = 24.4 s. During all of it the device is busy and cannot serve its normal job. That is why some products choose the two-bank design when a chip has the room.

A worked example: the numbers for one real slot

Take a 256 kB slot of 64 sectors of 4 kB, with a 4-byte write size.

  1. Records. Three per sector, one byte each, each padded to 4 bytes. That is 3 × 4 = 12 bytes per sector.
  2. Space for the default 128 sectors. 128 × 12 = 1,536 bytes, as in the text.
  3. Largest image. The slot is 262,144 bytes. Subtract 1,536 and you get 260,608 bytes. The trailer must be erasable on its own, so in practice you reserve whole pages for it. One 4 kB page leaves 258,048 bytes. This last step is our reasoning, not a quote.
  4. Resume cost. If power fails at step 2 of sector 37, the bootloader has 26 sectors to finish after that one (sectors 38 to 63), plus the rest of sector 37. At 0.38 s per sector that is about 10 s more.

The failure, as symptom, measurement and fix

Symptom. After an interrupted swap, the board resets again and again and never boots either image.

Measurement. Dump the last 16 bytes of each slot. Look for the trailer magic. If the magic is absent or wrong, the bootloader cannot find the record, so it cannot resume.

Fix. Keep the trailer in pages that nothing else erases. Make the write size in the bootloader build match the alignment used when signing images. A mismatch moves the records and the bootloader then reads the wrong bytes. And never skip the scratch area check when you change the partition table.

On real hardware. Build the Zephyr MCUboot sample for an nRF52840 DK with two slots. Request a swap, and reset the board by pulling the USB cable while the swap runs. Then read the last 16 bytes of the primary slot with your debugger. The magic is there, and the swap-info and flag bytes next to it show what the bootloader will do next.
A swap loses power during step 2 of sector 5, and the record for sector 5 reads 01 ff ff. What does the bootloader do at the next reset?

Chapter 6

Test, Confirm and Roll Back

Boot a new image on trial, confirm it only when it proves itself, and fall back when it does not

The update installs without a hitch. The hash passes. The bootloader jumps. And the new firmware crashes four seconds later, because it expects a sensor that older boards do not have. Thousands of devices are now stuck in a crash loop, every one of them carrying a perfectly valid image.

This is the gap Chapter 2 left open. A hash proves an image is complete. It does not prove the image works. For that, you need a trial.

Boot on trial, then confirm

The idea is the same one a car lease uses. You take the new car for a test drive. If you like it, you sign. If you do not sign, the dealer takes it back.

MCUboot calls this test and confirm. Its design document defines three swap types, stored in the trailer’s swap-info byte: TEST (2), PERM (3) and REVERT (4). In a test swap, the new image boots, but its image_ok flag stays unset, at its erased value of 0xFF. The new app must write that flag to 0x01, which means confirm. If the app never confirms, the next reset triggers a revert: the bootloader swaps the old image back, marks it OK and boots it. A permanent swap skips the trial: the new image is kept on every boot.

Revert is possible only because the swap in Chapter 5 kept the old image in the secondary slot. A design that overwrote the old image cannot go back.

What should the app check before it confirms?

Confirm too early and the trial is worthless. If the app confirms in its first line, a crash one second later is already permanent. Confirm too late, or never, and a working image reverts at the next reset, which looks like the update keeps vanishing.

A good rule is to confirm only after the app proves the things you cannot afford to lose. It starts its tasks. It reads its sensors. And above all, it reaches the update server. An image that works in every way except that it cannot receive the next update is a trap, because it cannot be repaired from afar. So the confirm call sits behind a check that the update link works.

Hangs, loops and the watchdog

A revert needs a reset. A crash that triggers a fault usually causes one, if the fault handler resets the chip. A hang, an endless loop with nothing running, causes none. That is the job of the watchdog: a hardware timer that resets the chip unless the program feeds it before it runs out. If the new app hangs, it stops feeding, the watchdog resets the chip, and the bootloader sees an unconfirmed image and reverts.

A second guard is a boot counter. The Interrupt DFU cookbook keeps a counter in a small shared RAM area. The loader increments it on every boot, and enters DFU mode when it reaches 3. The app clears it once it considers itself stable. This catches crash loops even in the permanent-swap case.

Boot the new image on trial

Pick how the new image behaves, how it was installed, and which safeguards exist. The boxes show each boot in order.

A model of the behaviour in the MCUboot design document (TEST, PERM, REVERT, image_ok) plus a watchdog and the 3-try boot counter from the Interrupt DFU cookbook. In the permanent case the counter is assumed to trigger a swap back to the old image still held in the secondary slot.

Start with Crashes at start and a test swap. Boot 1 runs v2 and fails. Boot 2 reverts and runs v1. Two boots, a working device. Now switch to Permanent swap. There is no trial, so every boot runs v2 and fails. Turn on the boot counter and the loop ends after the third failure with a fall back to v1. Turn it off and the loop never ends.

Try Works, forgets to confirm next. In a test swap, v2 runs well until the next reset, then the bootloader reverts to v1. This is the bug that makes updates seem to undo themselves. The symptom is a version number that goes backward a day after a rollout. The measurement is the boot log: it shows a swap of type test on one boot and a swap of type revert on the next. The fix is one call in the right place.

c/* in main(): runs on every boot of the app (Zephyr + MCUboot) */
if (!boot_is_img_confirmed()) {                  /* we are on trial */
    if (self_test_ok() && sensors_ok() && update_server_reachable()) {
        boot_write_img_confirmed();                /* image_ok = 0x01: keep me */
    } else {
        sys_reboot(SYS_REBOOT_COLD);                  /* do not confirm: the bootloader reverts */
    }
}
wdt_feed_start();   /* the watchdog is armed before this point, so a hang also ends in a reset */

One field report is worth knowing. A Nordic DevZone thread, “MCUBOOT bug, swapping back and forth forever if remote host doesn’t confirm”, describes a DFU that timed out before the image was confirmed. MCUboot then swapped the images on every reset. The lesson is general: an unconfirmed test image always reverts, so confirm only when the update path works, and remember that confirming is a flash write that must finish before you reset.

A worked example: what a revert costs in time

A revert is another swap, so count the time the device is offline.

  1. The failed trial. v2 boots and fails. With a watchdog timeout of 8 s (an illustrative value), the chip resets after 8 s.
  2. The revert swap. The scratch method needs 24.4 s for 64 sectors, as computed in Chapter 5.
  3. The boot. Add about 1 s for v1 to start.
  4. Total. 8 + 24.4 + 1 is about 33 s without service. With a boot counter that waits for 3 failed boots of 2 s each, add 6 s: about 39 s.

For a thermostat that is fine. For a medical pump it may not be. In that case a two-bank design with direct execute-in-place reverts by flipping the flag back, which takes microseconds.

The failure, as symptom, measurement and fix

Symptom. The device goes through test, revert, test, revert, forever.

Measurement. Read the swap-type record at each boot. If it alternates between test and revert, the bootloader sees the new image as valid every time.

Fix. After a revert, mark the new image as bad so the bootloader will not try it again. MCUboot does this for validation failures by setting the primary image_ok flag. For an image that boots and fails, the fix is to confirm the old image and clear the secondary slot’s magic.

On real hardware. Use an nRF52840 DK with MCUboot. Flash a v2 that calls boot_write_img_confirmed() and another v2 with an endless while(1) at the top of main. Count the boots until each ends on v1 or v2. Then arm the watchdog and repeat the hang case.
A new image installed as a test swap hangs in an endless loop, and the watchdog is armed. What happens?

Chapter 7

Trust: Hashes, Signatures and Versions

Check who made an image, and refuse one that is older than the device allows

Someone near your door cuts a wire off a smart lock and plugs into its update port. They send their own firmware. It is a complete image, with a correct header and a correct hash. The lock checks all that, finds it fine, and installs it. Now the lock opens for them.

Chapter 2 built a check for damage. This chapter builds a check for origin. A hash cannot do that job, because anyone can hash anything.

Signatures: a seal only one hand can make

A digital signature works like a wax seal with a private stamp. The vendor owns a private key and never shares it. The matching public key goes into every device. At build time, the vendor hashes the image and signs the hash with the private key. The result is a short blob, the signature. At install time, the bootloader checks the signature with the public key. If the image or the signature changed by even one bit, the check fails. Nobody can make a valid signature without the private key.

MCUboot’s image trailer carries the pieces as TLVs (Chapter 2): the SHA-256 hash (type 0x10), a hash of the public key (0x01, KEYHASH) and the signature. Its design document lists signature types: RSA-2048 with PSS (0x20), ECDSA (0x22), RSA-3072 with PSS (0x23) and Ed25519 (0x24). The imgtool utility generates keys of type rsa-2048, rsa-3072, ecdsa-p256 and ed25519. A signature TLV must come with a matching key-hash TLV.

The bootloader holds the public key, or its hash. So the bootloader must itself be hard to change. If an attacker can rewrite the bootloader, they can swap the key. That is why the bootloader is small, rarely updated, and, where the chip allows it, write-protected. Secure boot and device security builds the full chain of trust, including debug lock and key storage.

Old but genuine: the rollback attack

A signature proves who made an image. It says nothing about when. Suppose version 1.1.0 had a bug that lets anyone open the lock, and version 1.2.0 fixed it. An attacker captures the genuine, signed 1.1.0 and installs it. Every check passes, and the bug is back.

The defence is a counter the attacker cannot wind back. MCUboot describes two ways. Software downgrade prevention compares version numbers, and the document says it is available only with the overwrite-only upgrade mode. Hardware rollback protection compares a security counter inside the image (TLV type 0x50, set by imgtool with -s) against a counter in non-volatile hardware. The counter is independent of the version number.

Why a separate counter? Chapter 6 let a device revert an unconfirmed image. That is a deliberate step back. The security counter lets you move forward on security fixes only. You bump it when a release fixes a flaw. A design reason to advance the stored counter only after the new image is confirmed: otherwise a failed trial would lock out the very image the device needs to fall back to.

Attack the update

The device holds the vendor’s public key and a security counter of 3. Pick an image to send. Each check is real: SHA-256 and ECDSA P-256 run in your browser on keys made when the page opened.

Real SHA-256 and real ECDSA P-256 through the browser’s WebCrypto, with two fresh key pairs made on load. The image is a 96-byte stand-in. The order of checks (hash, key hash, signature, counter) follows the MCUboot design document. If your browser blocks WebCrypto, the page simulates the verdicts and says so.

Send the honest update. All four checks pass. Now send the others in turn. A flipped bit dies at the hash. A new payload with a recomputed hash passes the hash, because the attacker can hash their own file, and dies at the signature. An image signed with the attacker’s own key has a valid signature, but the key hash does not match the one in the device, so it dies at the key. The genuine old image passes everything until the counter. Turn the counter check off and it installs.

What this costs

Verification costs time and code space. An ECDSA check runs an expensive math routine on every install, and often every boot, so many products verify at install time and use a cheap check later. It also costs operations: the private key must live in a locked-down build system, because anyone who holds it can sign firmware for every device. A leaked key can only be revoked if the bootloader can learn a new key, and that capability is a design choice made before the product ships.

AttackHashKeySignatureCounter
Bit flip or truncationFailsnot reachednot reachednot reached
New payload, hash fixedPassesPassesFailsnot reached
Attacker keyPassesFailsnot reachednot reached
Genuine old imagePassesPassesPassesFails

A worked example: what a signature costs in bytes

Count the trailer for two key types. Each TLV has a 4-byte entry header. The info header adds 4 bytes.

  1. Hash. 4 + 32 = 36 bytes.
  2. Key hash. 4 + 32 = 36 bytes. It is a SHA-256 of the public key.
  3. ECDSA P-256 signature. A raw signature is two 32-byte numbers, 64 bytes. In the encoded form a trailer stores, it is a little over that. Call it 72 bytes plus 4: about 76.
  4. RSA-2048 signature. The signature is as long as the key: 256 bytes, plus 4 for the entry header.
  5. Totals. With P-256: 4 + 36 + 36 + 76 = about 150 bytes. With RSA-2048: 4 + 36 + 36 + 260 = about 336 bytes.

The trailer is small in both cases. The real difference is the verify time and the code size of the maths routine on a small chip. Measure both on your part.

The failure, as symptom, measurement and fix

Symptom. A new release is refused by every device in the field.

Measurement. Compare the key hash in the release image with the key hash the bootloader holds. If they differ, the build server signed with the wrong key, for instance a test key.

Fix. Make the release pipeline check the key hash before it publishes. Keep the production key in one locked system. Plan key rotation before launch: a device can only accept a new key if the bootloader was built to allow it.

On real hardware. With imgtool, generate an ecdsa-p256 key and sign a build with it. Build the MCUboot sample for an nRF52840 DK with that public key. Flash the signed image and confirm it runs. Then change one byte in the file with a hex editor and flash it again. The bootloader refuses it. Sign the same build with a second key and watch it refuse that too.
An attacker installs a genuine, correctly signed, older firmware with a known bug. The hash, key and signature checks all pass. What stops it?

Chapter 8

Getting the Bytes In: DFU Over UART, USB, BLE and CAN

Send an image over four links, and see what each link costs in time and in code

A new image is a file on a server. The device is a chip inside a sealed box with a cable, a radio or a car network. Between the two is a link, and the link decides how long the update takes, how much code the device needs to receive it, and how it fails.

We have said little about the link so far, on purpose. The safe-update ideas in Chapters 1 to 7 work on any link. But each link adds its own costs, so let us look at four common ones: UART, USB, BLE and CAN.

Two places to listen

A device can receive an image in two places. In the app, which already has a radio stack and network code. It downloads the image into the secondary slot while the product keeps working, then asks the bootloader to install it on the next reset. This is the normal over-the-air path. In the bootloader, which has almost no code. It can accept an image over a wire when no valid app exists. This is the rescue path, and it must be tiny, because the bootloader is the one program you do not want to grow or change.

The Interrupt DFU cookbook leaves the transport out of its design on purpose, because it “varies greatly depending on your use”. What it keeps fixed is the rule from Chapter 2: write the payload, verify, and only then commit the header.

Four links

UART is the simplest. Two wires carry bytes with no framing, no error check and no flow control, beyond what you add. At 115,200 baud with 8 data bits, no parity and one stop bit, each byte uses 10 bit times (a start bit, 8 data bits and a stop bit). That is 11,520 bytes per second at most, so a 256 kB image takes 262,144 / 11,520 = 22.8 s before any protocol overhead.

USB DFU is a standard. The USB-IF specification (DFU 1.1) defines an interface with class code 0xFE and subclass 0x01. Protocol 0x01 is the run-time mode, where the app is running. Protocol 0x02 is the DFU mode. The host sends the image in blocks using control transfers. The requests are numbered: DFU_DETACH 0, DFU_DNLOAD 1, DFU_UPLOAD 2, DFU_GETSTATUS 3, DFU_CLRSTATUS 4, DFU_GETSTATE 5 and DFU_ABORT 6. The device reports a maximum block size, wTransferSize. Because the standard exists, one host tool can update many devices. On the host, dfu-util -a 0 -s 0x08000000:leave -D app.bin sends a file.

The device walks through a small state machine as blocks arrive: dfuIDLE (2), dfuDNLOAD-SYNC (3), dfuDNBUSY (4) while it programs a block, dfuDNLOAD-IDLE (5), and at the end dfuMANIFEST-SYNC (6), dfuMANIFEST (7) and dfuMANIFEST-WAIT-RESET (8). A zero-length DFU_DNLOAD says “that was the last block”. If the device thinks data is missing, it replies with the error errNOTDONE (0x09). After each block the host polls DFU_GETSTATUS, a 6-byte reply, and waits as long as the device asks, so the device is never forced to take data faster than flash can absorb it.

BLE (Bluetooth Low Energy) moves data in short bursts at set connection intervals. A packet carries the ATT payload, which is the negotiated MTU minus 3 bytes of header. At the default MTU of 23, that is 20 bytes. With an MTU of 247 it is 244 bytes. The size of that payload and the number of packets per interval set the speed, and the default is slow.

CAN is a car and factory bus. A classic CAN frame carries at most 8 data bytes. A standard frame with 8 data bytes uses 111 bit times on the wire, counting the interframe gap: 1 + 11 + 1 + 1 + 1 + 4 + 64 + 15 + 1 + 2 + 7 + 3. At 1 Mbit/s that is about 9,009 frames per second. Update protocols often run on top of ISO-TP (ISO 15765-2), which uses one byte of each frame for control, so a frame carries 7 bytes of data. That gives 63,063 bytes per second if the bus carries nothing else. Other nodes share the bus, so the real rate is lower. CAN and EtherCAT covers bootloaders over CAN in more depth.

The slowest stage wins

Three stages sit between the server and the new image in flash: the link, the acknowledgement round trip, and the flash itself. Stage one moves bytes. Stage two waits for the device to say “got it”. Stage three erases and writes. Chapter 3 gave the flash cost: per 4 kB page, 85 ms to erase plus 1,024 words × 41 µs = 42 ms to write, so 127 ms per page and about 32 kB/s at the specified limits.

That means UART at 11.5 kB/s is the bottleneck on a fast chip, but a link that moves 200 kB/s is held back to about 32 kB/s by flash. If receiving and writing happen one after another, the times add. If the device receives the next chunk while it writes the last (double buffering), only the slower one counts.

Send the image

Pick a link. Drag the chunk size and the loss rate. The bar splits the total time into sending, waiting for acknowledgements, resending lost chunks and writing flash.

1,024 B
2%

A model with stop-and-wait chunks. Derived: UART 11,520 B/s from 115,200 baud at 10 bits per byte; CAN 63,063 B/s from 111-bit frames and 7 data bytes with ISO-TP. Illustrative: USB at 200 kB/s link rate, BLE at 4 packets per 30 ms connection interval, acknowledgement waits of 2, 2, 30 and 1 ms. Flash costs use the nRF52840 limits, 85 ms per 4 kB page and 41 µs per word.

Start with UART and a 1,024-byte chunk. The bar is mostly sending. Now switch to USB and the link all but disappears, and flash is most of what is left. Turn on Write flash while receiving and watch the flash segment hide behind sending. Then try BLE with the default MTU. A tiny payload per packet turns a 256 kB update into minutes, and a bigger MTU fixes it without any new hardware.

What the link must still guarantee

Every link needs the same few things from the receiving code. Each chunk carries its offset, so a repeated or missing chunk is detected. Each chunk carries a check value, so a bad chunk is rejected and re-sent. The device saves the next expected offset in flash, so after a reset the sender can resume instead of starting over. And after all chunks, the whole-image hash from Chapter 2 decides if the image is complete. Transport checks catch noise on the wire. Only the hash proves the image in flash is the image that was sent.

c/* one chunk, any link: UART frame, BLE write, CAN ISO-TP message, USB DNLOAD block */
typedef struct { uint32_t offset; uint16_t len; uint16_t crc; uint8_t data[]; } chunk_t;

int on_chunk(const chunk_t *c) {
    if (c->offset != next_off)                return nak_resend_from(next_off);  /* gap or repeat */
    if (crc16(c->data, c->len) != c->crc)  return nak_bad_crc();             /* noise on the wire */
    erase_ahead(SLOT_B + c->offset, c->len);           /* erase pages before the first write */
    flash_write(SLOT_B + c->offset, c->data, c->len);  /* 32-bit aligned words */
    next_off += c->len;
    save_progress(next_off);                          /* resume point after a reset */
    return ack(next_off);
}
/* when next_off == image_size: hash the slot (Chapter 2), verify the signature (Chapter 7),
   and only then ask the bootloader for a test swap (Chapter 6) */
On real hardware. Take an STM32F411 “Black Pill” board, hold BOOT0 high and reset it, so the chip's built-in USB DFU bootloader runs. Run dfu-util -l to list the DFU interfaces, then download a small image. Time it with the system clock. Compare with your model's USB figure: the real device is held to flash speed, not link speed.
An update over BLE takes minutes with the default MTU of 23. What is the best fix that needs no new hardware?

Chapter 9

Field Guide

Keep the numbers, the checklist, the core code and the way onward

A safe update is a short list of habits. Never touch the only good copy. Check the new image fully before you switch. Make the switch a single small write, or a swap that can resume. Boot the new image on trial. Confirm only after it proves it can still be updated. Refuse images that are damaged, unsigned or too old. And make every step survive a power cut, because the storm always comes at 3 a.m.

The numbers

WhatNumberSource or derivation
Page erase, nRF5284085 ms per 4 kB pageProduct specification, flash timing (a listed limit)
Word write, nRF5284041 µs per 32-bit wordProduct specification (a listed limit)
Flash endurance, writes per word10,000 erase cycles per page; 2 writes per word between erasesProduct specification
A 256 kB image64 pages, 65,536 words256 kB / 4 kB; 256 kB / 4 B
Erase plus write of 256 kB5.44 s + 2.69 s, about 8.1 s64 × 85 ms; 65,536 × 41 µs
Share of cuts that brickIn place 100%, stage-copy 0%, two banks 0%, swap 0%This lesson’s model, by time
Danger window of a flag flip41 µsOne word write
Swap of 64 sectors, scratch method24.4 s64 × (3 × 85 ms + 3 × 42 ms)
MCUboot image header32 bytes; magic 0x96f3b83dMCUboot design document
Trailer TLVsInfo magic 0x6907; SHA-256 type 0x10; key hash 0x01; security counter 0x50MCUboot design document
Signature typesRSA-2048 PSS 0x20, ECDSA 0x22, RSA-3072 PSS 0x23, Ed25519 0x24MCUboot design document
Swap status recordsff ff ff, 01 ff ff, 01 02 ff, 01 02 03MCUboot design document
Swap typesTEST 2, PERM 3, REVERT 4MCUboot design document
Boot counter limit3 boots, then DFU modeInterrupt DFU cookbook
VTOR address0xE000ED08Interrupt bootloader article
USB DFU interfaceclass 0xFE, subclass 0x01, protocol 0x01 or 0x02; requests 0 to 6USB DFU 1.1 specification
UART at 115200 baud11,520 B/s; 256 kB in 22.8 s10 bits per byte
Classic CAN at 1 Mbit/s9,009 frames/s; 63,063 B/s with ISO-TP111-bit frame; 7 data bytes
BLE payload per packet20 B at MTU 23; 244 B at MTU 247MTU minus 3 bytes of ATT header

The terms

The core as code

cvoid bootloader_main(void) {
    if (swap_in_progress())            resume_swap();             /* Ch 5: read the trailer, finish the sector */
    else if (test_swap_unconfirmed())  revert_swap();             /* Ch 6: the trial ended without a confirm */
    else if (secondary_wants_install()) {
        if (image_valid(SLOT_B) &&                   /* Ch 2: magic, sizes, SHA-256 */
            key_matches(SLOT_B) && signature_ok(SLOT_B) &&   /* Ch 7: key hash, ECDSA */
            counter_ok(SLOT_B))                       /* Ch 7: security counter */
            start_test_swap();                       /* Ch 5, 6: records first, then sectors */
        else mark_secondary_bad();                  /* never retry a bad image forever */
    }
    if (image_valid(SLOT_A) && signature_ok(SLOT_A))
        boot_app(SLOT_A);                            /* Ch 1: VTOR, MSP, bx */
    enter_rescue_dfu();                              /* Ch 8: wired path, the bootloader's own */
}

The checklist

  1. Keep one good image. At every instant, a complete, checkable image exists.
  2. Write the commit last. Header or flag goes in only after the payload verifies.
  3. Make the commit one word. Test it against an exact pattern.
  4. Cut power on purpose. Run at least 1,000 random cuts across the whole update and the first boot, and count dead boards.
  5. Boot on trial. Use test swaps. Confirm after sensors and the update link both work.
  6. Arm a watchdog before the new app runs, so a hang becomes a reset.
  7. Count failed boots. Fall back after a small number, such as 3.
  8. Sign images and keep the private key off the device and off laptops.
  9. Use a security counter and advance it only after the new image is confirmed.
  10. Keep the bootloader tiny and still. Protect it from writes, and give it a wired rescue path.
  11. Check the whole image at the end of every transfer, whatever the link.

Where this sits

The bootloader is the first code on the chip, so everything before it in the series is in play: reset to main() for the vector table, the embedded survey and embedded C for the startup and linker ideas, hardware interfacing for UART, USB and CAN on the wire, and RTOS and real-time systems for the watchdog and the tasks that run the update. Pipeline and privilege explains the processor modes behind the jump. Linux devices solve the same problem with a larger toolbox: embedded Linux covers the boot chain, and the planned secure boot and OTA lesson for Linux is the twin of this one.

Keep going

Sources and honesty notes

Built from primary sources we opened: the MCUboot design document and imgtool page, the Memfault Interrupt articles on the DFU cookbook and on writing a bootloader from scratch, the USB DFU 1.1 specification, the nRF52840 product specification (NVMC chapter), a Nordic DevZone thread on MCUboot confirm, and the Zephyr MCUboot API page. The STM32L4 bank-swap bit comes from ST community posts that cite the reference manual RM0351, so check the manual before relying on it. We searched for the Sabi article “OTA with safe rollback” and found no primary page, so nothing here is taken from it. The BLE rates, the 20 s receive time and the USB link rate are illustrative. Every device in this lesson is a model of the mechanism, not real silicon.

The takeaway. A safe update never has a moment when the device has no whole, checkable image and no way to find it again. Everything else, the two slots, the swap record, the trial boot, the signature and the counter, is a way to keep that one promise through a power cut, a bad image, an attacker and a slow link.
You must ship updates to devices you cannot reach. Which set of choices keeps the promise of this lesson?

Now press Present or Teach and explain one update from memory: what the bootloader reads at reset, what makes an image valid, why flash allows only one safe write, how each design survives a cut, how a swap resumes, how a trial boot rolls back, what a signature and a counter each stop, and why the link is rarely the slowest stage. Then go back to the plug at the top, sweep each design, and say out loud where each one is fragile.

Bootloaders and OTA, from the series Firmware from Zero to Expertise
MCUboot design · imgtool · Device Firmware Update Cookbook · Writing a bootloader from scratch · USB DFU 1.1 · nRF52840 NVMC · Back to Gleams