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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Chapter 1
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
$msp and *(uint32_t*)0xE000ED08 before and after. Then comment out the VTOR write and watch the first SysTick interrupt land in the bootloader.Chapter 2
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?
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.
ih_img_size), flags and the version: major, minor, revision and build number. All fields are little endian.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.
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.
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.
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.
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.
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 */ }
Take the small image in the device: a 32-byte header, a 96-byte payload and a trailer. Walk through what the bootloader reads.
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.
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.Chapter 3
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Chapter 4
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.
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.
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).
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.
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.
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.
| Design | Slots of image size | Where a cut hurts | Share of cuts that brick | Old image kept? |
|---|---|---|---|---|
| In place | 1 | Any moment of the update | 100% | No |
| Stage, then copy | 2 | Erase and copy of A (8.1 s), heals from B | 0% | No, A is overwritten |
| Two banks, flag | 2 | The flag write (41 µs) | 0% | Yes, in the other bank |
| Swap with record | 2, plus scratch or one spare sector | The swap (24.4 s), resumes from the record | 0% | 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.
Take a chip with 1 MB of flash, the size of the nRF52840, and an app that is 256 kB.
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.
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.
Chapter 5
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.
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.
A sector here means the unit the bootloader erases at one time. For each sector, in order, the swap does this.
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.
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.
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.
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.
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.
Take a 256 kB slot of 64 sectors of 4 kB, with a 4-byte write size.
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.
Chapter 6
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.
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.
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.
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.
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 revert is another swap, so count the time the device is offline.
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.
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.
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.Chapter 7
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.
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.
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.
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.
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.
| Attack | Hash | Key | Signature | Counter |
|---|---|---|---|---|
| Bit flip or truncation | Fails | not reached | not reached | not reached |
| New payload, hash fixed | Passes | Passes | Fails | not reached |
| Attacker key | Passes | Fails | not reached | not reached |
| Genuine old image | Passes | Passes | Passes | Fails |
Count the trailer for two key types. Each TLV has a 4-byte entry header. The info header adds 4 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.
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.
Chapter 8
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.
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.
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.
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.
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.
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.
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) */
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.Chapter 9
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.
| What | Number | Source or derivation |
|---|---|---|
| Page erase, nRF52840 | 85 ms per 4 kB page | Product specification, flash timing (a listed limit) |
| Word write, nRF52840 | 41 µs per 32-bit word | Product specification (a listed limit) |
| Flash endurance, writes per word | 10,000 erase cycles per page; 2 writes per word between erases | Product specification |
| A 256 kB image | 64 pages, 65,536 words | 256 kB / 4 kB; 256 kB / 4 B |
| Erase plus write of 256 kB | 5.44 s + 2.69 s, about 8.1 s | 64 × 85 ms; 65,536 × 41 µs |
| Share of cuts that brick | In place 100%, stage-copy 0%, two banks 0%, swap 0% | This lesson’s model, by time |
| Danger window of a flag flip | 41 µs | One word write |
| Swap of 64 sectors, scratch method | 24.4 s | 64 × (3 × 85 ms + 3 × 42 ms) |
| MCUboot image header | 32 bytes; magic 0x96f3b83d | MCUboot design document |
| Trailer TLVs | Info magic 0x6907; SHA-256 type 0x10; key hash 0x01; security counter 0x50 | MCUboot design document |
| Signature types | RSA-2048 PSS 0x20, ECDSA 0x22, RSA-3072 PSS 0x23, Ed25519 0x24 | MCUboot design document |
| Swap status records | ff ff ff, 01 ff ff, 01 02 ff, 01 02 03 | MCUboot design document |
| Swap types | TEST 2, PERM 3, REVERT 4 | MCUboot design document |
| Boot counter limit | 3 boots, then DFU mode | Interrupt DFU cookbook |
| VTOR address | 0xE000ED08 | Interrupt bootloader article |
| USB DFU interface | class 0xFE, subclass 0x01, protocol 0x01 or 0x02; requests 0 to 6 | USB DFU 1.1 specification |
| UART at 115200 baud | 11,520 B/s; 256 kB in 22.8 s | 10 bits per byte |
| Classic CAN at 1 Mbit/s | 9,009 frames/s; 63,063 B/s with ISO-TP | 111-bit frame; 7 data bytes |
| BLE payload per packet | 20 B at MTU 23; 244 B at MTU 247 | MTU minus 3 bytes of ATT header |
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 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.
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.
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.