2019-11-11 09:37:06 +08:00
|
|
|
use core::alloc::GlobalAlloc;
|
|
|
|
use core::ptr::NonNull;
|
|
|
|
use alloc::alloc::Layout;
|
|
|
|
use linked_list_allocator::Heap;
|
2019-12-18 06:35:58 +08:00
|
|
|
use libcortex_a9::mutex::Mutex;
|
|
|
|
use libboard_zynq::ddr::DdrRam;
|
2019-11-11 09:37:06 +08:00
|
|
|
|
|
|
|
#[global_allocator]
|
2019-11-21 00:25:30 +08:00
|
|
|
static ALLOCATOR: CortexA9Alloc = CortexA9Alloc(Mutex::new(Heap::empty()));
|
2019-11-11 09:37:06 +08:00
|
|
|
|
2020-06-18 06:51:13 +08:00
|
|
|
/// LockedHeap doesn't lock properly
|
2019-11-21 00:25:30 +08:00
|
|
|
struct CortexA9Alloc(Mutex<Heap>);
|
2019-11-11 09:37:06 +08:00
|
|
|
|
2019-11-21 00:25:30 +08:00
|
|
|
unsafe impl Sync for CortexA9Alloc {}
|
2019-11-11 09:37:06 +08:00
|
|
|
|
2019-11-21 00:25:30 +08:00
|
|
|
unsafe impl GlobalAlloc for CortexA9Alloc {
|
2019-11-11 09:37:06 +08:00
|
|
|
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
2019-11-21 00:25:30 +08:00
|
|
|
self.0.lock()
|
2019-11-11 09:37:06 +08:00
|
|
|
.allocate_first_fit(layout)
|
|
|
|
.ok()
|
|
|
|
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
2019-11-21 00:25:30 +08:00
|
|
|
self.0.lock()
|
2019-11-11 09:37:06 +08:00
|
|
|
.deallocate(NonNull::new_unchecked(ptr), layout)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-27 10:06:55 +08:00
|
|
|
pub fn init_alloc_ddr(ddr: &mut DdrRam) {
|
2019-11-11 09:37:06 +08:00
|
|
|
unsafe {
|
2019-11-21 00:25:30 +08:00
|
|
|
ALLOCATOR.0.lock()
|
2019-11-11 09:37:06 +08:00
|
|
|
.init(ddr.ptr::<u8>() as usize, ddr.size());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-27 10:06:55 +08:00
|
|
|
extern "C" {
|
|
|
|
static __heap_start: usize;
|
|
|
|
static __heap_end: usize;
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn init_alloc_linker() {
|
|
|
|
unsafe {
|
|
|
|
let start = &__heap_start as *const usize as usize;
|
|
|
|
let end = &__heap_end as *const usize as usize;
|
|
|
|
ALLOCATOR.0.lock()
|
|
|
|
.init(start, end - start);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-11 09:37:06 +08:00
|
|
|
|
|
|
|
#[alloc_error_handler]
|
|
|
|
fn alloc_error(_: core::alloc::Layout) -> ! {
|
|
|
|
panic!("alloc_error")
|
|
|
|
}
|