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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
#![allow(dead_code)]
use core::marker::PhantomData;
use core::mem;
use core::ptr;
use multiboot::information::Multiboot;
use x86::controlregs;
use x86::irq::PageFaultError;
#[cfg(feature = "smp")]
use crate::arch::x86_64::kernel::apic;
use crate::arch::x86_64::kernel::get_mbinfo;
use crate::arch::x86_64::kernel::irq;
use crate::arch::x86_64::kernel::processor;
use crate::arch::x86_64::mm::physicalmem;
use crate::arch::x86_64::mm::{PhysAddr, VirtAddr, MEM};
use crate::environment;
use crate::mm;
use crate::scheduler;
const BOOT_GDT: PhysAddr = PhysAddr(0x1000);
const PML4_ADDRESS: VirtAddr = VirtAddr(0xFFFF_FFFF_FFFF_F000);
const PAGE_BITS: usize = 12;
const PAGE_MAP_BITS: usize = 9;
const PAGE_MAP_MASK: usize = 0x1FF;
bitflags! {
pub struct PageTableEntryFlags: u64 {
const PRESENT = 1 << 0;
const WRITABLE = 1 << 1;
const USER_ACCESSIBLE = 1 << 2;
const WRITE_THROUGH = 1 << 3;
const CACHE_DISABLE = 1 << 4;
const ACCESSED = 1 << 5;
const DIRTY = 1 << 6;
const HUGE_PAGE = 1 << 7;
const GLOBAL = 1 << 8;
const EXECUTE_DISABLE = 1 << 63;
}
}
impl PageTableEntryFlags {
const BLANK: PageTableEntryFlags = PageTableEntryFlags { bits: 0 };
pub fn device(&mut self) -> &mut Self {
self.insert(PageTableEntryFlags::CACHE_DISABLE);
self
}
pub fn normal(&mut self) -> &mut Self {
self.remove(PageTableEntryFlags::CACHE_DISABLE);
self
}
pub fn read_only(&mut self) -> &mut Self {
self.remove(PageTableEntryFlags::WRITABLE);
self
}
pub fn writable(&mut self) -> &mut Self {
self.insert(PageTableEntryFlags::WRITABLE);
self
}
pub fn execute_disable(&mut self) -> &mut Self {
self.insert(PageTableEntryFlags::EXECUTE_DISABLE);
self
}
}
#[derive(Clone, Copy)]
pub struct PageTableEntry {
physical_address_and_flags: PhysAddr,
}
impl PageTableEntry {
pub fn address(self) -> PhysAddr {
PhysAddr(
self.physical_address_and_flags.as_u64()
& !(BasePageSize::SIZE as u64 - 1u64)
& !(PageTableEntryFlags::EXECUTE_DISABLE).bits(),
)
}
fn is_present(self) -> bool {
(self.physical_address_and_flags & PageTableEntryFlags::PRESENT.bits()) != 0
}
fn is_huge(self) -> bool {
(self.physical_address_and_flags & PageTableEntryFlags::HUGE_PAGE.bits()) != 0
}
fn is_user(self) -> bool {
(self.physical_address_and_flags & PageTableEntryFlags::USER_ACCESSIBLE.bits()) != 0
}
fn set(&mut self, physical_address: PhysAddr, flags: PageTableEntryFlags) {
if flags.contains(PageTableEntryFlags::HUGE_PAGE) {
assert_eq!(
physical_address % LargePageSize::SIZE,
0,
"Physical address is not on a 2 MiB page boundary (physical_address = {:#X})",
physical_address
);
} else {
assert_eq!(
physical_address % BasePageSize::SIZE,
0,
"Physical address is not on a 4 KiB page boundary (physical_address = {:#X})",
physical_address
);
}
assert_eq!(
physical_address >> processor::get_physical_address_bits().into(),
0,
"Physical address exceeds CPU's physical address width (physical_address = {:#X})",
physical_address
);
let mut flags_to_set = flags;
flags_to_set.insert(PageTableEntryFlags::PRESENT);
flags_to_set.insert(PageTableEntryFlags::ACCESSED);
self.physical_address_and_flags = PhysAddr(physical_address | flags_to_set.bits());
}
}
pub trait PageSize: Copy {
const SIZE: usize;
const MAP_LEVEL: usize;
const MAP_EXTRA_FLAG: PageTableEntryFlags;
}
#[derive(Clone, Copy)]
pub enum BasePageSize {}
impl PageSize for BasePageSize {
const SIZE: usize = 4096;
const MAP_LEVEL: usize = 0;
const MAP_EXTRA_FLAG: PageTableEntryFlags = PageTableEntryFlags::BLANK;
}
#[derive(Clone, Copy)]
pub enum LargePageSize {}
impl PageSize for LargePageSize {
const SIZE: usize = 2 * 1024 * 1024;
const MAP_LEVEL: usize = 1;
const MAP_EXTRA_FLAG: PageTableEntryFlags = PageTableEntryFlags::HUGE_PAGE;
}
#[derive(Clone, Copy)]
pub enum HugePageSize {}
impl PageSize for HugePageSize {
const SIZE: usize = 1024 * 1024 * 1024;
const MAP_LEVEL: usize = 2;
const MAP_EXTRA_FLAG: PageTableEntryFlags = PageTableEntryFlags::HUGE_PAGE;
}
#[derive(Clone, Copy)]
struct Page<S: PageSize> {
virtual_address: VirtAddr,
size: PhantomData<S>,
}
impl<S: PageSize> Page<S> {
fn address(self) -> VirtAddr {
self.virtual_address
}
fn flush_from_tlb(self) {
unsafe {
llvm_asm!("invlpg ($0)" :: "r"(self.virtual_address) : "memory" : "volatile");
}
}
fn is_valid_address(virtual_address: VirtAddr) -> bool {
virtual_address < VirtAddr(0x0000_8000_0000_0000u64)
|| virtual_address >= VirtAddr(0x0000_8000_0000_0000u64)
}
fn including_address(virtual_address: VirtAddr) -> Self {
assert!(
Self::is_valid_address(virtual_address),
"Virtual address {:#X} is invalid",
virtual_address
);
if S::SIZE == 1024 * 1024 * 1024 {
assert!(processor::supports_1gib_pages());
}
Self {
virtual_address: align_down!(virtual_address, S::SIZE),
size: PhantomData,
}
}
fn range(first: Self, last: Self) -> PageIter<S> {
assert!(first.virtual_address <= last.virtual_address);
PageIter {
current: first,
last,
}
}
fn table_index<L: PageTableLevel>(self) -> usize {
assert!(L::LEVEL >= S::MAP_LEVEL);
self.virtual_address.as_usize() >> PAGE_BITS >> (L::LEVEL * PAGE_MAP_BITS) & PAGE_MAP_MASK
}
}
struct PageIter<S: PageSize> {
current: Page<S>,
last: Page<S>,
}
impl<S: PageSize> Iterator for PageIter<S> {
type Item = Page<S>;
fn next(&mut self) -> Option<Page<S>> {
if self.current.virtual_address <= self.last.virtual_address {
let p = self.current;
self.current.virtual_address += S::SIZE;
Some(p)
} else {
None
}
}
}
trait PageTableLevel {
const LEVEL: usize;
}
trait PageTableLevelWithSubtables: PageTableLevel {
type SubtableLevel;
}
enum PML4 {}
impl PageTableLevel for PML4 {
const LEVEL: usize = 3;
}
impl PageTableLevelWithSubtables for PML4 {
type SubtableLevel = PDPT;
}
enum PDPT {}
impl PageTableLevel for PDPT {
const LEVEL: usize = 2;
}
impl PageTableLevelWithSubtables for PDPT {
type SubtableLevel = PD;
}
enum PD {}
impl PageTableLevel for PD {
const LEVEL: usize = 1;
}
impl PageTableLevelWithSubtables for PD {
type SubtableLevel = PT;
}
enum PT {}
impl PageTableLevel for PT {
const LEVEL: usize = 0;
}
#[repr(C)]
struct PageTable<L> {
entries: [PageTableEntry; 1 << PAGE_MAP_BITS],
level: PhantomData<L>,
}
trait PageTableMethods {
fn get_page_table_entry<S: PageSize>(&self, page: Page<S>) -> Option<PageTableEntry>;
fn map_page_in_this_table<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) -> bool;
fn map_page<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) -> bool;
}
impl<L: PageTableLevel> PageTableMethods for PageTable<L> {
fn map_page_in_this_table<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) -> bool {
assert_eq!(L::LEVEL, S::MAP_LEVEL);
let index = page.table_index::<L>();
let flush = self.entries[index].is_present();
if flags == PageTableEntryFlags::BLANK {
self.entries[index].set(physical_address, flags);
} else {
self.entries[index].set(
physical_address,
PageTableEntryFlags::DIRTY | S::MAP_EXTRA_FLAG | flags,
);
}
if flush {
page.flush_from_tlb();
}
flush
}
default fn get_page_table_entry<S: PageSize>(&self, page: Page<S>) -> Option<PageTableEntry> {
assert_eq!(L::LEVEL, S::MAP_LEVEL);
let index = page.table_index::<L>();
if self.entries[index].is_present() {
Some(self.entries[index])
} else {
None
}
}
default fn map_page<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) -> bool {
self.map_page_in_this_table::<S>(page, physical_address, flags)
}
}
impl<L: PageTableLevelWithSubtables> PageTableMethods for PageTable<L>
where
L::SubtableLevel: PageTableLevel,
{
fn get_page_table_entry<S: PageSize>(&self, page: Page<S>) -> Option<PageTableEntry> {
assert!(L::LEVEL >= S::MAP_LEVEL);
let index = page.table_index::<L>();
if self.entries[index].is_present() {
if L::LEVEL > S::MAP_LEVEL {
let subtable = self.subtable::<S>(page);
subtable.get_page_table_entry::<S>(page)
} else {
Some(self.entries[index])
}
} else {
None
}
}
fn map_page<S: PageSize>(
&mut self,
page: Page<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) -> bool {
assert!(L::LEVEL >= S::MAP_LEVEL);
if L::LEVEL > S::MAP_LEVEL {
let index = page.table_index::<L>();
if !self.entries[index].is_present() {
let new_entry = physicalmem::allocate(BasePageSize::SIZE).unwrap();
self.entries[index].set(new_entry, PageTableEntryFlags::WRITABLE);
let subtable = self.subtable::<S>(page);
for entry in subtable.entries.iter_mut() {
entry.physical_address_and_flags = PhysAddr::zero();
}
}
let subtable = self.subtable::<S>(page);
subtable.map_page::<S>(page, physical_address, flags)
} else {
self.map_page_in_this_table::<S>(page, physical_address, flags)
}
}
}
impl<L: PageTableLevelWithSubtables> PageTable<L>
where
L::SubtableLevel: PageTableLevel,
{
fn subtable<S: PageSize>(&self, page: Page<S>) -> &mut PageTable<L::SubtableLevel> {
assert!(L::LEVEL > S::MAP_LEVEL);
let index = page.table_index::<L>();
let table_address = self as *const PageTable<L> as usize;
let subtable_address = (table_address << PAGE_MAP_BITS) | (index << PAGE_BITS);
unsafe { &mut *(subtable_address as *mut PageTable<L::SubtableLevel>) }
}
fn map_pages<S: PageSize>(
&mut self,
range: PageIter<S>,
physical_address: PhysAddr,
flags: PageTableEntryFlags,
) {
let mut current_physical_address = physical_address;
let mut send_ipi = false;
for page in range {
send_ipi |= self.map_page::<S>(page, current_physical_address, flags);
current_physical_address += S::SIZE as u64;
}
if send_ipi {
#[cfg(feature = "smp")]
apic::ipi_tlb_flush();
}
}
}
pub extern "x86-interrupt" fn page_fault_handler(
stack_frame: &mut irq::ExceptionStackFrame,
error_code: u64,
) {
let virtual_address = unsafe { controlregs::cr2() };
let pferror = PageFaultError::from_bits_truncate(error_code as u32);
error!("Page Fault (#PF) Exception: {:#?}", stack_frame);
error!(
"virtual_address = {:#X}, page fault error = {}",
virtual_address, pferror
);
error!(
"fs = {:#X}, gs = {:#X}",
processor::readfs(),
processor::readgs()
);
unsafe {
controlregs::cr2_write(0);
}
scheduler::abort();
}
#[inline]
fn get_page_range<S: PageSize>(virtual_address: VirtAddr, count: usize) -> PageIter<S> {
let first_page = Page::<S>::including_address(virtual_address);
let last_page =
Page::<S>::including_address(virtual_address + (count as u64 - 1) * S::SIZE as u64);
Page::range(first_page, last_page)
}
pub fn get_page_table_entry<S: PageSize>(virtual_address: VirtAddr) -> Option<PageTableEntry> {
trace!("Looking up Page Table Entry for {:#X}", virtual_address);
let page = Page::<S>::including_address(virtual_address);
let root_pagetable = unsafe {
&mut *mem::transmute::<*mut u64, *mut PageTable<PML4>>(PML4_ADDRESS.as_mut_ptr())
};
root_pagetable.get_page_table_entry(page)
}
pub fn get_physical_address<S: PageSize>(virtual_address: VirtAddr) -> PhysAddr {
trace!("Getting physical address for {:#X}", virtual_address);
let page = Page::<S>::including_address(virtual_address);
let root_pagetable = unsafe {
&mut *mem::transmute::<*mut u64, *mut PageTable<PML4>>(PML4_ADDRESS.as_mut_ptr())
};
let address = root_pagetable
.get_page_table_entry(page)
.expect("Entry not present")
.address();
let offset = virtual_address & (S::SIZE - 1);
PhysAddr(address.as_u64() | offset.as_u64())
}
pub fn virtual_to_physical(virtual_address: VirtAddr) -> PhysAddr {
let mut page_bits: u64 = 39;
static SELF: [VirtAddr; 4] = {
[
VirtAddr(0xFFFFFF8000000000u64),
VirtAddr(0xFFFFFFFFC0000000u64),
VirtAddr(0xFFFFFFFFFFE00000u64),
VirtAddr(0xFFFFFFFFFFFFF000u64),
]
};
for i in (0..3).rev() {
page_bits -= PAGE_MAP_BITS as u64;
let vpn = (virtual_address.as_u64() >> page_bits) as isize;
let ptr = SELF[i].as_ptr::<u64>();
let entry = unsafe { *ptr.offset(vpn) };
if entry & PageTableEntryFlags::HUGE_PAGE.bits() != 0 || i == 0 {
let off = virtual_address.as_u64()
& !(((!0u64) << page_bits) & !PageTableEntryFlags::EXECUTE_DISABLE.bits());
let phys =
entry & (((!0u64) << page_bits) & !PageTableEntryFlags::EXECUTE_DISABLE.bits());
return PhysAddr(off | phys);
}
}
panic!("virtual_to_physical should never reach this point");
}
#[no_mangle]
pub extern "C" fn virt_to_phys(virtual_address: VirtAddr) -> PhysAddr {
virtual_to_physical(virtual_address)
}
pub fn map<S: PageSize>(
virtual_address: VirtAddr,
physical_address: PhysAddr,
count: usize,
flags: PageTableEntryFlags,
) {
trace!(
"Mapping physical address {:#X} to virtual address {:#X} ({} pages)",
physical_address,
virtual_address,
count
);
let range = get_page_range::<S>(virtual_address, count);
let root_pagetable = unsafe {
&mut *mem::transmute::<*mut u64, *mut PageTable<PML4>>(PML4_ADDRESS.as_mut_ptr())
};
root_pagetable.map_pages(range, physical_address, flags);
}
pub fn unmap<S: PageSize>(virtual_address: VirtAddr, count: usize) {
trace!(
"Unmapping virtual address {:#X} ({} pages)",
virtual_address,
count
);
let range = get_page_range::<S>(virtual_address, count);
let root_pagetable = unsafe {
&mut *mem::transmute::<*mut u64, *mut PageTable<PML4>>(PML4_ADDRESS.as_mut_ptr())
};
root_pagetable.map_pages(range, PhysAddr::zero(), PageTableEntryFlags::BLANK);
}
pub fn identity_map(start_address: PhysAddr, end_address: PhysAddr) {
let first_page = Page::<BasePageSize>::including_address(VirtAddr(start_address.as_u64()));
let last_page = Page::<BasePageSize>::including_address(VirtAddr(end_address.as_u64()));
assert!(
last_page.address() < mm::kernel_start_address(),
"Address {:#X} to be identity-mapped is not below Kernel start address",
last_page.address()
);
let root_pagetable = unsafe {
&mut *mem::transmute::<*mut u64, *mut PageTable<PML4>>(PML4_ADDRESS.as_mut_ptr())
};
let range = Page::<BasePageSize>::range(first_page, last_page);
let mut flags = PageTableEntryFlags::empty();
flags.normal().read_only().execute_disable();
root_pagetable.map_pages(range, PhysAddr(first_page.address().as_u64()), flags);
}
#[inline]
pub fn get_application_page_size() -> usize {
LargePageSize::SIZE
}
pub fn init() {}
pub fn init_page_tables() {
debug!("Create new view to the kernel space");
unsafe {
let pml4 = controlregs::cr3();
let pde = pml4 + 2 * BasePageSize::SIZE as u64;
debug!("Found PML4 at 0x{:x}", pml4);
let start = pde
+ ((mm::kernel_end_address().as_usize() >> (PAGE_MAP_BITS + PAGE_BITS))
* mem::size_of::<u64>()) as u64;
let size = (512 - (mm::kernel_end_address().as_usize() >> (PAGE_MAP_BITS + PAGE_BITS)))
* mem::size_of::<u64>();
ptr::write_bytes(start as *mut u8, 0u8, size);
controlregs::cr3_write(pml4);
let mb_info = get_mbinfo();
if !mb_info.is_zero() {
info!("Found Multiboot info at 0x{:x}", mb_info);
identity_map(PhysAddr(mb_info.as_u64()), PhysAddr(mb_info.as_u64()));
let mb = Multiboot::from_ptr(mb_info.as_u64(), &mut MEM).unwrap();
let memory_map_address = mb
.memory_regions()
.expect("Could not find a memory map in the Multiboot information")
.next()
.expect("Could not first map address")
.base_address();
identity_map(PhysAddr(memory_map_address), PhysAddr(memory_map_address));
}
let cmdsize = environment::get_cmdsize();
if cmdsize > 0 {
let cmdline = environment::get_cmdline();
info!("Found cmdline at 0x{:x} (size {})", cmdline, cmdsize);
identity_map(
PhysAddr(cmdline.as_u64()),
PhysAddr(cmdline.as_u64()) + cmdsize - 1u64,
);
}
}
}