
Recall first from The allocator contract and a bump heap
- A successful nonzero allocation provides aligned storage that remains at the same address while the allocation is live.
- GlobalAlloc::alloc requires a nonzero layout size, while an interface that supports successful zero-size requests can use a non-null, aligned sentinel.
- GlobalAlloc::dealloc requires the original pointer and layout even when the allocator ignores both.
What the heap stores in each block
3 min readThe last lesson bumped and never freed. Now you store a size header in each free block, split on alloc, coalesce on dealloc, and keep the returned pointer aligned.
On Ubuntu, malloc(3) describes how a program releases a block with free so the memory can be reused. posix_memalign(3) describes requests that also specify an address alignment. The course kernel has to solve both problems inside its reserved heap. A request needs a single contiguous range at a suitable address. Even if the heap has enough free bytes in total, those bytes may be spread across ranges that are individually too small.
In this design, every block is a header followed by a payload region. The header holds the total block size in bytes, including the header, and a second field interpreted as either an allocated marker or the link to the next free header. The allocator returns the payload address. It keeps the allocated header so that deallocation can recover the actual span, including any bytes reserved for padding. The allocator's list head points to the lowest-address free header, and only free blocks appear in that list.
A concrete layout for the RV64 kernel is a #[repr(C)] header with two usize fields, size and used_or_next. Store a heap-relative byte offset in the second field for free blocks. Reserve usize::MAX for the end of the list and usize::MAX - 1 for the allocated marker, and keep the managed region small enough that neither value can be an offset. Offset zero can name the first block. Derive in-heap pointers from the original heap base and validated offsets. Use size_of and align_of to obtain the header size H and alignment A. For these two fields on RV64, H is 16 bytes and A is 8 bytes.
During initialization, trim the managed range inward to aligned boundaries and create one free header spanning that entire range. The managed range needs room for at least one header. As the heap changes, every block begins at an A-aligned address and has a span that is a multiple of A. Together, the free and allocated spans cover the managed range without overlap. A free span may be as small as H because the two fields fit there. Such a span cannot serve a nonempty allocation by itself, but it can still be linked and later merged.
Store free blocks in ascending address order. A link can skip over one or more live allocations, so following a link tells you which free block comes next in the list. Finding the end of a block is a separate calculation. Add its stored span to its starting address. That calculation is what lets the allocator tell whether two free neighbors in the list also touch in memory.
How allocation splits a free block
3 min readFor each candidate, calculate where the payload and its header would go before changing any links. A candidate fits only if it can hold the aligned payload, its header, and any padding that the allocator must reserve. First fit stops at the first usable candidate. Best fit, defined here as choosing the smallest usable original span, scans the list and keeps the best candidate found so far. With an address-ordered list, you can break ties by taking the lower address. Either policy uses the same split operation, and either can require a full scan. The lab uses first fit.
Within the candidate, distinguish three ranges. A prefix lies before the allocated header. The allocated span starts at that header and includes the requested bytes and any end padding. A suffix lies after the allocated span. Keep each nonempty remainder as a free block if it can hold a header. If the suffix is shorter than H, extend the allocated span to the end of the candidate and record that larger span in the allocated header. A short prefix requires a different placement because deallocation expects the allocated header immediately before the payload.
Going deeperExplore the mechanism
Let b and end be the start and exclusive end of one candidate, expressed as addresses for the alignment calculation. Let L = max(layout.align(), A). Compute p = align_up(b + H, L) and put the allocated header at h = p - H. For a power-of-two L, align_up(x, L) adds L - 1 with checked arithmetic and clears the low bits using & !(L - 1). Align the absolute address, or account for the base address explicitly when calculating with offsets. An aligned offset alone gives no alignment guarantee if the base has a different alignment.
Because H is a multiple of A, both p and h are header-aligned. The usable payload starts exactly H bytes after h. If h - b is zero, the allocated header reuses the original header slot. If h - b is at least H, the original slot holds the free prefix header. If 0 < h - b < H, recompute p = align_up(b + 2 * H, L) and h = p - H. This moves the header far enough forward to retain the prefix as a free block. If the new placement exceeds the candidate, continue the search.
For an alignment of 8, b + 16 is already aligned on this kernel. For an alignment of 16, it is aligned when b is a multiple of 16. When b is 8 bytes past a multiple of 16, the first placement leaves an 8-byte prefix, too small for the 16-byte header. The recomputed placement leaves a 24-byte prefix. For an alignment of 4096 and a candidate starting on a 4096-byte boundary, the payload starts 4096 bytes after b and the header starts 16 bytes before the payload. The resulting 4080-byte prefix stays available for other requests. Those values follow from the layout and illustrate the calculation.
Compute alloc_end = align_up(p + layout.size(), A) so any suffix header is aligned as well. Treat overflow or an end beyond the candidate as a failed fit. After checking these bounds, apply the short-suffix rule and store alloc_end - h using the final end. Derive the header and payload pointers from the original heap base using the checked offsets. Keeping the header immediately before the payload means dealloc can recover it by subtracting H, even for a request aligned to 4096.
When committing the split, save the candidate's old next link before writing any header. Replace the candidate's node with whichever remainders survive, in address order, and link the last remainder to the saved successor. If neither survives, link the predecessor directly to that successor. When the candidate was the first free block, update the list head in place of a predecessor's link. Write the allocated marker and actual span, then return the payload pointer. If the scan finds no fit, return a null pointer with the list intact.
How deallocation restores contiguous free space
4 min readThe pointer passed to dealloc identifies the payload of a live allocation. Subtract H to locate its header, then read the stored span to find its end. The original Layout gives the caller's requested size and alignment. The stored span also includes the header, end padding, and any short suffix absorbed during allocation. Using that span ensures the returned range covers exactly the bytes reserved for the allocation.
Walk the address-ordered list to find the free predecessor and successor of the returned span. Insert the span between them, writing its free link in the old allocated header. If there is no predecessor, make it the head. First check the neighbor on the right. If the returned span ends exactly where the successor begins, add the successor's size to the returned span and take the successor's next link. Then check the neighbor on the left. If the predecessor ends exactly where the returned span begins, add the returned span's updated size to the predecessor and link the predecessor to the updated successor. The surviving header is always the lowest-address header of the merged range.
Suppose three consecutive blocks are called A, B, and C in memory order. Free A and C while B is still live. A's link may now point straight to C, but the end of A is the beginning of B, so A and C stay separate. When B is freed, it first absorbs C. A then absorbs the combined B and C span. One free node now describes all three original ranges. Releasing the same three blocks in another order yields the same single span because every deallocation checks both boundaries.
This merging operation is combining free blocks whose address ranges touch. It reduces external fragmentation, which occurs when free memory is divided into separate ranges by live allocations. It cannot combine ranges across a live allocation. A useful diagnostic is to inspect both total free span and largest free span. The first measures how much space the list represents. The second bounds the contiguous space available for an allocation, with the header and alignment still to account for.
Install the allocator in the existing kernel by replacing the bump allocator's #[global_allocator] static with one whose GlobalAlloc methods delegate to the new heap. Initialize the region once before the first allocation. Keep list reads and writes exclusive across each operation. For a boot-hart lab, keep allocator calls on that hart and out of interrupt handlers. If the kernel already shares the heap across harts, use its synchronization around the entire search and update. The allocator's internal state and diagnostics must avoid heap allocation, since a recursive call could enter while the list is being changed.
For direct tests, use Layout::from_size_align and match each successful allocation with one deallocation using the same layout. Check alignment and write distinct contents to live payloads. Fill an isolated heap until no further request of the chosen size fits, then free neighboring blocks and request a size that requires their combined span. Keep the other allocations live so a successful request demonstrates reuse of the merged space. After all the direct allocations are freed, inspect the list for one free span covering the initialized range.
For the kernel integration test, bring Box, Vec, and String into scope from alloc::boxed, alloc::vec, and alloc::string, respectively. Use a nonzero-sized boxed value, push values into a vector, and append text to a string. Assert that you can read each value back, then drop the objects or end their scope. Compare free-list snapshots around that scope where you control other allocation activity. The collection test checks the normal entry points. The direct tests give you precise control over allocation sizes, alignment, and the order of frees.
This heap can reuse variable-sized ranges, with a list walk to find space and another to reinsert a freed range. “Fixed-size and buddy heaps” follows by asking how organizing free memory by size changes the search and the way blocks are combined.
Key takeaways
- Each header records the full block span, including the header itself.
- First fit stops at the first usable block, while best fit scans for the smallest usable block.
- An aligned payload can have its header immediately before it, with a representable free prefix retained.
- Coalescing combines free blocks only when their byte ranges touch.
Reflect
- Explain to a colleague, in two sentences: draw the header and payload of a free block and an allocated block.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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
- Man pagemalloc(3): allocating and releasing memory
- Man pageposix_memalign(3): allocating aligned memory
Official documentation first. Links checked when the lesson was published.