Write a Physical Memory Manager With a Bitmap Allocator
Write a bitmap physical memory manager in C: place the bitmap in usable RAM, mark reserved and kernel frames, allocate and free 4 KiB frames, and allocate runs.

Before a kernel can build page tables, allocate a heap or load a program, it has to know which pieces of RAM are free and hand them out one at a time. That job belongs to the physical memory manager, the PMM, and it is the lowest layer of memory management: it deals in physical frames of 4 KiB, knows nothing about virtual addresses and exists so the layers above can ask for a frame and get one. This post writes a PMM with the simplest data structure that works, a bitmap with one bit per frame. It covers the whole life of the thing: finding room for the bitmap in the memory the bootloader reported, marking everything used and then freeing only the genuinely usable regions, protecting the kernel image and the bitmap itself, allocating one frame or a contiguous run and freeing frames again. The code is boot-protocol neutral: it takes an array of regions, whatever your bootloader produced. The map comes from parsing the memory map handed over by the bootloader, and the PMM is a layer of the guide to interrupts, memory and paging.
Why a bitmap
A physical allocator has to answer three questions fast enough: give me a frame, give me n contiguous frames and take this frame back. Several structures do that.
| Design | Allocate | Free | Metadata | Contiguous runs |
|---|---|---|---|---|
| Bitmap | Scan for a clear bit | Clear a bit | 1 bit per frame | Natural: scan for n clear bits |
| Free list stack | Pop | Push | 8 bytes per free frame, stored in the frames | Hard |
| Buddy allocator | Split blocks | Merge buddies | Per-order bitmaps or lists | Natural, power-of-two sizes |
A bitmap is the easiest to get right and to inspect: you can print it, and a bug shows as a wrong bit. It costs 1 bit per 4 KiB frame, or 32 KiB of bitmap per gigabyte of RAM, which is negligible. Its weakness is speed on large machines, since a scan for a free bit is linear in the worst case. A next_hint index keeps ordinary allocation near constant, and a hierarchical bitmap or a free list takes over when it matters. The buddy allocator, used by Linux, is the right step up when you need fast contiguous allocations of varying sizes.
The input
The allocator takes an array of usable regions and the kernel's own physical extent. Both come from the bootloader and the linker script, so the function interface is:
#ifndef PMM_H
#define PMM_H
#include <stdint.h>
#include <stddef.h>
#define FRAME_SIZE 4096UL
struct pmm_region {
uint64_t base; /* physical address */
uint64_t length; /* bytes */
};
/* regions: usable RAM only. reserved: ranges to keep out even if usable. */
void pmm_init(const struct pmm_region *regions, size_t nregions,
const struct pmm_region *reserved, size_t nreserved);
uint64_t pmm_alloc(void); /* one frame; 0 on failure */
uint64_t pmm_alloc_run(size_t n); /* n contiguous frames; 0 on failure */
void pmm_free(uint64_t phys);
void pmm_free_run(uint64_t phys, size_t n);
size_t pmm_free_frames(void);
size_t pmm_total_frames(void);
#endifPhysical address 0 is never handed out, so a return value of 0 can mean failure. That matches reality: the first frame holds the BIOS data area and the real-mode interrupt table on a PC, and keeping it reserved also catches null physical pointers.
The bitmap and its helpers
The bitmap is an array of bytes, one bit per frame, with 1 meaning used. Each frame number is the physical address divided by the frame size:
#include "pmm.h"
#include <string.h>
extern uint64_t hhdm_offset; /* physical memory is mapped at this offset */
static uint8_t *bitmap;
static size_t total_frames;
static size_t free_count;
static size_t hint;
static inline void bit_set(size_t f) { bitmap[f >> 3] |= (uint8_t)(1u << (f & 7)); }
static inline void bit_clear(size_t f) { bitmap[f >> 3] &= (uint8_t)~(1u << (f & 7)); }
static inline int bit_test(size_t f) { return (bitmap[f >> 3] >> (f & 7)) & 1; }
static void mark_used(uint64_t base, uint64_t length)
{
uint64_t first = base / FRAME_SIZE;
uint64_t last = (base + length + FRAME_SIZE - 1) / FRAME_SIZE;
for (uint64_t f = first; f < last && f < total_frames; f++) {
if (!bit_test(f)) {
bit_set(f);
free_count--;
}
}
}
static void mark_free(uint64_t base, uint64_t length)
{
uint64_t first = (base + FRAME_SIZE - 1) / FRAME_SIZE; /* round start up */
uint64_t last = (base + length) / FRAME_SIZE; /* round end down */
for (uint64_t f = first; f < last && f < total_frames; f++) {
if (bit_test(f)) {
bit_clear(f);
free_count++;
}
}
}The rounding is deliberate and asymmetric. When freeing a region, the start rounds up and the end rounds down, so only whole frames fully inside usable memory become free. When reserving, the start rounds down and the end rounds up, so any frame that overlaps a reserved range is protected. Getting these backwards frees a frame that is half firmware, and the bug appears much later, far from its cause. The functions keep free_count accurate by changing it only when a bit actually flips.
Initialization
The steps are: find the highest address to size the bitmap, find a usable region large enough to hold the bitmap and put it there, mark every frame used, free the usable regions, and finally mark used the reserved ranges and the bitmap's own frames.
void pmm_init(const struct pmm_region *regions, size_t nregions,
const struct pmm_region *reserved, size_t nreserved)
{
uint64_t top = 0;
for (size_t i = 0; i < nregions; i++) {
uint64_t end = regions[i].base + regions[i].length;
if (end > top)
top = end;
}
total_frames = top / FRAME_SIZE;
size_t bitmap_bytes = (total_frames + 7) / 8;
size_t bitmap_frames = (bitmap_bytes + FRAME_SIZE - 1) / FRAME_SIZE;
/* The bitmap must sit above 1 MiB and above every reserved range. */
uint64_t floor = 0x100000;
for (size_t i = 0; i < nreserved; i++) {
uint64_t e = reserved[i].base + reserved[i].length;
if (e > floor)
floor = e;
}
floor = (floor + FRAME_SIZE - 1) & ~(FRAME_SIZE - 1);
/* Find a usable region above that floor that can hold the bitmap. */
uint64_t bitmap_phys = 0;
for (size_t i = 0; i < nregions; i++) {
uint64_t base = regions[i].base < floor ? floor : regions[i].base;
uint64_t end = regions[i].base + regions[i].length;
if (end > base && end - base >= bitmap_frames * FRAME_SIZE) {
bitmap_phys = (base + FRAME_SIZE - 1) & ~(FRAME_SIZE - 1);
break;
}
}
if (!bitmap_phys)
return; /* no room: a real kernel panics here */
bitmap = (uint8_t *)(bitmap_phys + hhdm_offset);
memset(bitmap, 0xFF, bitmap_bytes); /* everything starts used */
free_count = 0;
for (size_t i = 0; i < nregions; i++)
mark_free(regions[i].base, regions[i].length);
mark_used(0, FRAME_SIZE); /* frame 0 is never allocated */
mark_used(bitmap_phys, bitmap_frames * FRAME_SIZE);
for (size_t i = 0; i < nreserved; i++)
mark_used(reserved[i].base, reserved[i].length);
hint = 256; /* start looking above 1 MiB */
}Starting from "all used" is the safe default: every frame the bootloader did not explicitly call usable stays out of circulation, including holes in the map that the firmware did not mention. The bitmap is reached through the direct map, phys + hhdm_offset, because by this point paging is on; a kernel before paging, or one with an identity map, uses the physical address directly. Placing the bitmap above 1 MiB avoids the low memory that real-mode code and some legacy DMA devices want, and placing it above every reserved range keeps it from landing on top of the kernel image, which in this example also sits at 1 MiB.
With the usual QEMU memory map, one usable region from 1 MiB to just under 128 MiB, a hand check shows what the function does. The top is 0x7FE0000, so total_frames is 0x7FE0 = 32,736 and the bitmap needs 4,092 bytes, one frame. The usable frames run from 256 to 32,735, which is 32,480. One frame goes to the bitmap and, if the kernel reserves 16 frames starting at 1 MiB, 16 more are used, leaving 32,463 free.
Allocation and free
A single-frame allocation scans from the hint, wrapping around once:
uint64_t pmm_alloc(void)
{
for (size_t n = 0; n < total_frames; n++) {
size_t f = (hint + n) % total_frames;
if (!bit_test(f)) {
bit_set(f);
free_count--;
hint = f + 1;
return (uint64_t)f * FRAME_SIZE;
}
}
return 0;
}
void pmm_free(uint64_t phys)
{
size_t f = phys / FRAME_SIZE;
if (f == 0 || f >= total_frames || !bit_test(f))
return; /* a double free or a bad address: ignore */
bit_clear(f);
free_count++;
if (f < hint)
hint = f;
}The scan starts at hint, which is the frame after the last allocation, so repeated allocations walk forward without rescanning the used prefix. Freeing pulls the hint back if the freed frame is earlier, so the freed frame is found again. The guard in pmm_free rejects frame 0, out-of-range frames and frames that are already free: a double free is a bug in the caller, and a production kernel would log it or panic, but the allocator must not corrupt its own count in response.
A contiguous run, needed for DMA buffers and for large page tables, looks for n clear bits in a row:
uint64_t pmm_alloc_run(size_t n)
{
size_t run = 0;
for (size_t f = 1; f < total_frames; f++) {
if (bit_test(f)) {
run = 0;
continue;
}
if (++run == n) {
size_t start = f + 1 - n;
for (size_t i = start; i <= f; i++)
bit_set(i);
free_count -= n;
return (uint64_t)start * FRAME_SIZE;
}
}
return 0;
}
void pmm_free_run(uint64_t phys, size_t n)
{
for (size_t i = 0; i < n; i++)
pmm_free(phys + i * FRAME_SIZE);
}
size_t pmm_free_frames(void) { return free_count; }
size_t pmm_total_frames(void) { return total_frames; }The run search is the bitmap's natural strength, and also where it shows its linear cost: asking for 512 contiguous frames on a fragmented bitmap can scan the whole array. External fragmentation is the issue that a buddy allocator addresses, by keeping free memory in aligned power-of-two blocks.
Testing it
The allocator should be tested before anything depends on it, with printed assertions. A short test:
pmm_init(regions, 1, reserved, 1);
kprintf("frames: total=%zu free=%zu\n", pmm_total_frames(), pmm_free_frames());
uint64_t a = pmm_alloc();
uint64_t b = pmm_alloc();
kprintf("a=0x%lx b=0x%lx\n", a, b);
pmm_free(a);
uint64_t c = pmm_alloc();
kprintf("c=0x%lx (should equal a)\n", c);
kprintf("free=%zu\n", pmm_free_frames());With the one-region setup from above and the hint starting at frame 256, the first free frame above the kernel and bitmap is what a receives. With the kernel's 16 frames at 1 MiB (frames 256 to 271) and the bitmap in frame 272, the first free frame is 273:
frames: total=32736 free=32463
a=0x111000 b=0x112000
c=0x111000 (should equal a)
free=32461a is frame 273, 0x111000, and b the next. Freeing a pulls the hint back to it, so c reuses the same frame, and two frames are in use at the end, giving 32,461. If c differs from a, the hint logic is wrong; if free does not drop by two, the count is not maintained. The numbers follow from the example memory map and will differ for yours.
What to reserve
The list of ranges to keep out of the allocator is where PMM bugs hide. It must include the kernel image, from the start of the first segment to the end of .bss, which you take from linker symbols; the bootloader's information structures, which may sit in usable memory until you copy what you need; any modules loaded with the kernel; the framebuffer if it was reported as usable; and, on Limine, the memory the bootloader marks as reclaimable, which must not be freed until you are done with the data in it. The first megabyte is also best left alone, because the BIOS data area, the video buffer and option ROMs live there and some devices can only DMA to low addresses. A frame handed out while it still holds the boot information is a bug that corrupts the very thing you are still reading.
Where this does not fit
This allocator is single-threaded: two CPUs calling pmm_alloc at once can return the same frame, and a spinlock around each function fixes it. A bitmap is poor for very large machines, where a terabyte needs 32 MiB of bitmap and a scan for a free frame may cross megabytes, and it handles non-contiguous NUMA memory only by treating the whole span as one array with holes marked used. It also treats all memory alike, while real kernels keep separate zones for the legacy DMA range below 16 MiB and for memory above 4 GiB that 32-bit devices cannot reach. When any of those matter, move to a buddy allocator with per-zone free lists.


