</>EmbeddedInterview

Implement a bitmap-based physical page allocator.

MediumCoding: Systems, Bitmaps & Virtualization

Short answer: Each bitmap bit represents one physical page. Find a clear bit, set it and return the corresponding physical address. Freeing clears the bit.

#include <stdint.h>
#include <stdbool.h>
#define BASE UINT64_C(0x80000000)
#define PAGE UINT64_C(4096)
static uint64_t used;

bool alloc_page(uint64_t *pa)
{
    for (unsigned i = 0; i < 64; i++) {
        uint64_t bit = UINT64_C(1) << i;
        if (!(used & bit)) {
            used |= bit;
            *pa = BASE + i * PAGE;
            return true;
        }
    }
    return false;
}

bool free_page(uint64_t pa)
{
    if (pa < BASE || pa - BASE >= 64 * PAGE ||
        (pa - BASE) % PAGE) return false;
    uint64_t bit = UINT64_C(1) << ((pa - BASE) / PAGE);
    if (!(used & bit)) return false;
    used &= ~bit;
    return true;
}

This manages 64 pages (256 KiB) with only 8 bytes of allocation metadata. Reserve firmware/MMIO pages before use and protect the bitmap if multiple CPUs allocate concurrently. Real kernels also track ownership and reference counts.