|
| 1 | +use bitmap_allocator::BitAlloc; |
| 2 | +use spin::Mutex; |
| 3 | + |
| 4 | +use super::address::{align_down, align_up, virt_to_phys, PhysAddr}; |
| 5 | +use super::PAGE_SIZE; |
| 6 | +use crate::config::PHYS_MEMORY_END; |
| 7 | + |
| 8 | +// Support max 1M * 4096 = 1GB memory. |
| 9 | +type FrameAlloc = bitmap_allocator::BitAlloc1M; |
| 10 | + |
| 11 | +static FRAME_ALLOCATOR: Mutex<FrameAllocator> = Mutex::new(FrameAllocator::empty()); |
| 12 | + |
| 13 | +struct FrameAllocator { |
| 14 | + base: PhysAddr, |
| 15 | + inner: FrameAlloc, |
| 16 | +} |
| 17 | + |
| 18 | +impl FrameAllocator { |
| 19 | + const fn empty() -> Self { |
| 20 | + Self { |
| 21 | + base: 0, |
| 22 | + inner: FrameAlloc::DEFAULT, |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + fn init(&mut self, base: PhysAddr, size: usize) { |
| 27 | + self.base = align_up(base); |
| 28 | + let page_count = align_up(size) / PAGE_SIZE; |
| 29 | + self.inner.insert(0..page_count); |
| 30 | + } |
| 31 | + |
| 32 | + unsafe fn alloc(&mut self) -> Option<PhysAddr> { |
| 33 | + let ret = self.inner.alloc().map(|idx| idx * PAGE_SIZE + self.base); |
| 34 | + trace!("Allocate frame: {:x?}", ret); |
| 35 | + ret |
| 36 | + } |
| 37 | + |
| 38 | + unsafe fn dealloc(&mut self, target: PhysAddr) { |
| 39 | + trace!("Deallocate frame: {:x}", target); |
| 40 | + self.inner.dealloc((target - self.base) / PAGE_SIZE) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +pub unsafe fn alloc_page() -> Option<PhysAddr> { |
| 45 | + FRAME_ALLOCATOR.lock().alloc() |
| 46 | +} |
| 47 | + |
| 48 | +pub unsafe fn dealloc_page(paddr: PhysAddr) { |
| 49 | + FRAME_ALLOCATOR.lock().dealloc(paddr) |
| 50 | +} |
| 51 | + |
| 52 | +pub(super) fn init() { |
| 53 | + extern "C" { |
| 54 | + fn ekernel(); |
| 55 | + } |
| 56 | + |
| 57 | + let mem_pool_start = align_up(virt_to_phys(ekernel as usize)); |
| 58 | + let mem_pool_end = align_down(PHYS_MEMORY_END); |
| 59 | + let mem_pool_size = mem_pool_end - mem_pool_start; |
| 60 | + println!( |
| 61 | + "Initializing frame allocator at: [{:#x?}, {:#x?})", |
| 62 | + mem_pool_start, mem_pool_end |
| 63 | + ); |
| 64 | + FRAME_ALLOCATOR.lock().init(mem_pool_start, mem_pool_size); |
| 65 | +} |
0 commit comments