buddy_system_allocator

buddy_system_allocator is a crate implementing a basic buddy system allocator. It can be used both for LockedHeap implementing GlobalAlloc so you can use the standard alloc crate (as we saw before), or for allocating other address space. For example, we might want to allocate MMIO space for PCI BARs:

use buddy_system_allocator::FrameAllocator;
use core::alloc::Layout;

fn main() {
    let mut allocator = FrameAllocator::<32>::new();
    allocator.add_frame(0x200_0000, 0x400_0000);

    let layout = Layout::from_size_align(0x100, 0x100).unwrap();
    let bar = allocator
        .alloc_aligned(layout)
        .expect("Failed to allocate 0x100 byte MMIO region");
    println!("Allocated 0x100 byte MMIO region at {:#x}", bar);
}
  • PCI BARs always have alignment equal to their size.
  • Run the example with cargo run under src/bare-metal/useful-crates/allocator-example/. (It won't run in the Playground because of the crate dependency.)