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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! Paging implementation on i386
//!
//! No PAE, no PSE, just regular 2-level paging, with simple 4kB tables and pages.

pub mod entry;
pub mod table;
pub mod lands;

use crate::mem::{VirtualAddress, PhysicalAddress};

/// The page size. Dictated by the MMU.
/// In simple, elegant, sane i386 paging, a page is 4kB.
pub const PAGE_SIZE: usize = 4096;

/// The number of entries a page table has.
/// On i386 a page table/directory is 1024 entries * 4 bytes per entry = 4kB, fits in 1 page.
pub const ENTRY_COUNT: usize = PAGE_SIZE / ::core::mem::size_of::<entry::I386Entry>();

//pub static mut ACTIVE_PAGE_TABLES: ActiveHierarchy = ActiveHierarchy;

/// Check if the paging is currently active.
///
/// This is done by checking if we're in protected mode and if paging is
/// enabled.
pub fn is_paging_on() -> bool {
    let cr0: usize;
    unsafe {
        // Safety: this is just getting the CR0 register
        llvm_asm!("mov $0, cr0" : "=r"(cr0) ::: "intel" );
    }
    cr0 & 0x80000001 == 0x80000001 // PE | PG
}

/// Not used anymore, bootstrap's job
pub unsafe fn enable_paging(page_directory_address: PhysicalAddress) {
    llvm_asm!("mov eax, $0
          mov cr3, eax

          mov eax, cr0
          or eax, 0x80010001
          mov cr0, eax          "

            :
            : "r" (page_directory_address.addr())
            : "eax", "memory"
            : "intel", "volatile");
}

/// Flush the Translation Lookaside Buffer [https://wiki.osdev.org/TLB]
fn flush_tlb() {
    #[cfg(not(test))]
    unsafe {
        llvm_asm!("mov eax, cr3
          mov cr3, eax  "
          :
          :
          : "eax"
          : "intel", "volatile");
    }
}

/// Changes the content of the cr3 register, and returns the value before the change was made
fn swap_cr3(page_directory_address: PhysicalAddress) -> PhysicalAddress {
    let old_value: PhysicalAddress;
    unsafe {
        llvm_asm!("mov $0, cr3
              mov cr3, $1"
              : "=&r"(old_value)
              : "r"(page_directory_address)
              : "memory"
              : "intel", "volatile");
    }
    old_value
}

/// Reads the value of cr3, retrieving the current page directory's physical address
pub fn read_cr3() -> PhysicalAddress {
    let cr3_value: usize;
    unsafe {
        llvm_asm!( "mov $0, cr3" : "=r"(cr3_value) : : : "intel", "volatile");
    }
    PhysicalAddress(cr3_value)
}

/// Reads the value of cr2, retrieving the address that caused a page fault
pub fn read_cr2() -> VirtualAddress {
    let cr2_value : usize;
    unsafe {
        llvm_asm!( "mov $0, cr2" : "=r"(cr2_value) : : : "intel", "volatile");
    }
    VirtualAddress(cr2_value)
}