// black metal kernel — episode 07 of 08
// kernel programming in rust — zero-cost abstractions — no gc — no mercy
// 07 — mapping virtual execution to physical reality
x86-64 enforces a rigid four-level paging hierarchy. every single memory access that the cpu makes is dynamically translated by the hardware memory management unit (mmu). without explicit control of this mapping, the kernel is blind, running at the mercy of whatever bootloader populated the `CR3` register initially. to own the address space, you must rewrite reality from the ground up, manipulating page map level 4 (pml4) descriptors directly.
allocating 2mb huge pages over the standard 4kb pages significantly reduces translation lookaside buffer (tlb) pressure. it avoids thrashing caches. establishing a direct map of all physical memory into a high-half virtual window ensures the kernel can universally dereference physical memory directly.
pub const BLACK_PAGE_PRESENT: u64 = 1 << 0; pub const BLACK_PAGE_WRITABLE: u64 = 1 << 1; pub const BLACK_PAGE_HUGE: u64 = 1 << 7; #[repr(C, align(4096))] pub struct BlackPageTable { black_entries: [u64; 512], } impl BlackPageTable { pub const fn black_zeroed() -> Self { Self { black_entries: [0; 512], } } pub fn black_map_huge(&mut self, black_index: usize, black_phys: u64, black_flags: u64) { self.black_entries[black_index] = black_phys | black_flags | BLACK_PAGE_HUGE | BLACK_PAGE_PRESENT; } pub unsafe fn black_load(&self) { let black_addr = self as *const _ as u64; core::arch::asm!( "mov cr3, {}", in(reg) black_addr, options(nostack, preserves_flags) ); } }
// 07 / 08 — black_ptr owns its truth — BLACK0X80