Module 10 · Lesson 32 of 112

The free-list frame allocator

Build a Rust frame allocator that reuses a reserved boot region through constant-time list operations, then verify exhaustion and reuse in QEMU.

  • Beginner to advanced
  • 10 min read
  • 48 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, the module's Rust toolchain and QEMU setup, and the kernel's boot memory map and PhysFrame type

Your place in the module
By the end you can 4 objectives
  • Initialize an in-frame linked list from an exclusively reserved boot memory range.
  • Implement alloc_frame and dealloc_frame with constant-time list updates.
  • Explain when to clear frame contents and how double frees and leaks affect the allocator.
  • Verify frame uniqueness, exhaustion, zeroing, and reuse with an in-kernel self-test.
Video coming soonThe free-list frame allocator
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from PhysFrame and the bump allocator
  • A 4 KiB frame starts at a physical address whose low 12 bits are zero
  • An order-k block contains 2^k frames and starts on a boundary of its own size
  • A successful bump allocation advances the cursor by the number of frames granted
01

Build the free list at boot

3 min read

The last lesson bumped and never freed. Now you store the next-free pointer inside each free frame so alloc pops and dealloc pushes, and see how fragmentation and per-hart arenas enter.

A kernel needs to distinguish memory it can allocate from memory that already holds something it needs to keep. Linux on Ubuntu 24.04 handles this distinction during early boot through memblock, which tracks memory and reserved regions before the normal page allocator takes over. In this module's freestanding Rust kernel, the same boot-time problem gives us a concrete starting point. Pick one usable RAM interval, set it aside for the frame allocator, and write a link into each frame in that interval. Linux 6.8 boot time memory management

An has a fixed capacity here. Managed frames all have the same size, and the list uses last-in, first-out order, so the arena behaves like a stack of available frames. Once a frame is allocated, the caller can use the whole frame. The allocator uses its first machine word only while the frame is free. The arena keeps the range bounds and one head value outside the managed region. An empty head represents an empty list.

Use a half-open interval [start, end). Begin with a usable RAM interval from the boot map, after excluding occupied and reserved ranges such as the kernel image, boot stacks, and any boot data still in use. Round the start up and the end down to whole-frame boundaries, checking for overflow when rounding up. If there is no whole frame left, the arena can start empty. Give the resulting interval exclusively to this allocator before writing any links. If the kernel also tracks available memory elsewhere, remove that range from the other allocator's supply. Otherwise, two allocators can issue the same frame even when their individual lists are correct.

A reserved frame arenahigherExcluded memoryFrame arenaWhole frames owned by allocatorlowerExcluded memoryhigherExcluded memoryFrame arenaWhole frames owned byallocatorlowerExcluded memory
The allocator takes exclusive control of a whole-frame interval inside usable RAM before writing links

Use the PhysFrame representation from the previous lesson for the API. For the link stored inside each frame, one concrete encoding uses a machine-word slot number relative to the arena. Reserve zero for the end of the list. Encode the frame at start as one, the following frame as two, and continue in address order. This is a next-frame pointer encoded as an index. It allows a single word at the front of each frame to represent either a successor or the end. To decode a nonzero slot, subtract one, multiply by the frame size, and add the result to start. A slot must be within the arena's frame count before it is used to address memory.

Reading or writing the link requires a CPU-accessible address. PhysFrame identifies physical memory, and the conversion to a dereferenceable pointer belongs in a small helper. In a boot context where physical RAM is directly accessible at the same address, that helper can use the physical address. With translation enabled, use the kernel's valid writable mapping for that RAM. Keep this mapping valid while the allocator uses it, and ensure the first word is suitably aligned for a machine-word read or write.

Start with an empty head. Walk the region from lowest to highest frame and insert each frame at the head. For each frame, write the old head into its first word, then make the encoded slot of that frame the new head. After the pass, the highest frame is first and the lowest frame ends the list. Initialization takes O(n) time for n frames. It needs no heap allocation, and there is no reason to clear the full region during this pass if allocation will clear each frame before returning it.

02

Allocate and free a frame

4 min read

Use alloc_frame(&mut self) -> Option<PhysFrame> and dealloc_frame(&mut self, frame: PhysFrame) as the core API. In this version, deallocation should be an unsafe Rust method if a PhysFrame value alone cannot prove the caller owns a live allocation from this arena. Document the precondition precisely. The frame must currently be allocated by this arena, and the caller must have stopped all other users of the frame before returning it. A range and alignment check can reject bad addresses. Checking whether a valid address is currently allocated requires additional state.

The list invariant gives you a way to reason about both methods. Every available frame occurs exactly once in the chain reachable from the head. Every allocated frame is absent from that chain. Each link is either an in-range slot or the end marker, and following links eventually reaches that marker. When you allocate or free, check which frame changes membership and where its successor comes from.

List membership before and after each updateInitial listHeadABEndAllocate AHeadBEndFree AHeadABEndRead each row from the head through successive links.
Allocation advances the head to the saved successor, and deallocation links the returned frame to the old head

In alloc_frame(), return None immediately if the head is empty. Otherwise decode the head and read the link from the corresponding frame's first word. Set the head to the saved successor. If the API promises zeroed memory, clear the entire frame now through its writable mapping, then return the PhysFrame. Reading the link before clearing is essential. With the encoding above, clearing first changes the link to zero and makes every remaining free frame unreachable. Returning None on an empty list leaves the allocator ready to accept a frame again.

In dealloc_frame(), check that the address lies inside the arena and is frame-aligned. Encode it as a slot, write the current head into the frame's first word, then update the head to that slot. Store the link before publishing the new head. The next allocation returns this frame first because the list uses last-in, first-out ordering. Each call changes only the head and one frame's list word. The list work takes O(1) regardless of how many frames are free. Clearing is a separate cost proportional to the number of bytes cleared. The frame size is fixed for this allocator, so that cost also stays independent of the number of free frames.

Clearing on allocation gives every caller the same guarantee and removes data left by the previous owner. The clear must cover the first word too, since it held the allocator link, and must reach the last byte. You can defer this work with a separate raw allocation path, provided its callers explicitly initialize or clear the necessary bytes before reading them or exposing the memory to another domain. For the lab, use eager clearing. A test can then write a nonzero pattern into a frame, return it, allocate it again, and check every byte before making any new writes.

A double free differs from an out-of-range free because both calls can pass the address checks. If you push frame A twice in succession, the second push stores A's slot as A's successor. The head points to A, and popping A sets the head back to A. The allocator can now issue the same physical frame to multiple callers. With eager zeroing the damage is wider. The first pop of A zeroes A's link word, so the second pop returns A again but reads a zero link, which ends the list, and every other free frame becomes unreachable. In a QEMU run of the lab allocator, a double free of one frame made the next two allocations return the same frame and the third return None. If a caller keeps writing through an old mapping after a valid free, even one write to the first word can corrupt the list. A debug build can keep a separate allocation-state bit for each frame and assert that a frame is allocated before pushing it. The state needs to be outside the frames that callers can write.

A leak goes the other way. If a caller loses track of a frame without returning it, the frame stays absent from the list, and future allocations exhaust the arena sooner. Test this by counting distinct frames through exhaustion, holding their handles in a fixed-size array outside the arena. After returning them, count again. Comparing the number of distinct frames with the arena capacity detects lost frames. Checking uniqueness also detects repeated addresses that would otherwise make a fixed-length allocation loop appear successful.

03

Understand the limits of one free list

3 min read
Going deeperExplore the mechanism

occurs whenever a caller needs less than the full frame it receives. Rounding one positive byte count up to a whole number of frames wastes less than one frame for that request, assuming frame-size alignment is sufficient. A free frame's link consumes no space in the caller's allocation because that word becomes available when the frame leaves the list. A variable-size free-list allocator can also have internal fragmentation when it rounds for alignment or gives a caller a block whose leftover space is too small to split usefully.

can affect a variable-size free list as allocations split blocks and later frees leave holes between live blocks. Total free space can exceed the request while every free block is too small. Fixed-size single-frame requests avoid that problem because any free frame can satisfy one. As soon as a caller needs consecutive physical frames, the problem returns. List order records insertion order, so even adjacent entries in the list can represent nonadjacent frames in RAM.

Physical adjacency and free framesPhysical orderFirstMiddleLastFrame stateFreeAllocatedFreeFree run startsHereNoneHere
Two free frames can satisfy two single-frame requests while a live frame between them prevents one contiguous pair

A bitmap represents availability in physical frame order using one bit per frame. It can identify a contiguous free run by examining adjacent bits, and it keeps unused full frames individually available. A bitmap alone does not prevent external fragmentation, because live frames can still divide free runs. A buddy allocator uses aligned power-of-two blocks and merges free buddies when both become available. In the usual buddy model, rounding a request to its next power-of-two frame count gives a block smaller than twice the request, with zero rounding waste for an exact power of two. Coalescing restores larger aligned blocks when possible. A large contiguous request can still fail. Linux organizes physical memory into nodes and zones, as its physical memory documentation describes, and /proc/buddyinfo lists how many free blocks of each order its buddy allocator holds. Linux 6.8 physical memory documentation

A single arena also assumes exclusive access while its head is being updated. Two harts popping the same shared head without synchronization can both return the same frame. A per-region arena avoids that race on the allocation path when each region has exactly one operating hart. At boot, reserve disjoint regions and give each hart its own arena state. A hart allocates and frees from its private list without taking a shared lock, provided code on that hart cannot reenter the allocator during an update. If an interrupt handler can allocate from the same arena, it needs local exclusion or a separate arena. A frame released on another hart still has to reach its owning arena through a synchronized handoff if cross-hart frees are allowed. The trade-off is that one private region can run out while another has free frames. M10-S08B returns to the boot hart and secondary harts, where those ownership decisions become relevant to kernel startup.

When you test the allocator, ask what reaching None actually proves. It proves the head is empty at that instant. To establish that every frame was available and returned exactly once, also compare the distinct addresses with the reserved range and repeat the check after recycling frames in a different order.

The next lesson, Bitmap and buddy allocators, asks how to track free physical memory when a kernel needs to find consecutive frames as well as reuse individual ones.

Key takeaways

  • Each free frame stores the next link in its first word.
  • An allocation pops the head and a deallocation pushes a frame onto it.
  • Clearing a frame must happen after reading its link and before handing it to a caller who expects zeroed memory.
  • Single-frame allocations need no contiguous run of free frames, but a multi-frame request can fail despite sufficient total free memory.
Reflect
  1. Explain to a colleague, in two sentences: initialize an in-frame linked list from an exclusively reserved boot memory range.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close