Skip to main content

strat9_kernel/memory/
paging.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Virtual Memory Management (Paging) for Strat9-OS
24//!
25//! Uses the `x86_64` crate's `OffsetPageTable` which is designed for the HHDM
26//! (Higher Half Direct Map) pattern : exactly what the UEFI bootloader provides.
27//!
28//! Provides map/unmap/translate operations on the active page table.
29
30use crate::{
31    arch::xshim::{PageTableFlags, PhysAddr, PhysFrame as X86PhysFrame, Size4KiB, VirtAddr},
32    x86_crate_shim::{
33        registers::control::Cr3,
34        structures::paging::{
35            FrameAllocator as X86FrameAllocator, Mapper, OffsetPageTable, Page, PageTable,
36            Translate,
37        },
38    },
39};
40
41use crate::{
42    memory::frame::{FrameAllocOptions, FramePurpose},
43    sync::SpinLock,
44};
45
46/// Wrapper around the buddy allocator implementing the x86_64 crate's `FrameAllocator` trait.
47///
48/// Used by `OffsetPageTable` when it needs a new intermediate page-table node
49/// (PML4 / PDPT / PD / PT).
50///
51/// # Safety invariant: page-table frames MUST be zeroed
52///
53/// The x86_64 CPU page-table walker reads all 512 entries of every
54/// intermediate node it traverses, regardless of which entries are "in use".
55/// If a newly allocated page-table frame contains stale bytes (left behind by
56/// the slab allocator or a previous allocation), any non-zero entry is decoded
57/// as a valid PTE pointing to an arbitrary physical address.  The first fetch
58/// from such an address becomes the new RIP after the Ring 3 transition :
59/// explaining why RIP is non-deterministic across boots.
60///
61/// `BuddyFrameAllocator` enforces zeroing via `FrameAllocOptions::new()
62///  .purpose(FramePurpose::PageTable)` which:
63///
64///  1. Calls the buddy allocator for a raw order-0 frame.
65///  2. CAS-claims the frame via the [`MetaSlot`](crate::memory::MetaSlot) refcount field
66///     (`REFCOUNT_UNUSED` => `1`).
67///  3. Zeros the 4 KiB with a single `ptr::write_bytes` through the HHDM.
68///  4. Sets purpose flags on the [`MetaSlot`](crate::memory::MetaSlot) with `Release` ordering.
69///  5. Stores `refcount = 1` with `Release` ordering so any future reader
70///     that loads the refcount with `Acquire` observes a fully-initialised frame.
71///
72/// This matches the Asterinas OSTD pattern (`FrameAllocOptions` + per-frame
73/// [`MetaSlot`](crate::memory::MetaSlot) with refcount CAS). Metadata lives in
74/// dedicated slots (not in mapped page bytes); see [`get_meta_slot`](crate::memory::get_meta_slot).
75pub struct BuddyFrameAllocator;
76
77// SAFETY: `BuddyFrameAllocator::allocate_frame` returns 4KiB-aligned,
78// exclusively-owned physical frames.  Exclusive ownership is guaranteed by
79// the buddy's own bitmap + free-list discipline.  Frames allocated with
80// `FramePurpose::PageTable` are always fully zeroed before being returned.
81#[cfg(target_arch = "x86_64")]
82unsafe impl X86FrameAllocator<Size4KiB> for BuddyFrameAllocator {
83    fn allocate_frame(&mut self) -> Option<X86PhysFrame<Size4KiB>> {
84        // `with_irqs_disabled` produces a real `IrqDisabledToken`, saving and
85        // restoring RFLAGS, so it is correct even when the caller already holds
86        // IRQs disabled (e.g. during early boot or under a scheduler/AddressSpace
87        // lock).
88        let frame = crate::sync::with_irqs_disabled(|token| {
89            FrameAllocOptions::new()
90                .purpose(FramePurpose::PageTable)
91                .allocate(token)
92        })
93        .ok()?;
94
95        // `PageTable` purpose enforces:
96        //  - `zeroed = true` unconditionally (cannot be overridden by callers).
97        //  - `FrameMeta::flags` stamped with `KERNEL | ALLOCATED`.
98        //  - `FrameMeta::refcount` set to 1 with `Release` ordering after
99        //    zeroing, so any `Acquire` load of the refcount observes a clean
100        //    frame.
101        X86PhysFrame::from_start_address(frame.start_address).ok()
102    }
103}
104#[cfg(not(target_arch = "x86_64"))]
105impl crate::arch::x86_64::structures::paging::FrameAllocator<crate::arch::xshim::Size4KiB>
106    for BuddyFrameAllocator
107{
108    fn allocate_frame(
109        &mut self,
110    ) -> Option<crate::arch::xshim::PhysFrame<crate::arch::xshim::Size4KiB>> {
111        None // R2: real Sv48 frame allocation
112    }
113}
114
115/// Paging initialization flag.
116static mut PAGING_READY: bool = false;
117
118/// Physical address of the kernel's level-4 page table (set at init, never changes).
119static mut KERNEL_CR3: PhysAddr = PhysAddr::new_truncate(0);
120
121/// Serializes mutations of the canonical kernel page tables.
122///
123/// The active-CR3 mapping helpers are still caller-synchronized by their own
124/// higher-level address-space locks, but kernel-global mappings such as vmalloc
125/// must not race while allocating or wiring intermediate page-table levels.
126static KERNEL_PT_LOCK: SpinLock<()> = SpinLock::new(());
127
128/// Returns whether initialized.
129pub fn is_initialized() -> bool {
130    unsafe { *(&raw const PAGING_READY) }
131}
132
133/// Initialize the paging subsystem.
134///
135/// Reads the active CR3 (level-4 page table) and creates an `OffsetPageTable`
136/// mapper using the HHDM offset for physical-to-virtual translation.
137///
138/// Must be called after the buddy allocator and HHDM offset are initialized.
139pub fn init(hhdm_offset: u64) {
140    let phys_offset = VirtAddr::new(hhdm_offset);
141    let (level_4_frame, _flags) = Cr3::read();
142    let level_4_phys = level_4_frame.start_address().as_u64();
143    let level_4_virt = phys_offset + level_4_phys;
144
145    // SAFETY: called once during single-threaded init. The HHDM offset correctly
146    // maps all physical RAM to virtual addresses. CR3 points to a valid page table
147    // set up by the bootloader.
148    unsafe {
149        let kcr3 = &raw mut KERNEL_CR3;
150        *kcr3 = level_4_frame.start_address();
151        let ready = &raw mut PAGING_READY;
152        *ready = true;
153    }
154
155    log::info!(
156        "Paging initialized: CR3={:#x}, HHDM={:#x}, L4 table @ {:#x}",
157        level_4_phys,
158        hhdm_offset,
159        level_4_virt.as_u64(),
160    );
161}
162
163/// Map all RAM regions from the memory map into the HHDM.
164///
165/// This ensures that every byte of physical RAM is accessible through the
166/// higher-half direct map. Should be called after paging::init.
167/// Fix for VMWare Workstation which doesn't identity-map all RAM by default, causing
168/// the kernel to crash when it tries to access unmapped RAM (e.g. for the buddy allocator's
169/// metadata array). The bootloader's initial map only covers the first 1GB of RAM, which is not enough
170/// for our 2GB test VM. This function lazily maps any missing RAM regions on
171/// demand using `ensure_identity_map_range()`, which checks if the region is already mapped
172/// before mapping it. This allows the kernel to boot successfully on VMWare Workstation without
173/// requiring changes to the bootloader configuration.
174///
175pub fn map_all_ram(memory_regions: &[crate::boot::entry::MemoryRegion]) {
176    use crate::boot::entry::MemoryKind;
177
178    for region in memory_regions {
179        if matches!(region.kind, MemoryKind::Free | MemoryKind::Reclaim) {
180            log::debug!(
181                "Mapping RAM region to HHDM: phys=0x{:x}..0x{:x}",
182                region.base,
183                region.base + region.size
184            );
185            ensure_hhdm_range(
186                region.base,
187                region.size,
188                PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::NO_EXECUTE,
189            );
190        }
191    }
192}
193
194/// Map a virtual page to a physical frame with the given flags.
195///
196/// Intermediate page tables are allocated from the buddy allocator as needed.
197pub fn map_page(
198    page: Page<Size4KiB>,
199    frame: X86PhysFrame<Size4KiB>,
200    flags: PageTableFlags,
201) -> Result<(), &'static str> {
202    if !is_initialized() {
203        return Err("Paging not initialized");
204    }
205    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
206    let (level_4_frame, _) = Cr3::read();
207    let level_4_virt = phys_offset + level_4_frame.start_address().as_u64();
208    // SAFETY: level_4_virt points to the active CR3 PML4 via HHDM.
209    let mapper = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
210    let mut mapper = unsafe { OffsetPageTable::new(mapper, phys_offset) };
211    let mut allocator = BuddyFrameAllocator;
212
213    unsafe {
214        mapper
215            .map_to(page, frame, flags, &mut allocator)
216            .map_err(|_| "Failed to map page")?
217            .flush();
218    }
219    Ok(())
220}
221
222/// Map a page into the kernel's canonical page tables (not the active CR3).
223///
224/// This ensures that the mapping is visible from all address spaces, because
225/// every user address space clones the kernel half (PML4[256..512]) from the
226/// kernel's L4 table at creation time.
227///
228/// Used by vmalloc so that heap allocations are kernel-global.
229/// Intermediate page tables are allocated from the buddy allocator as needed.
230pub fn map_page_kernel(
231    page: Page<Size4KiB>,
232    frame: X86PhysFrame<Size4KiB>,
233    flags: PageTableFlags,
234) -> Result<(), &'static str> {
235    if !is_initialized() {
236        return Err("Paging not initialized");
237    }
238    let _guard = KERNEL_PT_LOCK.lock();
239    // SAFETY: KERNEL_CR3 is set once during init and never changes.
240    let kernel_cr3 = unsafe { *(&raw const KERNEL_CR3) };
241    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
242    let level_4_virt = phys_offset + kernel_cr3.as_u64();
243    // SAFETY: level_4_virt points to the kernel's L4 table via HHDM.
244    let mapper = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
245    let mut mapper = unsafe { OffsetPageTable::new(mapper, phys_offset) };
246    let mut allocator = BuddyFrameAllocator;
247
248    unsafe {
249        use crate::x86_crate_shim::structures::paging::mapper::MapToError;
250        mapper
251            .map_to(page, frame, flags, &mut allocator)
252            .map_err(|e| match e {
253                MapToError::ParentEntryHugePage => "Failed to map page (kernel): parent huge page",
254                MapToError::PageAlreadyMapped(_) => {
255                    "Failed to map page (kernel): page already mapped"
256                }
257                MapToError::FrameAllocationFailed => {
258                    "Failed to map page (kernel): frame allocation failed"
259                }
260            })?
261            .flush();
262    }
263    Ok(())
264}
265
266/// Unmap a page from the active CR3, returning the physical frame.
267pub fn unmap_page(page: Page<Size4KiB>) -> Result<X86PhysFrame<Size4KiB>, &'static str> {
268    if !is_initialized() {
269        return Err("Paging not initialized");
270    }
271    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
272    let (level_4_frame, _) = Cr3::read();
273    let level_4_virt = phys_offset + level_4_frame.start_address().as_u64();
274    // SAFETY: level_4_virt points to the active CR3 PML4 via HHDM.
275    let mapper = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
276    let mut mapper = unsafe { OffsetPageTable::new(mapper, phys_offset) };
277    let (frame, flush) = mapper.unmap(page).map_err(|_| "Failed to unmap page")?;
278    flush.flush();
279    Ok(frame)
280}
281
282/// Unmap a page from the kernel's canonical page tables.
283///
284/// This is the counterpart to `map_page_kernel`. It removes the mapping from
285/// the kernel's L4 table so that the page is no longer visible in any address
286/// space.
287pub fn unmap_page_kernel(page: Page<Size4KiB>) -> Result<X86PhysFrame<Size4KiB>, &'static str> {
288    if !is_initialized() {
289        return Err("Paging not initialized");
290    }
291    let _guard = KERNEL_PT_LOCK.lock();
292    // SAFETY: KERNEL_CR3 is set once during init and never changes.
293    let kernel_cr3 = unsafe { *(&raw const KERNEL_CR3) };
294    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
295    let level_4_virt = phys_offset + kernel_cr3.as_u64();
296    // SAFETY: level_4_virt points to the kernel's L4 table via HHDM.
297    let mapper = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
298    let mut mapper = unsafe { OffsetPageTable::new(mapper, phys_offset) };
299    let (frame, flush) = mapper
300        .unmap(page)
301        .map_err(|_| "Failed to unmap page (kernel)")?;
302    flush.flush();
303    Ok(frame)
304}
305
306/// Translate a virtual address to its mapped physical address.
307///
308/// Returns `None` if the address is not mapped.
309pub fn translate(addr: VirtAddr) -> Option<PhysAddr> {
310    if !is_initialized() {
311        return None;
312    }
313    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
314    let (level_4_frame, _) = Cr3::read();
315    let level_4_virt = phys_offset + level_4_frame.start_address().as_u64();
316    // SAFETY: level_4_virt points to the active CR3 PML4 via HHDM.
317    let mapper = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
318    let mapper = unsafe { OffsetPageTable::new(mapper, phys_offset) };
319    mapper.translate_addr(addr)
320}
321
322#[allow(dead_code)] // Retained active-page-table translation wrapper.
323fn translate_via_active_page_tables(addr: VirtAddr) -> Option<PhysAddr> {
324    translate_via_active_page_tables_sized(addr).map(|(phys, _)| phys)
325}
326
327/// Same walk as [`translate_via_active_page_tables`], also returning the size in
328/// bytes of the leaf page that maps `addr` (4 KiB, 2 MiB or 1 GiB).
329fn translate_via_active_page_tables_sized(addr: VirtAddr) -> Option<(PhysAddr, u64)> {
330    let hhdm = crate::memory::hhdm_offset();
331    let (level_4_frame, _) = Cr3::read();
332
333    unsafe {
334        let l4_ptr = (level_4_frame.start_address().as_u64() + hhdm) as *const u64;
335        let l4e = *l4_ptr.add(((addr.as_u64() >> 39) & 0x1FF) as usize);
336        if l4e & 1 == 0 {
337            return None;
338        }
339
340        let l3_ptr = ((l4e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
341        let l3e = *l3_ptr.add(((addr.as_u64() >> 30) & 0x1FF) as usize);
342        if l3e & 1 == 0 {
343            return None;
344        }
345        if l3e & 0x80 != 0 {
346            return Some((
347                PhysAddr::new((l3e & 0x000F_FFFF_C000_0000) + (addr.as_u64() & 0x3FFF_FFFF)),
348                1 << 30,
349            ));
350        }
351
352        let l2_ptr = ((l3e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
353        let l2e = *l2_ptr.add(((addr.as_u64() >> 21) & 0x1FF) as usize);
354        if l2e & 1 == 0 {
355            return None;
356        }
357        if l2e & 0x80 != 0 {
358            return Some((
359                PhysAddr::new((l2e & 0x000F_FFFF_FFE0_0000) + (addr.as_u64() & 0x1F_FFFF)),
360                1 << 21,
361            ));
362        }
363
364        let l1_ptr = ((l2e & 0x000F_FFFF_FFFF_F000) + hhdm) as *const u64;
365        let l1e = *l1_ptr.add(((addr.as_u64() >> 12) & 0x1FF) as usize);
366        if l1e & 1 == 0 {
367            return None;
368        }
369
370        Some((
371            PhysAddr::new((l1e & 0x000F_FFFF_FFFF_F000) + (addr.as_u64() & 0xFFF)),
372            4096,
373        ))
374    }
375}
376
377/// Returns whether the current page tables map the HHDM view of the whole range.
378///
379/// This helper is safe before `paging::init()` and is intended for early boot
380/// allocators that must only touch memory already reachable through the current
381/// firmware-provided direct map.
382pub fn is_hhdm_range_mapped_now(phys_base: u64, size: u64) -> bool {
383    if size == 0 {
384        return true;
385    }
386
387    let start = phys_base & !0xFFF;
388    let end = phys_base.saturating_add(size).saturating_add(0xFFF) & !0xFFF;
389
390    crate::e9_mark!(b'*');
391    let mut phys = start;
392    while phys < end {
393        let virt = VirtAddr::new(crate::memory::phys_to_virt(phys));
394        let (mapped, page_size) = match translate_via_active_page_tables_sized(virt) {
395            Some(m) => m,
396            None => return false,
397        };
398        if mapped.as_u64() != phys {
399            return false;
400        }
401        // A 2 MiB / 1 GiB leaf maps the rest of its extent linearly, so every
402        // 4 KiB page up to the end of this leaf is mapped identically: skip it
403        // instead of re-walking the tables once per page (a 2 GiB region was
404        // ~500k walks, repeated by boot_alloc's binary search).
405        let remaining_in_page = page_size - (virt.as_u64() & (page_size - 1));
406        phys = phys.saturating_add(remaining_in_page);
407    }
408    crate::e9_mark!(b'+');
409    true
410}
411
412/// Read the current CR3 value (physical address of the active level-4 page table).
413pub fn active_page_table() -> PhysAddr {
414    let (frame, _) = Cr3::read();
415    frame.start_address()
416}
417
418/// Return the physical address of the kernel's level-4 page table.
419///
420/// This is the CR3 value captured at init time : used by `AddressSpace::new_user()`
421/// to clone kernel mappings (PML4 entries 256..512) into new address spaces.
422pub fn kernel_l4_phys() -> PhysAddr {
423    // SAFETY: Written once during single-threaded init, read-only after that.
424    unsafe { *(&raw const KERNEL_CR3) }
425}
426
427/// Ensure a physical address is identity-mapped in the HHDM region.
428///
429/// If the page is not present, it is mapped with Read/Write permissions.
430/// This is used to lazily map MMIO or legacy BIOS regions (like ACPI tables)
431/// that might have been skipped by the bootloader's initial map.
432pub fn ensure_identity_map(phys_addr: u64) {
433    let virt_addr = crate::memory::phys_to_virt(phys_addr);
434    let page = Page::<Size4KiB>::containing_address(VirtAddr::new(virt_addr));
435    let frame = X86PhysFrame::<Size4KiB>::containing_address(PhysAddr::new(phys_addr));
436
437    if translate(VirtAddr::new(virt_addr)).is_none() {
438        log::debug!(
439            "Identity mapping missing page: {:#x} -> {:#x}",
440            phys_addr,
441            virt_addr
442        );
443        let flags = uncached_hhdm_flags();
444        if let Err(e) = map_page(page, frame, flags) {
445            log::error!("Failed to identity map {:#x}: {}", phys_addr, e);
446        }
447    }
448}
449
450/// Ensure a physical range is mapped in the HHDM region.
451///
452/// Builds a single `OffsetPageTable` for the entire range instead of
453/// one per page, and emits a single summary log instead of per-page noise.
454pub fn ensure_identity_map_range(phys_base: u64, size: u64) {
455    ensure_hhdm_range(phys_base, size, uncached_hhdm_flags());
456}
457
458fn uncached_hhdm_flags() -> PageTableFlags {
459    let flags = PageTableFlags::PRESENT
460        | PageTableFlags::WRITABLE
461        | PageTableFlags::NO_EXECUTE
462        | PageTableFlags::NO_CACHE;
463    #[cfg(target_arch = "x86_64")]
464    let flags = flags | PageTableFlags::WRITE_THROUGH; // PAT[3] = UC, not UC-.
465    flags
466}
467
468/// Flags selecting write-combining (WC) for a 4 KiB HHDM mapping.
469///
470/// The PAT index is `(PAT << 2) | (PCD << 1) | PWT` with PAT = PTE bit 12.
471/// `arch::x86_64::pat::init()` programs slot 1 (index `0b001`) as WC, which a
472/// leaf selects with `PWT = 1`, `PCD = 0` and the PAT bit clear. Setting bit
473/// 12 instead would select slot 4, which stays Uncacheable.
474#[cfg(target_arch = "x86_64")]
475fn wc_hhdm_flags() -> PageTableFlags {
476    // PAT index for 4 KiB pages is `(PAT << 2) | (PCD << 1) | PWT`.
477    // PA1 is programmed to Write-Combining by `arch::x86_64::pat`, so a WC
478    // leaf selects it with PWT=1, PCD=0 and the PAT bit (bit 12) clear.
479    // Using bit 12 here would select PA4, which stays Uncacheable.
480    PageTableFlags::PRESENT
481        | PageTableFlags::WRITABLE
482        | PageTableFlags::NO_EXECUTE
483        | PageTableFlags::WRITE_THROUGH
484}
485
486/// Whether this CPU can map memory as write-combining through PAT.
487///
488/// Returns `false` on architectures without PAT.
489pub fn framebuffer_wc_supported() -> bool {
490    #[cfg(target_arch = "x86_64")]
491    {
492        crate::arch::x86_64::pat::wc_supported()
493    }
494    #[cfg(not(target_arch = "x86_64"))]
495    {
496        false
497    }
498}
499
500/// Map a physical framebuffer range into the HHDM as write-combining (WC).
501///
502/// Unlike [`ensure_identity_map_range`], this helper **updates** the cache
503/// policy of pages that are already mapped (firmware framebuffer mappings or
504/// RAM the bootloader already described): a WC framebuffer is only useful if
505/// the existing WB/UC leaf is rewritten. Pages that are not mapped at all are
506/// created with WC flags.
507///
508/// Only the requested range is touched. On CPUs whose PAT has no WC slot the
509/// call falls back to the UC identity mapping so the framebuffer remains
510/// usable (with slower MMIO writes) instead of unmapped.
511pub fn ensure_framebuffer_range_wc(phys_base: u64, size: u64) {
512    #[cfg(not(target_arch = "x86_64"))]
513    {
514        let _ = (phys_base, size);
515        return;
516    }
517
518    #[cfg(target_arch = "x86_64")]
519    {
520        use crate::x86_crate_shim::structures::paging::{
521            mapper::{MappedFrame, TranslateResult},
522            PageSize, Size1GiB, Size2MiB,
523        };
524
525        if size == 0 || !is_initialized() {
526            return;
527        }
528
529        if !framebuffer_wc_supported() {
530            log::warn!(
531                "IA32_PAT has no WC slot; mapping framebuffer {:#x}..{:#x} as UC",
532                phys_base,
533                phys_base.saturating_add(size),
534            );
535            ensure_identity_map_range(phys_base, size);
536            return;
537        }
538
539        let page_size = 4096u64;
540        let start = phys_base & !(page_size - 1);
541        let end = (phys_base.saturating_add(size).saturating_add(page_size - 1)) & !(page_size - 1);
542        if start >= end {
543            return;
544        }
545
546        let _guard = KERNEL_PT_LOCK.lock();
547        let flags = wc_hhdm_flags();
548        let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
549        let (level_4_frame, _) = Cr3::read();
550        let level_4_virt = phys_offset + level_4_frame.start_address().as_u64();
551
552        // SAFETY: level_4_virt points to the active CR3 PML4 via HHDM.
553        let l4_table = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
554        let mut mapper = unsafe { OffsetPageTable::new(l4_table, phys_offset) };
555        let mut allocator = BuddyFrameAllocator;
556
557        let mut mapped_count: u64 = 0;
558        let mut updated_count: u64 = 0;
559        let mut p = start;
560        while p < end {
561            let virt = VirtAddr::new(crate::memory::phys_to_virt(p));
562            let page = Page::<Size4KiB>::containing_address(virt);
563
564            if mapper.translate_addr(virt).is_none() {
565                let frame = X86PhysFrame::<Size4KiB>::containing_address(PhysAddr::new(p));
566                // SAFETY: frame is a valid physical page; mapper uses HHDM offset.
567                match unsafe { mapper.map_to(page, frame, flags, &mut allocator) } {
568                    Ok(flush) => {
569                        flush.flush();
570                        mapped_count += 1;
571                    }
572                    Err(_) => {
573                        log::error!("ensure_framebuffer_range_wc: failed to map {:#x}", p);
574                    }
575                }
576            } else {
577                // The bootloader often maps the HHDM with 2 MiB / 1 GiB leaves.
578                // Retype a huge leaf as a whole when it lies entirely inside
579                // the framebuffer; otherwise leave it alone (it also covers
580                // unrelated memory) and skip to its end with a single warning.
581                let huge_size = match mapper.translate(virt) {
582                    TranslateResult::Mapped {
583                        frame: MappedFrame::Size2MiB(_),
584                        ..
585                    } => Some(Size2MiB::SIZE),
586                    TranslateResult::Mapped {
587                        frame: MappedFrame::Size1GiB(_),
588                        ..
589                    } => Some(Size1GiB::SIZE),
590                    _ => None,
591                };
592
593                if let Some(huge) = huge_size {
594                    let huge_start = p & !(huge - 1);
595                    let huge_end = huge_start.saturating_add(huge);
596                    if huge_start >= start && huge_end <= end {
597                        let res = if huge == Size2MiB::SIZE {
598                            let hp = Page::<Size2MiB>::containing_address(virt);
599                            // SAFETY: the leaf exists and lies entirely inside
600                            // the framebuffer; only its cache policy changes.
601                            unsafe { mapper.update_flags(hp, flags) }.map(|f| f.flush())
602                        } else {
603                            let hp = Page::<Size1GiB>::containing_address(virt);
604                            // SAFETY: as above, for a 1 GiB leaf.
605                            unsafe { mapper.update_flags(hp, flags) }.map(|f| f.flush())
606                        };
607                        match res {
608                            Ok(()) => updated_count += huge / page_size,
609                            Err(_) => log::error!(
610                                "ensure_framebuffer_range_wc: failed to update huge page {:#x}",
611                                huge_start
612                            ),
613                        }
614                    } else {
615                        log::warn!(
616                            "ensure_framebuffer_range_wc: huge page {:#x}..{:#x} extends \
617                             outside the framebuffer; WC not applied",
618                            huge_start,
619                            huge_end
620                        );
621                    }
622                    p = huge_end;
623                    continue;
624                }
625
626                // SAFETY: the mapping exists and the flags only change cache
627                // policy; the caller is wiring a framebuffer under its lock.
628                match unsafe { mapper.update_flags(page, flags) } {
629                    Ok(flush) => {
630                        flush.flush();
631                        updated_count += 1;
632                    }
633                    Err(_) => {
634                        log::error!("ensure_framebuffer_range_wc: failed to update {:#x}", p);
635                    }
636                }
637            }
638            p = p.saturating_add(page_size);
639        }
640
641        // Other CPUs may hold stale TLB entries for the HHDM range. The IPI
642        // path is a no-op until the APIC is initialized (early boot).
643        if mapped_count + updated_count > 0 {
644            let virt_start = VirtAddr::new(crate::memory::phys_to_virt(start));
645            let virt_end = VirtAddr::new(crate::memory::phys_to_virt(end));
646            crate::arch::x86_64::tlb::shootdown_range(virt_start, virt_end);
647            log::debug!(
648                "Framebuffer WC: {} mapped, {} retyped, phys {:#x}..{:#x}",
649                mapped_count,
650                updated_count,
651                start,
652                end,
653            );
654        }
655
656        // A memory-type change needs more than a TLB flush: CPUs may still
657        // hold cache lines for the same physical memory filled under the old
658        // (WB) type. WBINVD on every CPU drops them; a TLB flush alone would
659        // leave the stale lines in place.
660        if updated_count > 0 {
661            crate::arch::x86_64::tlb::shootdown_caches();
662        }
663    }
664}
665
666// Existing mappings retain their cache policy and ELF protections. Only the
667// RAM-map caller requests WB; missing MMIO/firmware pages use UC and NX.
668fn ensure_hhdm_range(phys_base: u64, size: u64, flags: PageTableFlags) {
669    if size == 0 || !is_initialized() {
670        return;
671    }
672
673    let page_size = 4096u64;
674    let start = phys_base & !(page_size - 1);
675    let end = (phys_base.saturating_add(size).saturating_add(page_size - 1)) & !(page_size - 1);
676    if start >= end {
677        return;
678    }
679
680    let phys_offset = VirtAddr::new(crate::memory::hhdm_offset());
681    let (level_4_frame, _) = Cr3::read();
682    let level_4_virt = phys_offset + level_4_frame.start_address().as_u64();
683
684    // SAFETY: level_4_virt points to the active CR3 PML4 via HHDM.
685    let l4_table = unsafe { &mut *level_4_virt.as_mut_ptr::<PageTable>() };
686    let mut mapper = unsafe { OffsetPageTable::new(l4_table, phys_offset) };
687    let mut allocator = BuddyFrameAllocator;
688
689    let mut mapped_count: u64 = 0;
690    let mut p = start;
691    while p < end {
692        let virt = VirtAddr::new(crate::memory::phys_to_virt(p));
693        // Only map if not already present.
694        if mapper.translate_addr(virt).is_none() {
695            let page = Page::<Size4KiB>::containing_address(virt);
696            let frame = X86PhysFrame::<Size4KiB>::containing_address(PhysAddr::new(p));
697            // SAFETY: frame is a valid physical page; mapper uses HHDM offset.
698            match unsafe { mapper.map_to(page, frame, flags, &mut allocator) } {
699                Ok(flush) => {
700                    flush.flush();
701                    mapped_count += 1;
702                }
703                Err(_) => {
704                    log::error!("ensure_identity_map_range: failed to map {:#x}", p);
705                }
706            }
707        }
708        p = p.saturating_add(page_size);
709    }
710
711    if mapped_count > 0 {
712        log::debug!(
713            "Identity mapped {} pages: phys {:#x}..{:#x}",
714            mapped_count,
715            start,
716            end,
717        );
718    }
719}
720
721/// Revoke the loader's temporary identity RX pages before starting allocators.
722///
723/// # Safety
724/// BSP-only, interrupts disabled, before AP startup. CR3 must be the Strat9
725/// UEFI loader's tables and the HHDM must already be set. The kernel runs in its
726/// separate higher-half mapping. There are no global leaves in these tables.
727#[cfg(target_arch = "x86_64")]
728pub unsafe fn retire_uefi_identity_code() {
729    const ADDRESS: u64 = 0x000F_FFFF_FFFF_F000;
730    const NX: u64 = 1 << 63;
731    unsafe fn retire(table_phys: u64, level: u8) {
732        let table = crate::memory::phys_to_virt(table_phys) as *mut u64;
733        for index in 0..512 {
734            let slot = unsafe { table.add(index) };
735            let entry = unsafe { slot.read_volatile() };
736            if entry & 1 == 0 {
737                continue;
738            }
739            if level == 1 || entry & (1 << 7) != 0 {
740                if entry & NX == 0 {
741                    unsafe { slot.write_volatile(entry | NX | 2) };
742                }
743            } else {
744                unsafe { retire(entry & ADDRESS, level - 1) };
745            }
746        }
747    }
748    let cr3: u64;
749    unsafe {
750        core::arch::asm!("mov {}, cr3", out(reg) cr3, options(nomem, nostack, preserves_flags))
751    };
752    let root = crate::memory::phys_to_virt(cr3 & ADDRESS) as *const u64;
753    let identity = unsafe { root.read_volatile() };
754    if identity & 1 != 0 {
755        unsafe { retire(identity & ADDRESS, 3) };
756    }
757    unsafe { core::arch::asm!("mov cr3, {}", in(reg) cr3, options(nostack, preserves_flags)) };
758}
759
760/// Change execution of just the existing 4 KiB identity trampoline page,
761/// preserving its cache selector. BSP enables it before SIPI and retires it
762/// after every AP has left it. APs invalidate their TLB at the boot barrier.
763#[cfg(target_arch = "x86_64")]
764pub fn set_trampoline_execution(physical: u64, executable: bool) -> Result<(), &'static str> {
765    if physical != 0x8000 {
766        return Err("unexpected AP trampoline page");
767    }
768    let _guard = KERNEL_PT_LOCK.lock();
769    let (frame, _) = Cr3::read();
770    let mut table = frame.start_address().as_u64();
771    const ADDRESS: u64 = 0x000F_FFFF_FFFF_F000;
772    for shift in [39, 30, 21, 12] {
773        let slot = (crate::memory::phys_to_virt(table) as *mut u64)
774            .wrapping_add(((physical >> shift) & 511) as usize);
775        let entry = unsafe { slot.read_volatile() };
776        if entry & 1 == 0 {
777            return Err("missing AP identity page");
778        }
779        if shift != 12 && entry & (1 << 7) != 0 {
780            // Legacy loaders may supply an already executable huge identity
781            // mapping. Do not silently make a whole NX huge page executable.
782            return if executable && entry & (1 << 63) == 0 {
783                Ok(())
784            } else {
785                Err("AP identity mapping requires a 4 KiB leaf")
786            };
787        }
788        if shift == 12 {
789            if entry & ADDRESS != physical {
790                return Err("AP identity mapping collision");
791            }
792            unsafe {
793                let updated = if executable {
794                    entry & !((1 << 63) | 2)
795                } else {
796                    entry | (1 << 63)
797                }; // Retired trampoline stays read-only.
798                slot.write_volatile(updated);
799                core::arch::asm!("invlpg [{}]", in(reg) physical, options(nostack, preserves_flags));
800            }
801            return Ok(());
802        }
803        table = entry & ADDRESS;
804    }
805    Err("invalid AP identity mapping")
806}