This repository has been archived by the owner on Feb 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.rs
65 lines (54 loc) · 1.66 KB
/
heap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! This file contains the memory allocator used by the kernel. It is a thin wrapper around
//! smallheap.
use core::alloc::{GlobalAlloc, Layout, Opaque};
use core::cell::RefCell;
use smallheap::{self, Allocator};
use interrupts::no_interrupts;
/// A wrapper around the heap allocator for use as the `global_allocator`.
pub struct KernelAllocator {
heap: RefCell<Option<Allocator>>,
}
impl KernelAllocator {
pub const fn new() -> Self {
KernelAllocator {
heap: RefCell::new(None),
}
}
pub fn set_heap(&mut self, heap: Allocator) {
*self.heap.borrow_mut() = Some(heap);
}
}
unsafe impl GlobalAlloc for KernelAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut Opaque {
no_interrupts(|| {
self.heap
.borrow_mut()
.as_mut()
.unwrap()
.malloc(layout.size(), layout.align())
.map(|p| p.as_ptr() as *mut Opaque)
.unwrap_or(0 as *mut Opaque)
})
}
unsafe fn dealloc(&self, ptr: *mut Opaque, layout: Layout) {
no_interrupts(|| {
self.heap
.borrow_mut()
.as_mut()
.unwrap()
.free(ptr as *mut u8, layout.size())
})
}
}
/// Initialize the kernel heap
pub fn init(allocator: &mut KernelAllocator, start: usize, size: usize) {
let heap = unsafe { Allocator::new(start as *mut u8, size) };
let free_size = heap.size();
allocator.set_heap(heap);
bootlog!(
"heap inited - start addr: 0x{:x}, end addr: 0x{:x}, {} bytes\n",
start,
start + size,
free_size
);
}