Cleanup, use spinlock for allocator

This commit is contained in:
Jeremy Soller 2016-08-15 15:01:24 -06:00
parent cc8fe85e6a
commit 2a66a84a50
9 changed files with 146 additions and 30 deletions

View file

@ -1,3 +1,6 @@
[package]
name = "bump_allocator"
version = "0.1.0"
[dependencies]
"spin" = "*"

View file

@ -1,24 +1,23 @@
//! A simple allocator that never frees, for testing
//! Some code borrowed from [Phil Opp's Blog](http://os.phil-opp.com/kernel-heap.html)
#![feature(allocator)]
#![feature(const_fn)]
#![allocator]
#![no_std]
pub static mut HEAP: usize = 10*1024*1024;
use spin::Mutex;
extern crate spin;
pub const HEAP_START: usize = 0o_000_001_000_000_0000;
pub const HEAP_SIZE: usize = 100 * 1024; // 100 KiB
static BUMP_ALLOCATOR: Mutex<BumpAllocator> = Mutex::new(BumpAllocator::new(HEAP_START, HEAP_SIZE));
#[no_mangle]
pub extern fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
unsafe {
let mut ret = HEAP;
if align.is_power_of_two() {
ret += (align - 1);
ret &= !(align - 1);
} else {
assert_eq!(align, 0);
}
HEAP = ret + size;
ret as *mut u8
}
BUMP_ALLOCATOR.lock().allocate(size, align).expect("out of memory")
}
#[no_mangle]
@ -45,3 +44,53 @@ pub extern fn __rust_reallocate(ptr: *mut u8, size: usize, new_size: usize, alig
pub extern fn __rust_reallocate_inplace(ptr: *mut u8, size: usize, new_size: usize, align: usize) -> usize {
size
}
/// Align downwards. Returns the greatest x with alignment `align`
/// so that x <= addr. The alignment must be a power of 2.
pub fn align_down(addr: usize, align: usize) -> usize {
if align.is_power_of_two() {
addr & !(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
#[derive(Debug)]
struct BumpAllocator {
heap_start: usize,
heap_size: usize,
next: usize,
}
impl BumpAllocator {
/// Create a new allocator, which uses the memory in the
/// range [heap_start, heap_start + heap_size).
const fn new(heap_start: usize, heap_size: usize) -> BumpAllocator {
BumpAllocator {
heap_start: heap_start,
heap_size: heap_size,
next: heap_start,
}
}
/// Allocates a block of memory with the given size and alignment.
fn allocate(&mut self, size: usize, align: usize) -> Option<*mut u8> {
let alloc_start = align_up(self.next, align);
let alloc_end = alloc_start + size;
if alloc_end <= self.heap_start + self.heap_size {
self.next = alloc_end;
Some(alloc_start as *mut u8)
} else {
None
}
}
}