9. Heap and sbrk
Why this layer exists
Chapter 7 gave a process three pages by bumping a pointer past the page-table pool, and chapter 8 gave two processes six the same way. A pointer that only moves up is not an allocator: nothing ever comes back, and the kernel has no answer to “how much is left.” Every object from here on needs pages that can be handed out and taken back — a pipe’s ring buffer (chapter 10), the block device’s ring and its buffers (chapter 11), the fresh address space spawn builds (chapter 13) — and each needs them at run time, in an amount the link script could not have known.
malloc is not a law of nature. It is a library over a smaller thing the kernel provides, and the smaller thing is this chapter: physical pages, one at a time, from a region the kernel owns, into a page table the kernel builds with the frozen walk. The shape — a page-granular freelist over a physical region — is the one hearth uses to carve guest memory in chapter 34. The object outlives the kernel it was born in; what changes later is the name of the thing the page is given to.
Mechanism
The page is the unit
The MMU’s unit is the page, and the walk maps pages, so a kernel allocator that dealt in bytes would be lying about the granularity underneath it. Everything in this chapter is 4 KiB: the allocator hands out page-aligned physical addresses, sbrk grows a heap by whole pages, and the kernel never splits one. Sub-page allocation is a user-space concern — a malloc in the libc stub, when chapter 13 wants one — layered over sbrk exactly as it is layered over brk on Linux.
The link lives in the page
An allocator needs to know which pages are free. The obvious structure is a table — a bitmap or an array of flags — and it has a problem this early in a kernel: it has to be sized and placed before anything is allocated, which means the link script or a boot-time carve, which means one more number that moves with the image. The freelist avoids the table by using the pages themselves. A free page is, by definition, memory nobody is using; its first eight bytes can hold the physical address of the next free page. The free region describes itself, the head pointer is the whole allocator state, and both operations are a pointer swap:
struct run {
struct run *next;
};
static struct run *freelist;
static unsigned long nfree;
void kfree_page(unsigned long pa)
{
struct run *r;
/* Alignment and range are the only checks. A page freed twice is
* pushed twice and the list becomes a cycle — exercise (a). */
if ((pa & (PAGE_SIZE - 1)) || pa < KALLOC_FLOOR || pa >= KALLOC_CEIL)
halt(1);
r = (struct run *)pa;
r->next = freelist;
freelist = r;
nfree++;
}
unsigned long kalloc_page(void)
{
struct run *r = freelist;
unsigned long *w = (unsigned long *)r;
unsigned long i;
if (!r)
return 0; /* empty: the caller fails loudly, never wraps */
freelist = r->next;
nfree--;
for (i = 0; i < PAGE_SIZE / sizeof(unsigned long); i++)
w[i] = 0; /* the link goes too */
return (unsigned long)r;
}
kfree_page pushes; kalloc_page pops. The push writes the link into the page, through the kernel’s identity map, and that is where the design’s one cost lives. A page just popped from the list still holds that link in its first word — a kernel physical address, the next free page’s — and a moment later it is a U page. Hand it out unzeroed and every process gets a peek at the kernel’s free-page chain: one word per allocation, but a word that says where the next allocation will land. kalloc_page zeroes the page before returning it, link included, and the probe program checks the first and last words are zero as its first act — not because zero-fill is decoration but because the alternative is a leak. QEMU zeroes DRAM at start, so on this board only the link would have been non-zero; on a warm reboot it would be whatever ran last.
The zeroing has a second consequence, less obvious, that exercise (a) turns into a demonstration: a page freed twice is pushed twice and appears to make the list a cycle, but the next pop zeroes the page and with it the link that was the cycle — and everything the list held beyond that page is orphaned.
A constant floor
Where does the free region start? The obvious answer is the end of the image — pt_pool_end, the last link-script symbol — and it is the wrong answer for this book. That symbol moves with every chapter’s code size, and the allocator’s bounds appear in the transcript. A capture that pinned pt_pool_end would fail any correct mine/ whose code was a different size, before its stub ever ran; which is why chapter 2 alone pins link-time addresses — its subject is the layout — and no later capture does.
void kalloc_init(void)
{
extern char pt_pool_end[];
unsigned long pa;
/* The floor is a constant so the transcript never depends on code
* size; this is the check that keeps it honest. */
if ((unsigned long)pt_pool_end > KALLOC_FLOOR) {
uart_puts("S: kalloc: image past the floor\r\n");
halt(1);
}
/* Chapter 4 mapped one page of this region, 0x81000000, U=1 in
* the identity map — named for a process, never used. The kernel
* cannot write a freelist link through a U leaf without SUM
* (cause 15), so the page comes back to the kernel first. */
map_page(CH4_USER_PAGE, CH4_USER_PAGE, PTE_R | PTE_W | PTE_X);
__asm__ volatile("sfence.vma" ::: "memory");
for (pa = KALLOC_FLOOR; pa < KALLOC_CEIL; pa += PAGE_SIZE)
kfree_page(pa);
uart_puts("S: kalloc ");
uart_puthex(KALLOC_FLOOR);
uart_puts("..");
uart_puthex(KALLOC_CEIL);
uart_puts(" pages=");
uart_puthex(nfree);
uart_puts("\r\n");
}
So the floor is a constant, 0x80400000 — 4 MiB into DRAM — and the ceiling is -m 128M’s end, 0x88000000. The image is nowhere near 4 MiB, but “nowhere near” is not a proof; the boot assertion is. If a later chapter ever grows the image past the floor, the kernel says so and stops, and the constant moves by a DECISIONS.md line, not by silent drift. The region is 31744 pages, 0x7c00, and the transcript says so in a line no reader’s code size can change.
One page in that region is special, and the allocator has to know it. Chapter 4 mapped 0x81000000 into the identity map with U=1 — a user page, named for a process that chapter 7 never used, because chapter 7 carved fresh pages instead. It is inside the free region, and kfree_page’s link store through the identity map is an S-mode store to a U page: cause 15, the SUM rule from chapter 4, this time biting the kernel’s own bookkeeping. The kernel could not write its free-page chain through a leaf it had given away. kalloc_init takes the page back — remaps it U=0, fences — before weaving the list. That the same rule that protects the kernel from a user pointer also stops the kernel from writing through a U leaf it forgot about is the U bit doing exactly its job.
The break
A process’s heap is one contiguous range of virtual addresses that grows upward from a fixed point. The point is the break: the first address above the process’s stack page, va + 0x2000 — 0x12000 for the first program — set in proc_create and moved only by sbrk. sbrk(n) maps n fresh pages at the break, moves it up, and returns where it was: the start of the new pages. sbrk(0) reads it.
/* Grow the calling process's heap by npages, U|R|W and never X, and
* return the old break — the start of the new pages. sbrk(0) reads
* the break. On an empty freelist the pages already mapped stay the
* process's and brk already covers them; -1 says the request was not
* met in full. Shrinking is named, not built. */
static long sys_sbrk(long npages)
{
unsigned long old = curproc->brk;
long i;
if (npages < 0)
return -1;
for (i = 0; i < npages; i++) {
unsigned long *slot = walk(curproc->brk);
unsigned long pa;
/* One table for everyone: the break can run into the kernel's
* own low maps (the finisher at 0x100000 is 238 pages up from
* the first program's heap) or another process's pages. A
* slot that is already valid is refused, never overwritten. */
if (!slot || (*slot & PTE_V)) {
uart_puts("S: sbrk: break hit a mapping\r\n");
return -1;
}
pa = kalloc_page();
if (!pa) {
uart_puts("S: sbrk: out of pages\r\n");
return -1;
}
map_page(curproc->brk, pa, PTE_R | PTE_W | PTE_U);
curproc->brk += PAGE_SIZE;
}
__asm__ volatile("sfence.vma" ::: "memory");
return (long)old;
}
Three decisions in that function are the chapter’s. The pages are U|R|W and never X: heap memory is data, and a process that could execute what it wrote into its heap could execute what a pipe or a file put there too. Nothing enforces that distinction yet — exercise (e) shows the transcript does not change if you add X — which is exactly why the flag is set correctly now, before chapter 13 loads programs from a disk and the distinction starts to matter. The second: on an empty freelist the pages already mapped stay the process’s, the break already covers them, and -1 says the request was not met in full — a partial sbrk is still an sbrk. Shrinking the heap is named and not built; nothing in Part II frees a heap page before the process dies.
The third decision is the guard, and it exists because ember has one page table. Chapters 7 and 8 said the U pages are private to a process only by convention, since every process and the kernel share the same tree. The break makes the sharing concrete: 0x12000 upward is the first program’s heap, and 238 pages up from there is 0x100000, the finisher’s identity-mapped MMIO page — the kernel’s halt. Without the guard, sbrk would reach it, and map_page would overwrite the finisher’s PTE with a heap page; the next halt() is then an S-mode store to a U page, cause 15, in a handler that halts, forever. With it, a slot that is already valid is refused: S: sbrk: break hit a mapping, and the caller gets -1. Exercise (b) runs both. In chapter 8’s layout, where a second program sits 64 KiB above the first, the first heap has fourteen pages before it meets the second program’s code — a limit set by where the programs were linked, not by how much DRAM there is. Per-process page tables would dissolve that limit, and that is the design every production kernel uses; this one keeps a single table through Part II and says so wherever it costs something.
Who owns a page
A page is owned by whoever mapped it: the process, once sbrk puts it in the table. There is no reference count, because in this kernel a page has exactly one owner and is never shared — chapter 10’s pipe page is the kernel’s, copied through, and never mapped into a process. The count would be bookkeeping for a sharing that does not exist. What does exist is a leak: a process that exits leaves its pages mapped and its slot DEAD; chapter 8’s pick skips the slot, nothing frees the pages, and the next proc_create reuses the slot with fresh pages. Chapter 13’s wait is where a parent reclaims a child’s pages; until then the leak is named, small, and deliberate.
The page-table budget
Each new page the heap maps costs a leaf in a level-0 table, and each new 2 MiB region the heap enters costs a fresh level-0 table from pt.c’s pool — 512 KiB, 128 tables, fixed in link.ld. The walk is frozen and its pool cursor is private, so the kernel cannot ask pt.c how many it has used; it counts instead, walking from satp’s root: the root, every valid pointer entry in it, every valid pointer entry in those. That is a pure function of the maps, not of code size, and the transcript prints it twice — after the process is created and after it has exited — as 0x4a of 0x80. Part I’s identity map and MMIO windows took 74 tables; the first program’s pages landed in a level-0 table the finisher’s mapping had already created; the four heap pages are in the same 2 MiB region as the code, so sbrk cost no table at all. The number to remember is the one that is left: 54. Heaps that cross 2 MiB boundaries and more processes at more bases spend from it, and a chapter that prints a higher number is spending on purpose.
Where the process starts, and a build rule
The kernel enters a user blob at its first byte — proc_create fabricates sepc = va, and va is where the blob’s byte 0 was copied. The blob is the program’s .text followed by .rodata, so byte 0 is whatever the compiler emitted first in .text. Nothing guarantees that is _start: at -O2 GCC is free to emit a static helper ahead of the function that calls it, and when it does the blob’s first bytes are, say, a puts, and the process’s first instruction is a load through a0, which the fabricated frame set to zero — cause 13 at stval 0, sepc 0x10000. So _start is placed in a .text.start section by attribute, in every program, and the link script places that section first. The entry belongs at the front by construction, not by emission order.
One build rule goes with it: the user binaries depend on their sources in the kernel’s Makefile, so an edited program reaches the image on the next build. A transcript that came from a stale blob is not a transcript.
The probe itself:
int main(void);
int main(void)
{
unsigned long old = (unsigned long)syscall3(4, HEAP_PAGES, 0, 0);
unsigned long now = (unsigned long)syscall3(4, 0, 0, 0);
unsigned long *w = (unsigned long *)old;
unsigned long sum = 0, i;
puts("U: brk ");
puthex(old);
puts(" -> ");
puthex(now);
puts("\r\n");
/* A free page's first word held the kernel's freelist link; the
* last word is as far from it as the page goes. Both must be 0. */
puts(w[0] == 0 && w[WORDS - 1] == 0 ? "U: fresh page zero\r\n"
: "U: fresh page dirty\r\n");
for (i = 0; i < WORDS; i++)
w[i] = (i + 1) * MULT;
for (i = 0; i < WORDS; i++)
sum += w[i];
puts("U: sum=");
puthex(sum);
puts("\r\n");
syscall3(1, 0, 0, 0); /* exit */
return 0;
}
Four pages, a zero check at both ends of the new range, a pattern the reader can recompute — the sum over of — read back and printed. Every number in the transcript is a constant. The kernel’s side of the run is chapter 8’s launcher and loop, entered from a boot stage that prints the budget on either side:
mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
kalloc_init();
launch(user3_blob_start,
(unsigned long)(user3_blob_end - user3_blob_start),
USER_BASE, 0);
pt_report();
scheduler(); /* returns when the table is empty */
pt_report();
uart_puts("PASS\r\n");
halt(0);
scheduler() returns when its table is empty — the one behavioral change to chapter 8’s loop — and the caller decides what that means; here it means the probe exited and the lab passed. The scheduler is cooperative from this chapter on: nothing arms the tick, preempt_tick stays chapter 8’s, and a process runs until it yields, blocks, or exits. That is a choice, made here so chapters 10 and 13 inherit it knowingly.
Walkthrough
ch09-main (the boot stage: allocator, one launch, the loop, the budget on either side), ch09-kalloc-init (the assertion, the reclaimed page, the weave), ch09-freelist (push, pop, zero), ch09-sbrk (the guard, the break, the fence), ch09-heap-probe (four pages, two zero checks, one checksum). The regenerated ch07-proc-create shows proc_page — the carve for chapters 7 and 8, kalloc_page from here — and the break’s initial value.
Exercises
(a) Free a page twice, then allocate three times. Derive what the list does, then run it.
Answer
Pushed twice, the page’s link points at itself: x->next == x, a one-element cycle with the rest of the list hanging off the old head that is now unreachable behind it. The first pop returns x and sets the head to x->next, which is x again — and then zeroes the page, link included. The second pop returns x once more and sets the head to x->next, which is now 0. The third returns 0: the list is empty. Observed: 0x87fff000 0x87fff000 0x0, followed by S: proc_create: out of pages. The double free did not loop forever; it truncated the list at the duplicate and orphaned every page beyond it — the 31743 that were behind the first push. A freelist with the link in the page has no way to notice a double free without a scan; a bitmap would have refused the second free in one test. That is the trade the design made, and the exercise is where it shows.
(b) Ask for 40000 pages. Predict what stops you, then run it with the guard in sys_sbrk removed, and again with it present.
Answer
Not the allocator: 40000 is more than the 31741 pages the list holds, but the heap never gets that far. Without the guard, map_page walks up from 0x12000 and after 238 pages reaches 0x100000 — the finisher, identity-mapped by chapter 4 — and overwrites its PTE with a U heap page. The next kernel halt() is an S-mode store to a U page, cause 15, whose handler calls halt(): the transcript repeats S: unexpected scause=0xf until the timeout. With the guard, the 239th page is refused — S: sbrk: break hit a mapping — sbrk returns −1 with the break at 0x100000 and 238 pages mapped, and the probe, which trusts the return value, then dereferences −1 and faults in U with cause 13. Two lessons: in a one-table kernel the heap’s ceiling is the next mapping, not the amount of DRAM; and a refused sbrk is a return value the caller has to check.
(c) How many processes can this kernel hold, at three pages each plus a four-page heap?
Answer
Three answers, and the smallest wins. By physical memory: 31744 pages at 7 each is 4534 processes — the allocator is not the limit. By virtual layout: chapter 8 spaces programs 64 KiB apart from 0x10000, and the first kernel mapping above them is the finisher at 0x100000, so 15 slots fit, each with at most 14 heap pages before its break meets the next program’s code. By the table: NPROC is 4. The kernel holds four processes because a fixed-size array says so, could hold fifteen if the array grew, and could hold thousands only with per-process page tables, which it does not have. Each limit is a different object; knowing which one binds is the whole exercise.
(d) Why is there no reference count on a page, and what would it be for?
Answer
A count tracks sharing, and nothing in this kernel shares a page: every page has one owner — the kernel, or the process whose table maps it — and the owner is the only party that could free it. Chapter 10’s pipe is the counterexample that is not: the pipe page belongs to the kernel and the data is copied through it, so neither process ever maps it. The count would matter the moment two tables mapped one page (a shared library, a fork that copies on write, a zero page mapped everywhere), because then “who frees it” has no single answer. What this kernel has instead of a count is a leak: an exited process’s pages stay mapped in a DEAD slot until chapter 13’s wait reclaims them.
(e) Map heap pages U|R|W|X instead of U|R|W. What breaks?
Answer
Nothing, observably: the transcript is identical, PASS and all. The probe never jumps into its heap, and no other code in this chapter can put bytes there. That is the danger, not the reassurance. From chapter 10 a pipe can write bytes into a process’s heap on behalf of another process; from chapter 12 a file can; from chapter 13 a process is loaded from a file. A heap that is executable turns every one of those data paths into a code path, and nothing would fail until something exploited it. The flag is set correctly in the chapter where setting it costs nothing, so the chapters where it costs something inherit it.
(f) What does hearth change about this allocator, and what does it keep?
Answer
It keeps the object: a freelist of physical pages over a region the hypervisor owns, the link in the page, zero on hand-out. What changes is the boundary the page crosses. Here a page goes into a process’s table with U set and the process addresses it through satp. In chapter 34 a page goes into a G-stage table — the second walk chapter 19 builds — and a guest addresses it through its own satp and then through the hypervisor’s, and never learns the physical address at all. The zeroing rule gets stricter, not looser: a guest that saw a stale link would be reading the hypervisor’s free-page map from inside a VM. And the ceiling becomes a policy: how much of the machine each guest is allowed to take, which is chapter 37’s scheduling question in a different unit.
Lab
make lab CH=09
make lab CH=09 IMPL=mine
The transcript, after chapter 8’s boot lines: S: kalloc 0x80400000..0x88000000 pages=0x7c00, the constant bounds and the count; S: pt tables 0x4a/0x80 with the probe created; U: brk 0x12000 -> 0x16000, the old break and the new; U: fresh page zero, the first and last words of the new range; U: sum=0x1516cf4cac905400, the checksum; S: proc 1 exited; the budget again, unchanged, because four pages in one 2 MiB region cost no table; PASS. No clocks, no addresses that depend on code size — the floor and ceiling are constants and the table count is a function of the maps.
IMPL=mine copies exactly the objects chapter 9 links and stubs kalloc_page to print MINE: kalloc_page stub and halt. The lab boots, prints the allocator’s bounds — kalloc_init still weaves the list, since kfree_page is not the stub — and fails loudly at the first proc_page with no table count and no user lines.
Further reading
- The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (RISC-V International, v20260120, January 2026) — the
Ubit andsstatus.SUM(the rule that bit the allocator’s own link store),sfence.vmaafter PTE writes, the Sv39 page-table geometry behind the budget. - xv6-riscv (MIT PDOS) —
kernel/kalloc.cis the same freelist with the link in the page; xv6 fills freed pages with junk to catch use-after-free and zeroes onkallocfor the same reason this chapter does. Itssbrkgrows and shrinks; this one only grows, and says so.