Cut the power while a setting is saved. Overwrite it in place and the chip wakes up holding a number you never saved. A journal or copy-on-write keeps the old value safe.
Pick a way to save, slide the cut point, then press Save 24 and cut the power. Then press Try every cut point and count which designs ever lose the setting. After that we build, piece by piece, the flash cell, the wear arithmetic, the journal, copy-on-write and LittleFS.
You need the idea that flash keeps data without power and a little C. We build the rest from zero, starting from the flash rules in Reset to main(), Chapter 6.
Built from primary sources: the STM32L4 reference manual, the nRF52840 product specification, the Winbond W25Q128JV datasheet, and the LittleFS and Zephyr NVS documentation. Every source is listed in the Field Guide. The flash here is a model, not real silicon. Part of the Firmware from Zero to Expertise series.
A model, not silicon. The setting holds 20 before the save and the save writes 24. Erase takes 22.02 ms and each program step 81.69 µs, the typical times of the STM32L476 (reference manual and datasheet). The model programs one byte per step so tearing is visible; the real chip programs 8 bytes per step. A block that is mid-erase is drawn as red question marks: real cells there can read either way. The checksum is a toy 8-bit CRC; LittleFS uses a 32-bit CRC.
Chapter 0
See how one badly timed power cut can turn a saved setting into a number nobody saved, and why it only shows up in the field
A smart thermostat keeps one number in its flash memory: a calibration offset, the small correction that makes its temperature sensor read true. The factory sets it to 20, which means +2.0 °C. Every few weeks the thermostat re-measures itself and saves a new offset, say 24.
On the bench, this works for a year. In a customer’s house, one unit in a few thousand wakes up after a power cut with an offset of −23.2 °C. The heating runs flat out. The log shows no crash. Nothing was ever written that said −23.2.
The bug is in the save routine, and it can only fire if the power fails during the save. The save takes about 22 ms. The power fails once in a few thousand saves. So the bug is rare, fatal and almost impossible to reproduce by hand. This lesson makes it reproducible, then designs it away.
Non-volatile memory is memory that keeps its contents when the power is off. A notebook is non-volatile. A whiteboard that a gust of wind wipes is not. On a microcontroller, flash is the non-volatile memory. Your program lives there, and so can your settings.
Erase and program are the two ways to change flash, and they are not the same. Erasing sets a whole block of flash back to all ones (every byte reads FF). Programming then clears chosen bits to zero. You cannot clear a bit and set it back without erasing the whole block again. Reset to main(), Chapter 6 shows these rules on the STM32L476 with a device you can poke; this chapter needs only the one-sentence version.
A power cut is any moment the supply voltage drops too low for the chip to finish what it is doing. A pulled plug, a flat battery, a loose connector and a brownout (a dip that does not quite reach zero) all count. The chip does not get to say goodbye. The operation simply stops, wherever it is.
Here is the obvious way to save a setting. The code finds the flash block that holds it, erases that block, then programs the new value into the same place. This is overwrite in place.
c/* The obvious save. It has a hole in it. */ void save_offset(int32_t offset) { flash_erase_block(SETTINGS_BLOCK); /* 22 ms: the old value is destroyed here */ flash_program(SETTINGS_BLOCK, &offset, sizeof offset); /* the new value exists from here */ }
Look at the comments. From the first erase pulse until the last program step, the block holds neither the old value nor the new one. On the STM32L476, an erase takes 22.02 ms typically and programming one double word (8 bytes) takes 81.69 µs. The block is in limbo for about 22.1 ms of every save. That is the window.
Slide the power cut through the save below. Watch the colour under the cursor.
The bar is time. Blue means the old value is safe. Red means the flash holds neither value. Warm means the new value is safe. Slide the cut and check the sentence below.
Times are the STM32L476 typical values: erase 22.02 ms, program one double word 81.69 µs (datasheet and RM0351). Illustrative: one save a minute and two power cuts per device per year. The chance that one cut lands in the window is window divided by the minute: 22.1 ms / 60,000 ms.
The window covers 22.1 ms out of every minute: 22.1 / 60,000 = 0.037%. One power cut in 2,700 lands inside it. That sounds safe. Now ship 10,000 thermostats, each with two power cuts a year. That is 20,000 cuts, and 20,000 × 0.037% is about 7 ruined settings a year. At 100,000 units it is about 74 a year. Rare for one device is a steady stream for a fleet.
On real hardware. STM32 Nucleo-L476RG: set a spare GPIO high before the HAL erase call (HAL_FLASHEx_Erase) and low after it. Trigger a logic analyser on the rising edge. Expect a pulse close to 22 ms; the datasheet allows up to 24.47 ms.
Here is the road ahead.
Chapter 1
Learn the two jobs, program and erase, and the three rules they impose on every line of storage code
Picture a room with a long row of light switches. You may flip any single switch down, whenever you like. But flipping a switch back up is not allowed one at a time. Only a caretaker with a huge lever can do it, and the lever pushes every switch in the room back up at once. The lever is slow, and it wears out a little each time.
That room is a flash chip. A switch is a bit. Down is 0 and up is 1. This chapter explains why the chip is built this way, and what that means for code.
A flash cell is a transistor with an extra part: a floating gate, a tiny island of conductor sealed inside insulating oxide. Electrons on the island cannot leave by themselves, so they stay for years with no power. That is the memory.
The charge on the island shifts the voltage at which the transistor turns on. To read the cell, the chip applies a test voltage and checks whether the transistor conducts. By the usual convention for the NOR type of flash used inside microcontrollers, a cell with no trapped charge reads 1, and a cell with trapped charge reads 0.
The two ways to change the island are very different. Programming pushes electrons onto it. In NOR flash, this is done by channel hot-electron injection: a strong current in the cell gives a few electrons enough energy to jump the oxide. It targets one cell, or one small group. It turns a 1 into a 0.
Erasing pulls the electrons back off, by Fowler–Nordheim tunnelling: a very strong field lets electrons squeeze through the oxide. The erase circuitry is shared by a whole group of cells, so the chip erases them together. That group is the erase block: the smallest piece of flash you can erase. Sharing the circuitry keeps the chip small and cheap. That is why there is no “erase one byte”.
Everything in this lesson follows from three rules. The names differ between vendors, so we fix our words. Erase block means the smallest erasable piece. Program unit means the smallest piece you can program in one go. Vendors call the first a “page” (ST, Nordic) or a “sector” (Winbond). Winbond uses “page” for the program unit. Read the datasheet for the part in front of you.
Work one example. The byte holds F0 (binary 1111 0000). Your code writes 0F (0000 1111). The result is F0 AND 0F = 00. The chip did not store 0F. It cleared the four bits that were still ones in F0 and found nothing to set. Try it. Program, erase and watch the bits.
Top row: what the byte holds now. Switch bits in the second row to choose a value, press Program, and read the third row. Only Erase block brings ones back.
A model of one byte in one erase block. Bit meaning follows the NOR convention above. The 10,000-erase rating is the STM32L476 and nRF52840 figure (reference manual and product specification); the button adds 1,000 erases at once so you can see the gauge move.
The rules hold for every flash, but the numbers do not. Here are three common parts, each from its own datasheet. Look at the last column: the rewrite rule differs.
| Part | Erase block | Program unit | Erase time | Program time | Endurance | Rewrite rule |
|---|---|---|---|---|---|---|
| STM32L476 (inside the MCU) | 2 KB page | 8 bytes | 22.02 ms typical | 81.69 µs | 10,000 erases per page | A programmed double word cannot be programmed again unless the data is all zeros (PROGERR) |
| nRF52840 (inside the MCU) | 4 KB page | 4 bytes | 85 ms | 41 µs | 10,000 erases per page | A word may be written at most 2 times before the next erase (nWRITE = 2) |
| W25Q128JV (external SPI chip) | 4 KB sector | 1 to 256 bytes | 45 ms typical, 400 ms max | 0.4 ms typical, 3 ms max per 256 bytes | 100,000 erases per sector (minimum) | A partial page can be programmed if you stay within the page |
The external chip lasts ten times longer per erase block, but it needs a bus, and each erase is a command, not a register write. Here is the full sequence for one W25Q128JV sector in C. The opcodes are from its datasheet: 06h is Write Enable, 20h is 4 KB Sector Erase, and 05h reads Status Register 1, where bit S0 is BUSY.
cvoid nor_erase_sector(uint32_t addr) { spi_cmd(0x06); /* Write Enable: sets the WEL latch (S1) */ spi_cmd_addr(0x20, addr); /* Sector Erase, 4 KB; 24-bit address follows */ while (spi_read_status1() & 0x01) { } /* wait while BUSY (S0): 45 ms typical, 400 ms max */ }
Inside the STM32L476 there is no command to send. Flash sits at address 0x0800 0000 and you read it like RAM. A freshly erased word reads 0xFFFFFFFF. That single fact, that blank flash reads all ones, is how every design in this lesson tells “written” from “never written”.
Wear brings a fourth number. After the rated erase cycles, the chip no longer promises that data stays readable. Chapter 6 of Reset to main() gives the STM32L476 retention after 10,000 cycles: 30 years at 55 °C, 10 years at 105 °C. Heat shortens it.
On real hardware. STM32 Nucleo-L476RG with STM32CubeProgrammer: erase one page, then read it back and see 2,048 bytes of FF. Program one double word with F0, then try to program it again with 0F at the same address. Per RM0351 section 3.3.7 the second write is refused and the PROGERR flag in FLASH_SR is set.
Chapter 2
Read the exact bytes a power cut leaves behind, and see why a bigger capacitor cannot rescue a design that destroys its only copy
Go back to the hero, choose Overwrite, and set the cut to step 4. The chip reboots and reads 0xFFFFFF18. That is 4,294,967,064 as an unsigned number, and −232 as a signed one, which is why the thermostat in Chapter 0 thought its offset was −23.2 °C. No code ever wrote that number. Where did it come from?
A 32-bit number is stored as four bytes, least significant byte first. This order is little-endian. So 20 (0x14) is stored as 14 00 00 00, and 24 (0x18) as 18 00 00 00. After an erase, all four bytes are FF. Now follow the save, one program step at a time, and read the four bytes as a number after each step.
FF FF FF FF reads 0xFFFFFFFF, which is −1.18 FF FF FF reads 0xFFFFFF18, which is −232.18 00 FF FF reads 0xFFFF0018, which is −65,512.18 00 00 FF reads 0xFF000018, which is −16,777,192.18 00 00 00 reads 0x00000018, which is 24. Done.Four of those five states are wrong, and none of the four is 20 or 24. A write that stops part way is a torn write: some bytes are new, the rest are leftovers. The value you read is a blend that never existed.
A power cut during an in-place save leaves one of three messes. The first is a lost copy: the erase finished, nothing new was written, and the block reads all FF. The second is the torn write above. The third is a half-erased block: the erase was cut, and some cells sit between 1 and 0. Those cells can read either way, and the answer can change from one read to the next.
Use the symptom, measurement, fix order. The symptom: settings come back wrong, but only after power cuts, and only rarely. The measurement: dump the block right after the fault. If you see runs of FF mixed with the new bytes, you have a torn write. The fix is not to write faster. It is to stop destroying the only valid copy.
Real supplies do not drop to zero at once. They sag over milliseconds, and the chip keeps running until a brownout reset restarts it. Many chips can warn you first. The STM32L4 has a programmable voltage detector (PVD): you enable it with PVDE in PWR_CR2, choose a threshold with PLS[2:0], and it raises an interrupt on EXTI line 16 when the supply falls below that level (RM0351). The idea: on the warning, finish or abandon the save.
Two things limit that idea. First, the warning only helps if the chip can still run long enough. The energy comes from the capacitors on the supply. The time they hold is the charge you can spend, divided by the current the chip draws.
100 µF × 1.0 V / 10 mA = 0.0001 × 1.0 / 0.010 = 0.010 s = 10 ms
So 100 µF buys 10 ms, which is not enough for a 22 ms erase. To cover 22.4 ms you need 22.4 ms × 10 mA / 1.0 V = 224 µF. That is affordable. But try the device: the cost moves with every assumption, and the comparison below is the real lesson.
The yellow line is how long your capacitor keeps the chip alive. Each bar is the time one way of saving needs, on a log scale. A bar left of the line is covered. Change the capacitor, the voltage you can spend and the board current.
Illustrative: the capacitor, the voltage window and the current are made up, and erase may draw more than the figure you set. The three save times are the model's: 6 program steps of 81.69 µs for the journal, and an erase of 22.02 ms plus the program steps for the other two (STM32L476 typical times).
Look at the bars. The journal needs 0.49 ms, so even a small capacitor covers it many times over. The overwrite needs 22.4 ms. You can buy that with a bigger capacitor, but you pay in board area and in cost, and the number you bought only holds if the real current stays under your guess.
The second limit is worse. On a single bank of flash the core freezes while an erase runs. Chapter 6 of Reset to main() explains that two banks allow reads during a write. With one bank, the warning interrupt cannot run until the erase is over. The chip hears the alarm too late.
On real hardware. nRF52840 DK with a Nordic Power Profiler Kit II: start a page erase in code and capture the supply current. You should see one flat stretch of about 85 ms, the product specification’s page erase time. Repeat with a word write and compare the 41 µs step.
Chapter 3
Work out how long a block lasts, and see why one number, saves per erase, decides the answer
The thermostat from Chapter 0 also keeps a run-time counter. It adds one every minute and saves the total, so a technician can read the device’s age. The code is the same overwrite as before. The counter is four bytes. A flash chip stores trillions of bits. What could wear out?
The block wears out, not the byte. Every save erases the whole 2 KB page that holds the counter, and a page survives only so many erases. The STM32L476 rates a page for 10,000 of them. The counter erases that page once a minute.
Take the numbers one step at a time. A page survives 10,000 erases. The counter erases it once a minute. So the page lasts 10,000 minutes. That is 10,000 / 60 = 166.7 hours, or 6.9 days. The thermostat would eat its own storage in a week.
Here is the lifetime as one formula. Every term is something you can read off a datasheet or choose in code.
The product N × R is saves per erase, for the busiest block. It is the lever. Everything in the next chapters raises it. The in-place counter has N × R = 1. Now change the design. Instead of overwriting, append: write each new value into fresh space after the last one, and erase only when the block is full. Zephyr’s NVS stores each value with 8 bytes of metadata, so a 4-byte counter becomes a 12-byte record. A 2 KB page holds 2,048 / 12 = 170.7, so R = 170 whole records.
Two pages taking turns: N × R = 2 × 170 = 340 saves per erase of each page
life = 10,000 × 340 × 1 min = 3,400,000 min = 6.5 years
The same log on the nRF52840 holds 4,096 / 12 = 341 records per 4 KB page. Two pages give N × R = 682, and 10,000 × 682 minutes is about 13 years. Wear problems follow one pattern. The symptom: settings fail weeks or months after launch. The measurement: count erases per block, not writes. The fix: raise N × R, or save less often.
The Zephyr NVS documentation works the same example with 1,024-byte sectors and a flash rated for 20,000 erases, and also lands at about 6.5 years. Our number is 340 times the in-place lifetime, from the same flash, by changing how we write.
Now spend more flash. Give the log 8 pages instead of 2: N × R = 8 × 170 = 1,360, and the life is 10,000 × 1,360 minutes, about 25.9 years. Memory space turns directly into lifetime. Try the real parts.
Pick a flash part and how often you save. The yellow bar is rewriting in place. The blue bar is an append-only log over the blocks you give it. Dashed lines mark one day, one year and ten years.
Endurance, block size and part names are from the datasheets in the table of Chapter 1. Each record is the data plus 8 bytes of metadata, as in Zephyr NVS. The model counts only erases from saves. A real log also copies live records forward when it clears a block, which wears slightly more (Chapter 5). A 365-day year.
With the STM32L476 at one save a minute, the log gives 6.5 years from 2 pages. The W25Q128JV has ten times the endurance, and its 4 KB sectors hold twice the records, so the same log lasts about 130 years. Push the interval down to one save a second and the 2-block STM32L476 log lasts 10,000 × 340 s, about 39 days. Wear is always a budget, and the device shows where it runs out.
Before any clever structure, ask whether the save must happen at all. Three habits cut wear at the root.
One more piece of arithmetic keeps teams honest: erases per year. Before you ship, compute (saves per year) / (N × R), and compare it with E divided by the product life in years. If a page must last 10 years, the budget is 10,000 / 10 = 1,000 erases a year. That is under three erases a day.
On real hardware. nRF52840 DK: wrap the page erase call with a RAM counter, then run a test that makes one simulated hour of saves. Compare the counted erases with N × R from the formula; the two should match to within one.
Chapter 4
Spread erases over many blocks, and see which blocks still burn out first when some data never moves
Chapter 3 gave one log its own blocks. A real product stores more than one thing. It holds a firmware image that changes twice a year, a calibration table written once at the factory, a config file edited now and then, and a log that is rewritten every minute. Most of the flash is quiet. One corner is busy.
If the busy corner always uses the same block, that block reaches its 10,000 erases first. The rest of the chip is still new. The product is dead anyway, because one block failed.
Hot data is data that is rewritten often. Cold data is data that is written once and then only read. A block full of cold data sits at near zero wear for the whole life of the product. That is spare life you are not using.
Wear levelling is any scheme that spreads erases over many blocks, so that no block dies much sooner than the others. There are two levels of ambition.
Dynamic wear levelling spreads the hot writes over every block that is currently free. The next write goes to a different free block than the last one did. It costs almost nothing, because each write was going somewhere anyway. But blocks that hold cold data never take part. They never get erased, so they never share the load.
Static wear levelling also moves the cold data. From time to time it copies a cold block into a worn block and frees the fresh block for hot use. Now every block shares the load. The price is extra erases (each move costs one) and more code.
LittleFS, the filesystem of Chapter 7, is honest about this. Its design document says it “currently only provides dynamic wear leveling,” calls it best effort, and suggests combining it with a flash translation layer (FTL) if you need the static kind. Many SD cards and eMMC chips already have an FTL inside their controller. Bare NOR flash on a small board does not.
Picture the flash as a grid of 16 blocks. Six hold cold data. Ten are free. A hot file is rewritten again and again, and each rewrite costs one block erase. Which blocks take the erases? Compare the three policies. The colour of each block is its share of the rated 10,000 erases. A block turns red when it is used up.
Choose a policy, then drag the number of rewrites. The squares labelled “cold” hold data that never changes. Watch which squares fill up.
A model with illustrative numbers: 16 blocks, 6 of them cold, each rated for 10,000 erases (the STM32L476 and nRF52840 figure), and one erase per rewrite. Dynamic levelling shares the rewrites over the 10 free blocks. Static levelling shares them over all 16 and adds 1 extra erase per 100 for moving cold data (an assumed overhead).
Run the numbers by hand. With no levelling, one block takes every erase. It dies at the 10,000th rewrite. With dynamic levelling, 10 blocks share the work, so the first death comes at 10 × 10,000 = 100,000 rewrites. That is ten times better, for free. With static levelling, all 16 share, and the 1% overhead means each rewrite costs 1.01 erases: the first death comes at 16 × 10,000 / 1.01 = 158,416 rewrites. That is 1.58 times better again, and it needed the machinery to move cold data.
The lesson is the shape, not the decimals. Dynamic levelling gives you most of the win. Static levelling matters when the cold fraction is large, because a cold fraction f hides f of your flash from the hot writes.
Wear levelling usually needs a count of erases per block. A table of counters costs flash, and updating the table is itself a write. LittleFS avoids the table. Its block allocator has no on-disk free list. It scans the filesystem to find free blocks, and it starts that scan at a random offset on every mount. The seed comes from the checksums already stored on disk. Over many boots, new data lands all over the chip.
One place needs more care: the metadata logs of Chapter 6. They are small and updated often, so they are the hot spot. LittleFS takes a setting called block_cycles. After that many erases of a metadata block, the log moves to another block. The header comment suggests values from 100 to 1000. Larger values perform better but level less evenly. Setting it to −1 turns block-level levelling off.
The design document adds two more guards. After a write, LittleFS reads the data back. If it does not match, the block is marked bad, evicted, and the write is retried on a fresh block. If every block fails, the call returns the “out of space” error. LittleFS does not fix read errors itself: ECC, if the chip has it, comes from the block device below.
On real hardware. STM32 Nucleo-L476RG: in a debug build, add a counter array indexed by page number to your flash driver’s erase function. Run your storage code for a few hours of simulated saves, dump the array, and plot it as a bar chart. A flat plot means levelling works. A tall spike is your hot block.
Chapter 5
Save by writing the next line in a log and stamping it last, so a cut can never leave you without a valid value
A shopkeeper keeps a ledger in ink. When the price of tea changes, she does not scratch out the old line. She writes a new line below it and signs it. To find the price, you read from the bottom up until you meet a signed line. If she is called away before she signs, the unsigned line is ignored. The old price still stands.
That is a journal, also called a log-structured store: new values are appended, never overwritten, and a value counts only once its stamp is on it. Zephyr’s NVS (Non-Volatile Storage) is exactly this, built for flash.
NVS stores elements as an id plus data. Each element is the data plus 8 bytes of metadata. The metadata holds the id, the data offset, the data length, an unused field, and a CRC. A CRC (cyclic redundancy check) is a short number computed from the bytes it protects; if any byte differs, the number differs, so it detects a half-written record.
Inside a sector, the data is written from the start, and the metadata table grows from the end. The rule that makes it power-safe is one sentence in the documentation: “A write of data to nvs always starts with writing the data, followed by a write of the metadata.” And a second: data written without metadata is ignored when the store starts.
So a save is two program operations. Data first, label last. Walk the cuts. If the power dies before the data is complete, there is no label, so nothing refers to it. If the power dies after the data and before the label, the data is an orphan and is ignored. If the power dies in the middle of the label, the CRC does not match and the label is ignored. Only a complete label makes the new value real. At every instant there is exactly one newest valid record for each id: the old one, or the new one. Never none.
Hero sweep: the journal has 0 damaging cut points out of 6; overwrite has 6 out of 6.
Appending never erases, so sooner or later the sector is full. NVS keeps its sectors as a ring. When the current sector fills, it moves to the next one, and erases that one first if needed. Before it erases a sector, it checks that every id in it still has a pair in the other sectors in use, and copies forward any pair that would otherwise be lost. This is garbage collection.
That is why the documentation says “one sector is always kept empty to allow copying of existing data,” and why you must give NVS at least two sectors. The order matters again: copy first, erase last. A cut in the middle of the copy leaves the old sector whole. A cut during the erase happens after the live data has already been written to its new home.
Try it. The device has two sectors of six slots each. The real sector holds hundreds of records; six keeps the drawing readable. Save values for two ids, then cut the power at the two dangerous moments.
Each column is a record: the top cell is its data, the bottom cell is its label. Press Save to append. Press the cut buttons to kill the power at a bad moment. Then check the newest value.
A model of the NVS rules from the Zephyr documentation: data first, label last, unlabelled data ignored, one sector always empty, live records copied forward before an erase. The six slots per sector, the ids and the values are illustrative. A torn label is shown as failing its CRC check.
Fill the first sector and watch the next save. The device copies the newest A and B into the empty sector, then erases the full one. The erase counter on the sector goes up by one. All the older versions of A and B are gone, and the two live values are safe in the new sector before the old one is touched.
On Zephyr the whole thing is a few lines. You describe a flash area, mount it, then read and write by id. NVS lives in zephyr/fs/nvs.h up to Zephyr 4.3, and moves to zephyr/kvss/nvs.h in 4.4 when it joins the new key-value storage subsystem (the 4.4 migration guide). The settings fields obey three rules from the docs: the sector size is a multiple of the erase page size and a power of 2, the sector count is at least 2, and the offset is where the storage area starts.
c/* Zephyr NVS: store a calibration offset under id 1 */ #include <zephyr/storage/flash_map.h> #include <zephyr/fs/nvs.h> static struct nvs_fs fs; int store_init(void) { struct flash_pages_info info; fs.flash_device = FIXED_PARTITION_DEVICE(storage_partition); fs.offset = FIXED_PARTITION_OFFSET(storage_partition); flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info); fs.sector_size = info.size; /* one erase page per sector */ fs.sector_count = 3; /* at least 2; one stays empty for garbage collection */ return nvs_mount(&fs); /* scans sectors, ignores data without a label */ } int save_offset(int32_t v) { return nvs_write(&fs, 1, &v, sizeof v); } int load_offset(int32_t *v) { return nvs_read(&fs, 1, v, sizeof *v); }
NVS protects the metadata with a CRC. It does not protect your data unless you ask: the option CONFIG_NVS_DATA_CRC adds a CRC-32 over the data as well. Turn it on when a torn payload would hurt.
Compare with Chapter 3. Two 2 KB sectors give 6.5 years at one save a minute. Three sectors, one kept empty, still share the erases around the ring. The journal wins on wear and on safety with the same trick: never overwrite, and let a small final write decide what is real.
On real hardware. nRF52840 DK with a loop that saves a rising counter through NVS: put a relay on the board supply, driven by a spare GPIO of a second board, and cut the power at random moments. After each reboot read the counter. It must always equal one of the last two values saved, never a partial one.
Chapter 6
Keep two blocks, write the new version into the spare one, and let a checksum and a revision number pick the winner at boot
Take two sheets of paper, A and B. Each has a revision number at the top. Sheet B has the newest setting, revision 8. Sheet A holds the one before, revision 7. To change the setting, you do not touch B. You wipe A, write revision 9 on it, and sign it at the bottom with a checksum. If you are interrupted before the signature, A is junk, but B is whole. After the signature, A is the newest.
That is copy-on-write: never change the live copy. Write the new version somewhere else, then flip to it with one small step. LittleFS uses this for its metadata, in a structure it calls a metadata pair.
Metadata is the data about files: names, sizes, and where the file blocks are. In LittleFS each directory keeps its metadata in a pair of blocks. Each block starts with a revision count, a 32-bit number that the spec says is “incremented every erase cycle.” After the revision comes a series of commits. A commit is a group of entries, followed by a 32-bit CRC that covers them. The spec fixes the CRC: polynomial 0x04c11db7, starting from 0xffffffff.
At mount, the filesystem reads both blocks. A block is usable if its last commit has a good CRC. If both are usable, the spec says “only the block with the most recent revision count should be used.” “Most recent” needs care. A 32-bit counter wraps from 4,294,967,295 to 0. So the spec demands sequence arithmetic: compare the signed difference, not the plain values. The idea is (int32_t)(a - b) > 0 means a is newer than b. It still works after the wrap.
One checksum can cover several entries. That makes a change to more than one thing atomic. Rename a file and update its size in one commit, and a power cut shows you either both or neither.
Erasing a block on every update would burn the flash, as Chapter 3 showed. LittleFS mixes the journal of Chapter 5 with copy-on-write, and has three cases. Its design document names them.
The split happens at 50% of capacity, not 100%. The design document says this keeps the cost of an update constant on average, at the price of about twice the space. That is the same trade as Chapter 3: space in, lifetime out.
Append costs program steps and no erase. Compaction costs one erase and the copying of every live entry. So the number that matters is updates per erase. If a block holds S entries and L of them are live after a compaction, then S − L updates fit before the next one.
updates per erase = S − L for S = 16 and L = 3: 16 − 3 = 13 updates per erase
Try it. Move the number of updates and watch the block fill, compact and refill. Then raise the live entries and see the erases speed up.
The row is one block. Blue slots are live entries, grey slots are old versions, empty slots are free. Each time it fills, the live entries are copied to the spare block and the old one is erased.
A toy block: the real block holds hundreds of entries, and an entry's size varies. The rules are LittleFS's (append, compaction with revision + 1, split at 50% of capacity), and the entry counts are illustrative. Each update replaces one live entry; the other live entries are carried over unchanged.
With a toy 16-entry block and 3 live entries, 13 updates fit between erases. A real 4 KiB block fits far more, so the erase rate per update falls further. At 13 updates per erase and a 10,000-erase flash, the pair absorbs 130,000 updates before its busiest block is spent, and block_cycles (Chapter 4) moves the log elsewhere well before that.
Walk the compaction by hand, with block B live at revision 8 and A as the spare.
One step flips the decision, and that step is the CRC. Every cut before it keeps B. This is the structure the hero’s “Copy on write” button runs: all 7 cut points keep the old value, and the uncut save gives the new one.
On real hardware. nRF52840 DK with LittleFS on a QSPI or internal partition: format, write a small file in a loop, and read the two metadata blocks (blocks 0 and 1) with the flash tools. Find the 32-bit revision at the start of each. It should rise by one every time the log compacts.
Chapter 7
Plug a filesystem into a flash chip with four functions, size its caches, and see how a file grows without ever being rewritten
You have a W25Q128JV on your board. It holds 16 MiB. You want files: a config, a log, a calibration table. You could write all of Chapter 5 and Chapter 6 yourself. Or you could give LittleFS four small functions and let it do the rest.
LittleFS was designed for microcontrollers. Its authors list three problems it must solve at once: power loss at any moment, wear, and bounded RAM, meaning the RAM it needs does not grow with the size of the disk or the number of files. The first two are Chapters 5 and 6. This chapter covers the third, and the plug that connects LittleFS to your chip.
LittleFS knows nothing about SPI or your chip. It sees a block device: an array of erasable blocks, with four operations that you supply as function pointers.
Both prog and erase may return the error LFS_ERR_CORRUPT to say the block went bad. Then LittleFS evicts it and tries another, as Chapter 4 described.
Then you describe the geometry. Six numbers matter. The rules, from the library header: block_size must be a multiple of the read and program sizes; cache_size must be a multiple of both and a factor of the block size. Here is a full configuration for the W25Q128JV. The chip has 4,096 sectors of 4 KB, and it programs up to 256 bytes per page.
cstatic int bd_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buf, lfs_size_t size) { nor_read(block * 4096 + off, buf, size); return 0; } static int bd_prog(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buf, lfs_size_t size) { nor_page_program(block * 4096 + off, buf, size); return 0; } /* opcode 02h, never across a 256 B page */ static int bd_erase(const struct lfs_config *c, lfs_block_t block) { nor_erase_sector(block * 4096); return 0; } /* opcode 20h, from Chapter 1 */ static int bd_sync(const struct lfs_config *c) { return 0; } /* our helpers already wait for BUSY */ const struct lfs_config cfg = { .read = bd_read, .prog = bd_prog, .erase = bd_erase, .sync = bd_sync, .read_size = 16, .prog_size = 256, .block_size = 4096, .block_count = 4096, .cache_size = 256, .lookahead_size = 16, .block_cycles = 500, }; lfs_t lfs; if (lfs_mount(&lfs, &cfg) < 0) { lfs_format(&lfs, &cfg); lfs_mount(&lfs, &cfg); } /* first boot: blank chip */
LittleFS uses a read cache, a program cache, and one cache for each open file. Each is cache_size bytes. The allocator also has a lookahead bitmap: one bit per block, so each byte of RAM tracks 8 blocks. With the numbers above and two files open, the caches cost (2 + 2) × 256 = 1,024 bytes and the lookahead costs 16, so about 1,040 bytes in all. Those 16 bytes track 128 of the 4,096 blocks at a time. When the allocator runs out of known-free blocks, it rescans the filesystem and refills the bitmap.
That is the trade in cache_size and lookahead_size: RAM for speed. A bigger program cache means fewer small writes. A bigger lookahead means fewer rescans. The library header suggests block_cycles of 100 to 1000, as Chapter 4 explained.
Where does a file’s data go? A small file’s data lives inline, inside the directory’s metadata pair, and is covered by the same atomic commits. The design document says a file leaves the directory once it passes a quarter of the block size. The code is stricter: lfs_init in lfs.c caps the inline size at the smallest of cache_size, the attribute limit and one eighth of the block size. With the configuration above, cache_size is 256, so a file over 256 bytes gets its own blocks. Your calibration table of 200 bytes stays inline and shares a commit with its name.
A larger file becomes a chain of blocks of its own. Rewriting a block in the middle would force copying every block after it. LittleFS avoids it with a clever list. Each block points backwards to the block before it, so adding data at the end touches only the new block. The directory remembers the last block and the file size. That is enough to find anything: start at the end and follow pointers back.
Following one pointer per block is slow for a big file. So blocks carry extra pointers that jump further. This is a CTZ skip-list, named for “count trailing zeros.” Number the blocks 0, 1, 2 and so on. Block n holds a pointer to block n − 2i for each power of two that divides n. Block 8 divides by 1, 2, 4 and 8, so it holds four pointers: to blocks 7, 6, 4 and 0. Block 7 holds one, to block 6. On average a block carries about 2 pointers, so the overhead stays small.
pointers in block n = ctz(n) + 1 block 8 = 0b1000, three trailing zeros, so 3 + 1 = 4 pointers
Each arc is a pointer that a block holds. The bold arcs are the path from the end of the file to the block you want to read. Slide both controls and compare the hops with a plain list.
The pointer rule is LittleFS's (block n points to n minus 2 to the i for each i up to its trailing zero count; the design document counts about 2 pointers per block). The path takes the largest jump that does not pass the target; the model counts hops, not time.
Read block 3 of a 20-block file. A plain list needs 16 hops from block 19. The skip-list path is 19, 18, 16, 8, 4, 3: five hops, because it takes the biggest jump that does not pass the target. Try other lengths and targets in the device.
The file stays safe because blocks are never changed. Appending writes a new last block and then commits a new (pointer, size) pair to the directory with the Chapter 6 commit. A cut before the commit leaves the old pointer and the old size. The extra block is unreferenced garbage, and the allocator reuses it.
On real hardware. STM32 Nucleo-L476RG with a W25Q128JV breakout on SPI: mount the config above, open a file, and append 100 bytes in a loop. Log the elapsed time of lfs_file_sync. Most calls should take well under a millisecond, with an occasional 45 ms or more call: that is a sector erase, the datasheet’s typical tSE.
Chapter 8
Choose where to write, how to mark a record valid and in what order, then prove the design by cutting the power at every step
Not every project needs LittleFS. A motor driver keeps 16 bytes of calibration. A sensor board keeps one offset. Two flash pages and 60 lines of C are enough. But the safety does not come from the file system. It comes from three decisions, and each one is easy to get wrong. This chapter lets you break each one on purpose.
The rule behind all three is one sentence. Make the commit the last small step, and make everything before it safe to lose. The commit is the one program operation that changes what a reader will believe. Before it, the new record is junk that nobody trusts. After it, the new record is the truth. A cut can only land before or after.
Try all the designs. The device builds a two-slot store from your three choices, then cuts the power at every step of the save and reports what the chip reads after each reboot. The old value is 20 and the new is 24. A cut that reads anything else is a failure.
Walk one design by hand: write into the other slot, checksum last. The save has 7 steps. Step 1 erases the spare, step 2 writes the revision, steps 3 to 6 write the four data bytes, and step 7 writes the checksum. Cut during any of steps 1 to 7, and the live slot still has a good checksum and the higher revision. Mount reads 20. Only an uncut save reaches 24.
Pick a preset or set the three choices yourself. Each square is one step of the save. A red square means a power cut during that step leaves a value that is neither 20 nor 24.
Uses the same flash model as the hero: two slots, a revision byte, four data bytes, an optional check byte. The old value 20 is in the newer slot and an older value 18 in the other. A cut during an erase tears every cell of that block. “Nothing” with “other slot” fails because the reader cannot tell which slot is newest. The tally weights each step by its time: erase 22.02 ms, each program step 81.69 µs (STM32L476 typical).
Find the failing designs first. Any design that writes into the live slot fails at every step: the live slot is erased first, and the reader falls back to the old value 18 from two saves ago, or to garbage. A design with nothing to mark a record valid fails too. Now look at the flag-first design. Five of its seven cut points fail, yet measured in time it is dangerous for only 1.8% of the save, because the erase, the long step, is safe. That is the trap. In a test with random cuts the design looks perfect. At fleet scale it fails. The sweep catches it in one run.
Flag last and checksum last both pass in this model. A checksum earns its keep outside the model. It also detects a program step that was cut in the middle of a byte, a bit that flipped while the device sat in a drawer, and a flag value that is read by accident from a half-erased cell. Use the checksum. The two cost the same one program step.
Here is the checksum-last design in C for the STM32L4, where the program unit is 8 bytes. A slot is one erase block. The body is exactly one double word, and the commit is exactly one double word, written last. The sequence number is compared with the signed difference from Chapter 6.
cstruct slot { uint32_t seq; int32_t offset; /* body: one 8-byte double word */ uint32_t crc; uint32_t pad; /* commit: one double word, written LAST */ }; static bool slot_ok(const struct slot *s) { return s->seq != 0xFFFFFFFFu && s->crc == crc32(s, 8); /* blank or torn slots fail */ } bool load(int32_t *offset, uint32_t *seq) { const struct slot *a = SLOT_A, *b = SLOT_B; /* flash is memory-mapped */ bool oa = slot_ok(a), ob = slot_ok(b); const struct slot *w = oa && ob ? ((int32_t)(a->seq - b->seq) > 0 ? a : b) : oa ? a : ob ? b : NULL; if (!w) return false; *offset = w->offset; *seq = w->seq; return true; } int save(int32_t offset) { int32_t cur; uint32_t seq = 0; const struct slot *live = load(&cur, &seq) ? live_slot() : NULL; const struct slot *spare = (live == SLOT_A) ? SLOT_B : SLOT_A; /* never the live one */ struct slot n = { .seq = seq + 1, .offset = offset, .pad = 0xFFFFFFFFu }; n.crc = crc32(&n, 8); if (flash_erase(spare, SLOT_BYTES)) return -1; /* a cut here leaves the live slot whole */ if (flash_write(spare, &n, 8)) return -1; /* body: still not trusted */ return flash_write((char *)spare + 8, (char *)&n + 8, 8); /* the commit */ }
An erased slot has seq 0xFFFFFFFF, so slot_ok rejects it before the CRC even runs. The first boot of a blank chip finds no valid slot, and the caller writes factory defaults.
The device above is the same test, run by hand. In your project, run it automatically. Put the flash behind two functions, and on a host build replace them with fakes that count operations and stop at a chosen one. A half-erased block is filled with random bytes. A half-programmed byte is the AND of old and new.
cstatic uint8_t mem[2][4096]; static long budget; /* operations left before the power dies */ int flash_write(void *dst, const void *src, size_t n) { for (size_t i = 0; i < n; i++) { if (budget-- == 0) return CUT; ((uint8_t *)dst)[i] &= ((const uint8_t *)src)[i]; /* program only clears bits */ } return 0; } int flash_erase(void *blk, size_t n) { if (budget-- == 0) { for (size_t i = 0; i < n; i++) ((uint8_t *)blk)[i] = (uint8_t)rand(); return CUT; } memset(blk, 0xFF, n); return 0; } void test_cut_everywhere(void) { for (long b = 0; b < 40; b++) { reset_flash(); budget = LONG_MAX; save(20); /* the old value is safely stored */ budget = b; save(24); /* the power dies at operation b */ budget = LONG_MAX; int32_t v; uint32_t s; assert(load(&v, &s) && (v == 20 || v == 24)); /* old or new, never anything else */ } }
This loop is the hero’s “Try every cut point” button, in C. The testing lesson of this series builds that kind of harness and runs it in CI. Chapter 9 puts the whole recipe on one page.
On real hardware. STM32 Nucleo-L476RG: run save in a loop and add a relay on the board supply. Cut the power at random times, boot, call load, and log seq and offset. Over 1,000 cuts, the log must never show an offset outside the set of values you saved, and the sequence number must never move backwards by more than one.
Chapter 9
Keep the numbers, the checklist and the one pattern that makes a save survive a power cut
Flash changes in two ways. Program clears bits one unit at a time. Erase sets a whole block to ones, slowly, and wears it. A save that erases the only copy of a setting has a hole of about 22 ms. The cure is structural: write the new record somewhere else, finish it, and make it real with one small last step. A journal does this by appending, copy-on-write by alternating two blocks, and LittleFS does both. Then test a cut at every step.
| Item | Value | Source |
|---|---|---|
| STM32L476 flash | 2 KB erase page; erase 22.02 ms typical (24.47 max); program 8 bytes in 81.69 µs; 10,000 erases per page; data kept 30 years at 55 °C after that | RM0351 and the STM32L476 datasheet |
| nRF52840 flash | 4 KB page; erase 85 ms; write one 32-bit word in 41 µs; 10,000 erases per page; a word may be written at most 2 times between erases | nRF52840 product specification, NVMC |
| W25Q128JV (SPI NOR) | 4 KB sector erase 45 ms typical, 400 ms max; page program of up to 256 bytes 0.4 ms typical, 3 ms max; at least 100,000 erases per sector; opcodes 06h, 20h, 02h, 05h | Winbond datasheet |
| Overwrite in place, one save a minute | 10,000 erases last 10,000 minutes, 6.9 days | Chapter 3 arithmetic |
| NVS record | 8 bytes of metadata plus the data; 4-byte value = 12 bytes; 170 records per 2 KB page; two pages give 340 saves per erase; 6.5 years at one save a minute | Zephyr NVS documentation, Chapter 3 |
| LittleFS metadata | 32-bit revision count; CRC-32 polynomial 0x04c11db7, start 0xffffffff; newest valid revision wins; small files stay inline (design document: under 1/4 block; code: capped by cache_size and block/8); pair splits at 50% full; block_cycles 100 to 1000 | LittleFS SPEC.md, DESIGN.md, lfs.h |
| The torn write | 20 → 24 cut after the first byte reads 0xFFFFFF18 = −232 | Chapter 2, this lesson’s model |
| Term | Meaning |
|---|---|
| Erase block | The smallest piece of flash you can erase. Vendors call it page or sector. |
| Program unit | The smallest piece you can program in one go: 4 bytes, 8 bytes or up to 256 bytes, by part. |
| Torn write | A write cut part way, leaving a blend of new and old or blank bytes. |
| Commit | The one small last step that makes a new record the truth. |
| Journal | An append-only log where the newest labelled record wins. |
| Copy-on-write | Write a new version elsewhere, then switch to it. Never change the live copy. |
| Wear levelling | Spreading erases over many blocks. Dynamic uses free blocks; static also moves cold data. |
| Metadata pair | Two blocks plus a revision number: the LittleFS way to commit atomically. |
| CTZ skip-list | A file stored as blocks that point back by powers of two. |
c/* The whole idea. Everything else in this lesson is a way to make these four lines safe. */ spare = other_slot(newest_valid()); /* 1. never write where the truth lives */ flash_erase(spare); /* 2. a cut here is harmless: the truth is untouched */ flash_write(spare, body, len); /* 3. body first: nobody trusts it yet */ flash_write(spare + len, &crc, 4); /* 4. the commit, last: now it is the truth */
Most microcontroller products use one of three stores. A fixed A/B slot pair, as in Chapter 8, for a handful of settings. A key-value journal, such as Zephyr NVS, when you have many small values. A filesystem, such as LittleFS, when you have files and directories. SD cards and eMMC chips hide all of this inside a controller that levels wear for you. Linux on raw flash has its own stack; see the embedded Linux lesson.
The next lesson, Bootloaders and OTA, uses these patterns to replace firmware itself: a dual-bank swap is a copy-on-write of the whole program. Secure boot adds signatures to the commit. Testing firmware builds the cut-everywhere harness properly. On-device calibration stores factory coefficients with these rules, and store-and-forward sync logs data to flash until a phone is in range. Earlier lessons: Reset to main() for the flash rules, where memory goes, and the embedded systems introduction.
Everything above comes from primary sources and the lesson’s own model.
The flash, the journal and the copy-on-write blocks in this lesson are models, built from the rules in those sources. Toy sizes and times that are not in a source are marked illustrative where they appear. Written as part of the Engineermaxxing Firmware from Zero to Expertise series.
Now press Teach and explain one save out loud, from memory: why overwrite fails, what the commit step is, why a journal never leaves you without a value, and how you would test your own design. Then go back to the hero, pick Journal and press Try every cut point, and say why no cut loses the setting.