Section 8.16

Garbage collection

Definition

Garbage collection, in storage that saves every change as a new record, is the process that reclaims the space taken by obsolete records, those that a newer record or a deletion has replaced. Flash memory §6.6 erases only whole erase blocks, so the collector picks a region, copies the live records in it (those that still hold current values) to free space elsewhere, and then erases the region for reuse. Programming languages use the same name for automatically freeing unused working memory, a different mechanism with the same goal.

The idea

A device logs every change of its settings as a new record in four flash sectors. Eventually all four are full, although most records are obsolete: a setting changed a hundred times has one current record and ninety-nine dead ones. Collection makes that space usable again, at costs that ordinary writes do not have. It copies data, it erases, which on flash memory is slow, and it needs free space of its own to work in.

Collection trades work now for space later, and the trade depends on how much of the reclaimed region is still live. A region that is 90% obsolete yields almost a whole region for a few copies. A region that is 90% live costs nearly a region of copying and yields a tenth of one. A region that is entirely live yields nothing. That is why collection can delay service, and can fail outright when free space runs low.

How it works

A collector for a flash log runs these steps.

  1. Trigger: a write finds no room, or free space falls below a threshold and collection runs in the background.

  2. Choose a victim, the region to reclaim: a circular log §8.14 takes its oldest sector, and other designs take the region with the least live data.

  3. Find the live records: each record that is the newest record of its key (the name or number of the value it holds) and is not a deletion.

  4. Copy them outside the victim and read each copy back.

  5. Make the copies authoritative: recovery after a restart must select the copies, for example by their higher sequence numbers, and must be able to see that copying finished, for example from a completion marker.

  6. Erase the victim.

  7. Resume the waiting write.

Step 4 needs free space before step 6 creates any. Stores therefore keep a reserve, typically one erased sector, that ordinary writes never use. Without it, a store full of live data could free space only by erasing live records.

Power can fail during any step. Until step 6 the victim is intact. A torn copy is rejected by the record checks. An erase cut short is repeated, because every live record already has a checked copy. Recovery that finds no completion marker erases the partly filled destination and collects again. Repeating must give the same result as a single run, the property called idempotency §8.31. Power-loss injection §8.38, cutting the power at chosen points of a test run, checks these cases.

Worked example

Take the maximum times of the nRF52840 §6.4, a microcontroller §6.1 (a small computer on one chip): 41 microseconds to program a 4-byte word and 85 milliseconds (ms) to erase a 4096-byte page. An ordinary 24-byte record is 24/4=624 / 4 = 6 words, at most 6×41=2466 \times 41 = 246 microseconds, about 0.25 ms. A write that must first collect a victim holding 1000 live bytes programs 1000/4=2501000 / 4 = 250 more words, at most 250×41=10,250250 \times 41 = 10{,}250 microseconds, and erases once. It takes up to 0.246+10.25+85=95.4960.246 + 10.25 + 85 = 95.496 ms, about 390 times as long, plus the time to scan the victim. On many microcontrollers code cannot run from flash during an erase, so even interrupt handlers §6.12 (the routines that respond to hardware events) stored in flash can wait that long.

Now the space. A circular log has 3 sectors of 128 records of 32 bytes each, one sector kept as the reserve, so 256 record slots hold data.

Stated precisely

Let a region hold CC bytes of records, and let uu, with 0≤u≤10 \le u \le 1, be the live fraction of the victim. Collection copies uCuC bytes and frees (1−u)C(1 - u)C bytes, so for u<1u < 1 it copies uC(1−u)C=u1−u\frac{uC}{(1 - u)C} = \frac{u}{1 - u} bytes per byte freed: 1 at u=0.5u = 0.5, 3 at u=0.75u = 0.75, 9 at u=0.9u = 0.9, growing without bound as uu approaches 1. At u=1u = 1 it frees nothing. With SS regions, one of them the reserve, a new record of rr bytes can be accepted only if the live data VV satisfies V+r≤(S−1)CV + r \le (S - 1)C.

Let tpt_p be the time to program one write unit of ww bytes, tet_e the time to erase one region, rr the size of the record and ⌈x⌉\lceil x \rceil the number xx rounded up to a whole number. An ordinary write takes ⌈r/w⌉tp\lceil r / w \rceil t_p. A write that triggers one collection takes up to ⌈r/w⌉tp+⌈uC/w⌉tp+te\lceil r / w \rceil t_p + \lceil uC / w \rceil t_p + t_e, plus the scan. If a write may trigger kk collections, add kk collection times; in the current Zephyr NVS source, kk is the number of sectors. These bounds assume that nothing else uses the flash or the processor meanwhile.

The safety contract: at every moment, even inside a collection cut short, each key with a current value has a complete, valid record of that value outside any region being erased, and recovery selects that record or one with the same value. The victim is erased only after each of its live records has a checked copy that recovery will select.

Limits and common mistakes

Write times become uneven, and an average hides the rare slow write. Deadlines must be checked against the slow case, counted in the worst-case execution time §9.33 of the code that waits. Background collection moves the cost away from urgent writes but does not remove it.

Copies are writes that nobody asked for. The write amplification §8.18 entry measures them, and the extra erases add flash wear §8.17. Because victims that are 90% live cost 9 bytes of copying per byte freed, designs keep total live data well below capacity.

A deletion record may be discarded only when no older record of its key remains anywhere; otherwise the deleted value returns after a restart.

A copy must never look newer than a value that the application writes meanwhile. Running collection and ordinary writes under one mutex §9.5, a lock that lets only one of them run at a time, guarantees this.

Questions answered

Can collection interrupt service or fail when free space is too low?

Yes, it can do both. Collection delays service because it usually runs inside the write that found no room, and that write must copy the victim’s live records (those still holding current values) and erase the victim before it finishes. With the maximum times of the nRF52840 microcontroller, a write that normally takes about 0.25 milliseconds can take about 95 milliseconds, and on many microcontrollers code that runs from flash memory must wait during the erase.

Collection fails when free space is too low because it needs somewhere to copy live records before it can erase. If the victim’s live fraction is uu, each byte freed costs u/(1−u)u / (1 - u) bytes of copying, 9 bytes at u=0.9u = 0.9. When live data fills every region outside the reserve, nothing can be freed, and the store must refuse the write. Designs keep a reserved erased region, keep live data well below capacity, refuse writes rather than erase live data, and count collection in the worst-case time of every write.

Related entries: Circular log (§8.14), Flash wear and endurance (§8.17), Write amplification (§8.18), Crash consistency (§8.4). Further reading: [12, 56].