|
| 1 | +use x86_64::instructions::tables::{lgdt, load_tss}; |
| 2 | +use x86_64::registers::segmentation::{Segment, SegmentSelector, CS}; |
| 3 | +use x86_64::structures::gdt::{Descriptor, DescriptorFlags}; |
| 4 | +use x86_64::structures::{tss::TaskStateSegment, DescriptorTablePointer}; |
| 5 | +use x86_64::{addr::VirtAddr, PrivilegeLevel}; |
| 6 | + |
| 7 | +lazy_static::lazy_static! { |
| 8 | + static ref TSS: TaskStateSegment = TaskStateSegment::new(); |
| 9 | + static ref GDT: GdtStruct = GdtStruct::new(&TSS); |
| 10 | +} |
| 11 | + |
| 12 | +struct GdtStruct { |
| 13 | + table: [u64; 16], |
| 14 | +} |
| 15 | + |
| 16 | +impl GdtStruct { |
| 17 | + pub const KCODE_SELECTOR: SegmentSelector = SegmentSelector::new(1, PrivilegeLevel::Ring0); |
| 18 | + pub const _KDATA_SELECTOR: SegmentSelector = SegmentSelector::new(2, PrivilegeLevel::Ring0); |
| 19 | + pub const TSS_SELECTOR: SegmentSelector = SegmentSelector::new(3, PrivilegeLevel::Ring0); |
| 20 | + |
| 21 | + pub fn new(tss: &'static TaskStateSegment) -> Self { |
| 22 | + let mut table = [0; 16]; |
| 23 | + table[1] = DescriptorFlags::KERNEL_CODE64.bits(); // 0x00af9b000000ffff |
| 24 | + table[2] = DescriptorFlags::KERNEL_DATA.bits(); // 0x00cf93000000ffff |
| 25 | + if let Descriptor::SystemSegment(low, high) = Descriptor::tss_segment(tss) { |
| 26 | + table[3] = low; |
| 27 | + table[4] = high; |
| 28 | + } |
| 29 | + Self { table } |
| 30 | + } |
| 31 | + |
| 32 | + fn pointer(&self) -> DescriptorTablePointer { |
| 33 | + DescriptorTablePointer { |
| 34 | + base: VirtAddr::new(self.table.as_ptr() as u64), |
| 35 | + limit: (core::mem::size_of_val(&self.table) - 1) as u16, |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + pub fn load(&'static self) { |
| 40 | + unsafe { |
| 41 | + lgdt(&self.pointer()); |
| 42 | + CS::set_reg(GdtStruct::KCODE_SELECTOR); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + pub fn load_tss(&'static self, selector: SegmentSelector) { |
| 47 | + unsafe { load_tss(selector) }; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +pub fn init() { |
| 52 | + println!("Initializing GDT..."); |
| 53 | + lazy_static::initialize(&GDT); |
| 54 | + GDT.load(); |
| 55 | + GDT.load_tss(GdtStruct::TSS_SELECTOR); |
| 56 | +} |
0 commit comments