buddy_system_allocator

buddy_system_allocator is a crate implementing a basic buddy system allocator. It can be used both to implement GlobalAlloc (using LockedHeap) so you can use the standard alloc crate (as we saw before), or for allocating other address space (using FrameAllocator) . 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 BAR 的对齐方式始终与其大小相等。
  • 使用 src/bare-metal/useful-crates/allocator-example/ 目录下的 cargo run 运行该示例。(由于存在 crate 依赖项,无法在 Playground 中运行该示例。)