Lecture 5: Buddy allocation, testing

Allocation in Chickadee

WeensyOS allocator

void* kalloc(size_t sz) {
    if (sz > PAGESIZE) {
        return nullptr;
    }

    int pageno = 0;

    for (int tries = 0; tries != NPAGES; ++tries) {
        uintptr_t pa = pageno * PAGESIZE;
        if (allocatable_physical_address(pa)
            && physpages[pageno].refcount == 0) {
            ++physpages[pageno].refcount;
            memset((void*) pa, 0xCC, PAGESIZE);
            return (void*) pa;
        }
        pageno = (pageno + 1) % NPAGES;
    }

    return nullptr;
}

Chickadee allocator

void* kalloc(size_t sz) {
    if (sz == 0 || sz > PAGESIZE) {
        return nullptr;
    }

    auto irqs = page_lock.lock();
    void* ptr = nullptr;

    // skip over reserved and kernel memory
    auto range = physical_ranges.find(next_free_pa);
    while (range != physical_ranges.end()) {
        if (range->type() == mem_available) {
            // use this page
            ptr = pa2kptr<void*>(next_free_pa);
            next_free_pa += PAGESIZE;
            break;
        } else {
            // move to next range
            next_free_pa = range->last();
            ++range;
        }
    }

    page_lock.unlock(irqs);

    if (ptr) {
        // tell sanitizers the allocated page is accessible
        asan_mark_memory(ka2pa(ptr), PAGESIZE, false);
        // initialize to `int3`
        memset(ptr, 0xCC, PAGESIZE);
    }
    return ptr;
}

Disadvantages of this allocator

Buddy allocation

Blocks and buddies

Example: Split to allocate 4095 bytes

Freeing

Example: Free some order-12 allocations

Buddy allocation data structures (class discussion)

Questions asked by the buddy allocation algorithm

Testing and invariants

Validation 1: Testing

Unit tests

Integration tests

Testing goals

How should we measure a test suite?

Coverage

Validation 2: Proving

Invariants

Classes of invariant

Assertions

Assertion patterns

Test suite construction

Property testing

Some buddy allocation properties

Invariant-based testing

Some buddy allocation invariants

Debugging