//! Where the kernel reaches memory on a PC: all of the physical address //! space at [`KERNEL_OFFSET`] (up to [`MAPPED_GIB`]), and the kernel's own //! image in the top 2 GiB at [`IMAGE_OFFSET`], as the compiler's kernel code //! model wants it. `boot` maps the first 4 GiB; [`map_above_4gib`] the rest, //! in 1 GiB pages; programs' halves come with the scheduler. /// What a region of the physical address space holds. #[derive(Clone, Copy)] pub enum Kind { /// Registers: uncached. Device, /// RAM: write-back cached. Normal, } /// A range of the physical address space, `start..end`. pub struct Region { pub start: u64, pub end: u64, pub kind: Kind, } /// The most of the physical address space the direct map can cover: 64 TiB, /// a core with 46 bits of physical address (a Meteor Lake's) whole, in the /// root table's entries 256 to 383. Firmware puts devices' 64-bit windows /// anywhere in it: a ThinkPad's at 256 GiB, OVMF's at 768 GiB. pub const MAPPED_GIB: usize = EXTRA_TABLES * 512 + 512; /// The GiB `boot` maps in 2 MiB pages, the fourth uncached. const BOOT_GIB: usize = 4; /// Directory-pointer tables for the direct map beyond its first 512 GiB /// (which boot's own table covers): one a 512 GiB. const EXTRA_TABLES: usize = 127; #[repr(C, align(4096))] struct Table([u64; 512]); /// The tables [`map_above_4gib`] fills: in `.bss`, as nothing can be /// allocated before RAM is mapped. Written once, on the first core before /// any other runs. static TABLES: crate::sync::Global<[Table; EXTRA_TABLES]> = crate::sync::Global::new([const { Table([0; 512]) }; EXTRA_TABLES]); /// Maps the physical address space from 4 GiB to as far as the core /// addresses (CPUID's physical address bits, at most [`MAPPED_GIB`]) into /// the direct map, in 1 GiB pages: write-back where `ram(start, end)` says /// the GiB has RAM, uncached elsewhere (devices' windows). The firmware's /// MTRRs still make uncached what they call so within a page that has RAM. /// Returns how many GiB the direct map covers: 4 on a core without 1 GiB /// pages, which leaves what lies above out. pub fn map_above_4gib(ram: impl Fn(u64, u64) -> bool) -> usize { let gib = map_gibs(ram); MAPPED.store(gib, core::sync::atomic::Ordering::Relaxed); gib } /// How many GiB of the physical address space the direct map covers. static MAPPED: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(BOOT_GIB); /// The end of what the direct map covers, physical. pub fn mapped_end() -> usize { MAPPED.load(core::sync::atomic::Ordering::Relaxed) << 30 } fn map_gibs(ram: impl Fn(u64, u64) -> bool) -> usize { const PRESENT_WRITABLE: u64 = 0x03; const LARGE: u64 = 0x80; const UNCACHED: u64 = 0x18; // PWT | PCD: PAT entry 3, UC const GIB: u64 = 1 << 30; // CPUID 0x8000_0001, EDX bit 26: 1 GiB pages. if crate::arch::cpuid(0x8000_0001)[3] & (1 << 26) == 0 { return BOOT_GIB; } // CPUID 0x8000_0008, EAX's low byte: physical address bits. let bits = (crate::arch::cpuid(0x8000_0008)[0] & 0xff).clamp(32, 52); let gib = (1usize << (bits - 30)).min(MAPPED_GIB); let root = virt((cr3() & !0xfff) as usize) as *mut u64; // SAFETY: only the first core runs, once; the tables are ours. let tables = unsafe { TABLES.get() }; for g in BOOT_GIB..gib { let start = g as u64 * GIB; let mut entry = start | PRESENT_WRITABLE | LARGE; if !ram(start, start + GIB) { entry |= UNCACHED; } let table = match g / 512 { // Boot's own table, which root entries 0 and 256 share: its // entries 4 to 511. 0 => { // SAFETY: boot's root table, mapped; entry 256 is present. let pdpt = unsafe { root.add(256).read() } & 0x000f_ffff_ffff_f000; virt(pdpt as usize) as *mut u64 } n => tables[n - 1].0.as_mut_ptr(), }; // SAFETY: an entry nothing maps yet (no TLB entry to flush). unsafe { table.add(g % 512).write_volatile(entry) }; } for n in 1..gib.div_ceil(512) { let table = physical(tables[n - 1].0.as_ptr() as usize) as u64; // SAFETY: root entries 257 on, empty until now: programs' roots copy // the kernel's half after this, as every core shares this root. unsafe { root.add(256 + n).write_volatile(table | PRESENT_WRITABLE) }; } gib } /// IA32_PAT as every core has it: the power-on layout but for entry 1, /// write-combining (WC) instead of write-through, as Linux has it. A page /// with PWT alone (and neither PCD nor PAT) is WC; WB, UC- and UC stay /// where page tables already name them (none, PCD, PWT | PCD). const PAT: u64 = 0x0007_0406_0007_0106; /// The page bits that pick [`PAT`]'s entry 1, write-combining. const WRITE_COMBINING: u64 = 0x08; /// Programs IA32_PAT (MSR 0x277) with [`PAT`] on this core: on each core, /// before it touches a write-combining page, as the cores must agree. /// Nothing maps a page WC before the first core has done it, so no cache /// or TLB holds a line of the old type. pub fn set_pat() { // CPUID 1, EDX bit 16: PAT (every x86-64 core so far). if crate::arch::cpuid(1)[3] & (1 << 16) != 0 { crate::arch::write_msr(0x277, PAT); set_cr3(cr3()); } } /// The most a write-combining window maps: a 4K panel's framebuffer and /// then some, in 4 KiB pages. const WINDOW_TABLES: usize = 16; /// A window's tables: a directory for its GiB and the page tables under it, /// in `.bss` (the window is made before the allocator runs). #[repr(C, align(4096))] struct Window { directory: Table, pages: [Table; WINDOW_TABLES], } static WINDOW: crate::sync::Global = crate::sync::Global::new(Window { directory: Table([0; 512]), pages: [const { Table([0; 512]) }; WINDOW_TABLES], }); /// Where the window starts: the GiB below the image's, in the image's /// directory-pointer table (root entry 511), which every program's root /// shares, so the window is everywhere at once. const WINDOW_AT: usize = IMAGE_OFFSET - (1 << 30); /// Maps `len` bytes of the physical address space from `start` (a device's /// memory: a framebuffer) write-combining, in 4 KiB pages, beside the /// direct map, and returns the kernel's address of `start`. Writes to it /// gather in the core's write-combining buffers and go out as bursts, /// where the direct map's uncached ones go a word at a time; a reader /// (the display controller) sees them after an `sfence`. Once, on the first /// core before any other runs; None when it is larger than the window /// (`WINDOW_TABLES` × 2 MiB) or a window is already made. pub fn map_write_combining(start: usize, len: usize) -> Option { const PRESENT_WRITABLE: u64 = 0x03; const NO_EXECUTE: u64 = 1 << 63; let first = start & !0xfff; let pages = (start + len).div_ceil(4096) - first / 4096; if len == 0 || pages > WINDOW_TABLES * 512 { return None; } let root = virt((cr3_kernel() & !0xfff) as usize) as *const u64; // SAFETY: the root's last entry, the image's, present since boot. let pdpt = unsafe { root.add(511).read() } & 0x000f_ffff_ffff_f000; let slot = (virt(pdpt as usize) as *mut u64).wrapping_add(WINDOW_AT >> 30 & 511); // SAFETY: an entry of boot's table, mapped; an empty one is free. if unsafe { slot.read_volatile() } != 0 { return None; } // SAFETY: only the first core runs, once (the slot was empty). let window = unsafe { WINDOW.get() }; for page in 0..pages { window.pages[page / 512].0[page % 512] = (first + page * 4096) as u64 | PRESENT_WRITABLE | WRITE_COMBINING | NO_EXECUTE; } for t in 0..pages.div_ceil(512) { window.directory.0[t] = physical(window.pages[t].0.as_ptr() as usize) as u64 | PRESENT_WRITABLE; } let directory = physical(window.directory.0.as_ptr() as usize) as u64; // SAFETY: the free entry found above; nothing has a TLB entry for it. unsafe { slot.write_volatile(directory | PRESENT_WRITABLE) }; Some(WINDOW_AT + (start - first)) } /// Makes writes to write-combining memory visible to the device that /// reads it: what sits in the core's write-combining buffers goes out. pub fn flush_write_combining() { // SAFETY: a store fence; it changes no data. unsafe { core::arch::asm!("sfence", options(nostack, preserves_flags)) }; } /// The direct map: physical address 0 is here (PML4 entry 256). pub const KERNEL_OFFSET: usize = 0xffff_8000_0000_0000; /// The image: physical 0 is here too, for its first GiB (PML4 entry 511). pub const IMAGE_OFFSET: usize = 0xffff_ffff_8000_0000; /// The kernel's address for a physical address. pub const fn virt(physical: usize) -> usize { physical + KERNEL_OFFSET } /// The physical address behind a kernel address, in the direct map or in /// the image. pub const fn physical(virt: usize) -> usize { if virt >= IMAGE_OFFSET { virt - IMAGE_OFFSET } else { virt - KERNEL_OFFSET } } use core::sync::atomic::{AtomicU64, Ordering}; /// The kernel's own tables (boot's), for a core with no program's: no /// lower half once [`close_identity`] has run. static KERNEL_CR3: AtomicU64 = AtomicU64::new(0); fn cr3() -> u64 { let value: u64; // SAFETY: reading CR3 has no side effects. unsafe { core::arch::asm!("mov {}, cr3", out(reg) value, options(nomem, nostack)) }; value } fn set_cr3(value: u64) { // SAFETY: tables that map the kernel's half as boot's do. unsafe { core::arch::asm!("mov cr3, {}", in(reg) value, options(nostack)) }; } /// Drops boot's identity map of the first 4 GiB, once every core has /// climbed into the top half: from then on a stray low address faults, /// and the lower half is a program's alone. pub fn close_identity() { let root = cr3() & !0xfff; KERNEL_CR3.store(root, Ordering::Relaxed); // SAFETY: the root table's first entry, which nothing uses any more. unsafe { (virt(root as usize) as *mut u64).write_volatile(0) }; set_cr3(root); } /// The kernel's half's tables (entries 256 to 511 of the root), which a /// program's root copies. pub fn kernel_root() -> usize { virt((cr3_kernel() & !0xfff) as usize) } fn cr3_kernel() -> u64 { match KERNEL_CR3.load(Ordering::Relaxed) { 0 => cr3(), root => root, } } /// Points the lower half at a program's tables: CR3 is its root, whose top /// half is the kernel's. pub fn switch_lower_half(root: u64) { set_cr3(root); } /// A program's root table holds the kernel's half too, so a core must not be /// left on it once the program may be freed: a kernel task closes it. pub const PROGRAM_TABLES_HOLD_THE_KERNEL: bool = true; /// Back to the kernel's own tables: no program's half. pub fn close_lower_half() { set_cr3(cr3_kernel()); } /// Nothing to do on a PC: [`switch_lower_half`] brings the half with it. pub fn open_lower_half() {}