use core::ptr::Unique; use memory::{Frame, FrameAllocator}; use super::{Page, PAGE_SIZE, PhysicalAddress, VirtualAddress}; use super::entry::{self, EntryFlags}; use super::table::{self, Table, Level4}; pub struct Mapper { p4: Unique>, } impl Mapper { /// Create a new page table pub unsafe fn new() -> Mapper { Mapper { p4: Unique::new(table::P4), } } pub fn p4(&self) -> &Table { unsafe { self.p4.get() } } pub fn p4_mut(&mut self) -> &mut Table { unsafe { self.p4.get_mut() } } /// Map a page to a frame pub fn map_to(&mut self, page: Page, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let mut p3 = self.p4_mut().next_table_create(page.p4_index(), allocator); let mut p2 = p3.next_table_create(page.p3_index(), allocator); let mut p1 = p2.next_table_create(page.p2_index(), allocator); assert!(p1[page.p1_index()].is_unused()); p1[page.p1_index()].set(frame, flags | entry::PRESENT); } /// Map a page to the next free frame pub fn map(&mut self, page: Page, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let frame = allocator.allocate_frame().expect("out of memory"); self.map_to(page, frame, flags, allocator) } /// Identity map a frame pub fn identity_map(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } /// Unmap a page pub fn unmap(&mut self, page: Page, allocator: &mut A) where A: FrameAllocator { assert!(self.translate(page.start_address()).is_some()); let p1 = self.p4_mut() .next_table_mut(page.p4_index()) .and_then(|p3| p3.next_table_mut(page.p3_index())) .and_then(|p2| p2.next_table_mut(page.p2_index())) .expect("mapping code does not support huge pages"); let frame = p1[page.p1_index()].pointed_frame().unwrap(); p1[page.p1_index()].set_unused(); // TODO free p(1,2,3) table if empty allocator.deallocate_frame(frame); } pub fn translate_page(&self, page: Page) -> Option { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index())) .and_then(|p1| p1[page.p1_index()].pointed_frame()) } /// Translate a virtual address to a physical one pub fn translate(&self, virtual_address: VirtualAddress) -> Option { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } }