//! GDT (Global Descriptor Table) + TSS (Task State Segment). //! //! In 64-bit mode segmentation is mostly dead, but we still need a GDT for one //! important reason: it is how the CPU finds the TSS, and the TSS holds the //! Interrupt Stack Table (IST) -- a list of known-good stacks the CPU can //! switch to when an exception happens. //! //! Why it matters: if the kernel stack overflows, the CPU hits the guard page //! and raises a page fault. Pushing the exception frame onto the (already //! overflowed) stack faults again -> double fault -> same problem -> TRIPLE //! fault, which resets the machine. Giving the double-fault handler its own //! IST stack breaks that chain. use lazy_static::lazy_static; use x86_64::VirtAddr; use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector}; use x86_64::structures::tss::TaskStateSegment; /// Which IST slot (0..=6) the double-fault handler uses. pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; lazy_static! { static ref TSS: TaskStateSegment = { let mut tss = TaskStateSegment::new(); tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = { // No memory allocator yet, so the stack is just a static array. // (It has no guard page, so don't do anything recursive in the // double-fault handler!) const STACK_SIZE: usize = 4096 * 5; static mut STACK: [u8; STACK_SIZE] = [0; STACK_SIZE]; // Stacks grow downwards on x86, so hand the CPU the *end* address. let stack_start = VirtAddr::from_ptr(&raw const STACK); stack_start + STACK_SIZE as u64 }; tss }; } lazy_static! { /// The GDT, plus the selectors (indexes) of the entries we added. static ref GDT: (GlobalDescriptorTable, Selectors) = { let mut gdt = GlobalDescriptorTable::new(); let code_selector = gdt.append(Descriptor::kernel_code_segment()); let tss_selector = gdt.append(Descriptor::tss_segment(&TSS)); (gdt, Selectors { code_selector, tss_selector }) }; } struct Selectors { code_selector: SegmentSelector, tss_selector: SegmentSelector, } /// Load our GDT, point CS at our code segment and load the TSS. pub fn init() { use x86_64::instructions::segmentation::{CS, Segment}; use x86_64::instructions::tables::load_tss; GDT.0.load(); unsafe { // The old CS value points into the bootloader's GDT, which we just // replaced, so reload it. Then tell the CPU where our TSS is. CS::set_reg(GDT.1.code_selector); load_tss(GDT.1.tss_selector); } }