buddy_system_allocator

buddy_system_allocator is a third-party 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:

  1. use buddy_system_allocator::FrameAllocator;
  2. use core::alloc::Layout;
  3. fn main() {
  4.     let mut allocator = FrameAllocator::<32>::new();
  5.     allocator.add_frame(0x200_0000, 0x400_0000);
  6.     let layout = Layout::from_size_align(0x100, 0x100).unwrap();
  7.     let bar = allocator
  8.         .alloc_aligned(layout)
  9.         .expect("Failed to allocate 0x100 byte MMIO region");
  10.     println!("Allocated 0x100 byte MMIO region at {:#x}", bar);
  11. }
  • 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.)