:: commit 8cd645e0584e6e1c88fe928e69984510adfcbe6b

Mintsuki <mintsuki@protonmail.com> — 2026-05-18 02:26

parents: cfb6f79f48

mm/efi_pt: Map FB as WC via PAT page-table edits instead of MTRRs on x86-64

diff --git a/common/lib/gterm.c b/common/lib/gterm.c
index 2cded5ee..4a352c7b 100644
--- a/common/lib/gterm.c
+++ b/common/lib/gterm.c
@@ -820,9 +820,10 @@ bool gterm_init(struct fb_info **_fbs, size_t *_fbs_count,
         if (fb_size == 0) {
             continue;
         }
-        mtrr_wc_add_fb_range(fbs[i].framebuffer_addr, fb_size);
 #if defined (__x86_64__) && defined (UEFI)
-        efi_pt_set_fb_uc_minus(fbs[i].framebuffer_addr, fb_size);
+        efi_pt_set_fb_wc(fbs[i].framebuffer_addr, fb_size);
+#else
+        mtrr_wc_add_fb_range(fbs[i].framebuffer_addr, fb_size);
 #endif
     }
 #endif
diff --git a/common/lib/term.c b/common/lib/term.c
index 84951b93..201c70d6 100644
--- a/common/lib/term.c
+++ b/common/lib/term.c
@@ -7,6 +7,7 @@
 #include <lib/fb.h>
 #include <mm/pmm.h>
 #include <mm/mtrr.h>
+#include <mm/efi_pt.h>
 #include <drivers/vga_textmode.h>
 #include <flanterm_backends/fb.h>
 
@@ -33,7 +34,11 @@ void term_notready(bool preserve_screen) {
     }
 
 #if defined (__i386__) || defined (__x86_64__)
+#if defined (__x86_64__) && defined (UEFI)
+    efi_pt_restore();
+#else
     mtrr_restore();
+#endif
 #endif
 
     for (size_t i = 0; i < terms_i; i++) {
diff --git a/common/mm/efi_pt.c b/common/mm/efi_pt.c
index 4285fddb..e00d7a74 100644
--- a/common/mm/efi_pt.c
+++ b/common/mm/efi_pt.c
@@ -4,22 +4,22 @@
 #include <stddef.h>
 #include <stdbool.h>
 #include <mm/efi_pt.h>
+#include <mm/pmm.h>
 #include <sys/cpu.h>
 
 #define PTE_P ((uint64_t)1 << 0)
+#define PTE_RW ((uint64_t)1 << 1)
+#define PTE_US ((uint64_t)1 << 2)
 #define PTE_PWT ((uint64_t)1 << 3)
 #define PTE_PCD ((uint64_t)1 << 4)
 #define PTE_PS ((uint64_t)1 << 7)
 #define PTE_PAT_4K ((uint64_t)1 << 7)
 #define PTE_PAT_BIG ((uint64_t)1 << 12)
+#define PTE_NX ((uint64_t)1 << 63)
 #define PT_ADDR_MASK ((uint64_t)0x000FFFFFFFFFF000)
 
-#define UCM_MASK_4K (PTE_PWT | PTE_PCD | PTE_PAT_4K)
-#define UCM_MASK_BIG (PTE_PWT | PTE_PCD | PTE_PAT_BIG)
-#define UCM_VALUE PTE_PCD
-
 #define IA32_PAT_MSR 0x277
-#define PAT_TYPE_UCM 0x07
+#define PAT_TYPE_WC 0x01
 
 static bool la57_enabled(void) {
     uint64_t cr4;
@@ -27,81 +27,321 @@ static bool la57_enabled(void) {
     return !!(cr4 & ((uint64_t)1 << 12));
 }
 
-static bool pat_slot2_is_ucm(void) {
-    static bool checked = false, ok = false;
-    if (checked) {
-        return ok;
+// Firmware PTEs we overwrote, replayed by efi_pt_restore() to undo the FB WC.
+// On overflow we stop applying WC so the undo stays complete.
+#define SAVED_PTES_MAX 1024
+
+static uint64_t **saved_pte_ptr = NULL;
+static uint64_t *saved_pte_val = NULL;
+static size_t saved_pte_i = 0;
+static uint64_t saved_pat = 0;
+static bool pat_modified = false;
+
+static int wc_pat_index = -1;
+
+static bool save_pte(uint64_t *slot) {
+    if (saved_pte_i >= SAVED_PTES_MAX) {
+        return false;
+    }
+    saved_pte_ptr[saved_pte_i] = slot;
+    saved_pte_val[saved_pte_i] = *slot;
+    saved_pte_i++;
+    return true;
+}
+
+// Caches off + TLB flushed for a safe PAT-MSR memory-type change.
+static void cache_off(uint64_t *old_cr0) {
+    asm volatile ("mov %%cr0, %0" : "=r"(*old_cr0) :: "memory");
+    asm volatile ("mov %0, %%cr0"
+        :: "r"((*old_cr0 | ((uint64_t)1 << 30)) & ~((uint64_t)1 << 29))
+        : "memory");
+    asm volatile ("wbinvd" ::: "memory");
+    uint64_t cr3;
+    asm volatile ("mov %%cr3, %0" : "=r"(cr3) :: "memory");
+    asm volatile ("mov %0, %%cr3" :: "r"(cr3) : "memory");
+}
+
+static void cache_on(uint64_t old_cr0) {
+    uint64_t cr3;
+    asm volatile ("mov %%cr3, %0" : "=r"(cr3) :: "memory");
+    asm volatile ("mov %0, %%cr3" :: "r"(cr3) : "memory");
+    asm volatile ("wbinvd" ::: "memory");
+    asm volatile ("mov %0, %%cr0" :: "r"(old_cr0) : "memory");
+}
+
+// WP off to write read-only firmware PTEs; wp_on flushes the TLB to apply them.
+static void wp_off(uint64_t *old_cr0) {
+    asm volatile ("mov %%cr0, %0" : "=r"(*old_cr0) :: "memory");
+    asm volatile ("mov %0, %%cr0" :: "r"(*old_cr0 & ~((uint64_t)1 << 16)) : "memory");
+}
+
+static void wp_on(uint64_t old_cr0) {
+    // A plain CR3 reload leaves global TLB entries intact, so a firmware FB
+    // mapped with the global bit would keep its old memory type. Toggling
+    // CR4.PGE flushes the whole TLB including global entries (Intel SDM
+    // 4.10.4.1); fall back to a CR3 reload when PGE is off (no globals exist).
+    uint64_t cr4;
+    asm volatile ("mov %%cr4, %0" : "=r"(cr4) :: "memory");
+    if (cr4 & ((uint64_t)1 << 7)) {
+        asm volatile ("mov %0, %%cr4" :: "r"(cr4 & ~((uint64_t)1 << 7)) : "memory");
+        asm volatile ("mov %0, %%cr4" :: "r"(cr4) : "memory");
+    } else {
+        uint64_t cr3;
+        asm volatile ("mov %%cr3, %0" : "=r"(cr3) :: "memory");
+        asm volatile ("mov %0, %%cr3" :: "r"(cr3) : "memory");
+    }
+    asm volatile ("mov %0, %%cr0" :: "r"(old_cr0) : "memory");
+}
+
+static int pte_pat_index(uint64_t e, bool leaf4k) {
+    uint64_t patbit = leaf4k ? PTE_PAT_4K : PTE_PAT_BIG;
+    return (!!(e & patbit) << 2) | (!!(e & PTE_PCD) << 1) | !!(e & PTE_PWT);
+}
+
+// Non-leaf entries and CR3 have no PAT bit: typed by PCD/PWT only.
+static int walk_pat_index(uint64_t e) {
+    return (!!(e & PTE_PCD) << 1) | !!(e & PTE_PWT);
+}
+
+static void scan_walk(uint64_t *table, int lvl, uint8_t *used) {
+    for (size_t i = 0; i < 512; i++) {
+        if (*used == 0xff) {
+            return;
+        }
+        uint64_t e = table[i];
+        if (!(e & PTE_P)) {
+            continue;
+        }
+        if ((lvl == 1) || (lvl <= 3 && (e & PTE_PS))) {
+            *used |= 1 << pte_pat_index(e, lvl == 1);
+        } else {
+            *used |= 1 << walk_pat_index(e);
+            scan_walk((uint64_t *)(e & PT_ADDR_MASK), lvl - 1, used);
+        }
+    }
+}
+
+static uint8_t scan_used_pat_indices(void) {
+    uint64_t cr3;
+    asm volatile ("mov %%cr3, %0" : "=r"(cr3));
+    uint8_t used = 1 << walk_pat_index(cr3);
+    scan_walk((uint64_t *)(cr3 & PT_ADDR_MASK), la57_enabled() ? 5 : 4, &used);
+    return used;
+}
+
+// Reuse a WC slot if present, else repurpose one no live mapping selects.
+static bool ensure_wc_pat_slot(void) {
+    if (wc_pat_index >= 0) {
+        return true;
     }
-    checked = true;
 
     uint32_t eax, ebx, ecx, edx;
     if (!cpuid(1, 0, &eax, &ebx, &ecx, &edx) || !(edx & (1 << 16))) {
         return false;
     }
 
-    ok = ((rdmsr(IA32_PAT_MSR) >> 16) & 0xff) == PAT_TYPE_UCM;
-    return ok;
+    uint64_t pat = rdmsr(IA32_PAT_MSR);
+
+    for (int i = 0; i < 8; i++) {
+        if (((pat >> (i * 8)) & 0xff) == PAT_TYPE_WC) {
+            wc_pat_index = i;
+            return true;
+        }
+    }
+
+    uint8_t used = scan_used_pat_indices();
+
+    int slot = -1;
+    for (int i = 4; i < 8; i++) {
+        if (!(used & (1 << i))) {
+            slot = i;
+            break;
+        }
+    }
+    if (slot < 0) {
+        for (int i = 0; i < 4; i++) {
+            if (!(used & (1 << i))) {
+                slot = i;
+                break;
+            }
+        }
+    }
+    if (slot < 0) {
+        return false;
+    }
+
+    saved_pat = pat;
+    pat_modified = true;
+
+    pat = (pat & ~((uint64_t)0xff << (slot * 8)))
+        | ((uint64_t)PAT_TYPE_WC << (slot * 8));
+
+    uint64_t old_cr0;
+    cache_off(&old_cr0);
+    wrmsr(IA32_PAT_MSR, pat);
+    cache_on(old_cr0);
+
+    wc_pat_index = slot;
+    return true;
 }
 
-static uint64_t *walk_to_leaf(uint64_t addr, uint64_t *pg_size, bool *large) {
-    uint64_t cr3;
-    asm volatile ("mov %%cr3, %0" : "=r"(cr3));
+static uint64_t pte_set_pat(uint64_t e, int idx, bool leaf4k) {
+    uint64_t patbit = leaf4k ? PTE_PAT_4K : PTE_PAT_BIG;
+    e &= ~(PTE_PWT | PTE_PCD | patbit);
+    if (idx & 1) e |= PTE_PWT;
+    if (idx & 2) e |= PTE_PCD;
+    if (idx & 4) e |= patbit;
+    return e;
+}
+
+// Children inherit the parent mapping so memory sharing the leaf keeps its type.
+static uint64_t *split_leaf(uint64_t e, int lvl) {
+    uint64_t leaf_sz = (uint64_t)1 << ((lvl - 1) * 9 + 12);
+    uint64_t phys_base = e & PT_ADDR_MASK & ~(leaf_sz - 1);
+    int idx = pte_pat_index(e, false);
+    uint64_t flags = e & (PTE_P | PTE_RW | PTE_US | PTE_NX);
+
+    int child_lvl = lvl - 1;
+    uint64_t child_sz = (uint64_t)1 << ((child_lvl - 1) * 9 + 12);
+    bool child_4k = child_lvl == 1;
 
-    uint64_t *table = (uint64_t *)(cr3 & PT_ADDR_MASK);
+    uint64_t *t = ext_mem_alloc(0x1000);
+    for (int i = 0; i < 512; i++) {
+        uint64_t c = (phys_base + (uint64_t)i * child_sz) | flags;
+        if (!child_4k) {
+            c |= PTE_PS;
+        }
+        t[i] = pte_set_pat(c, idx, child_4k);
+    }
+    return t;
+}
 
-    int lvl = la57_enabled() ? 5 : 4;
+// pristine: inside firmware tables (saved); tables we allocate are not.
+static void wc_walk(uint64_t *table, int lvl, uint64_t tbl_va,
+                    uint64_t base, uint64_t end, bool pristine) {
+    uint64_t step = (uint64_t)1 << ((lvl - 1) * 9 + 12);
+
+    for (size_t i = 0; i < 512; i++) {
+        uint64_t va = tbl_va + (uint64_t)i * step;
+        if (va >= end) {
+            break;
+        }
+        if (va + step <= base) {
+            continue;
+        }
 
-    for (; lvl >= 1; lvl--) {
-        int shift = (lvl - 1) * 9 + 12;
-        size_t idx = (addr >> shift) & 0x1ff;
-        uint64_t e = table[idx];
+        uint64_t *e = &table[i];
+        bool present = !!(*e & PTE_P);
+        bool is_leaf = (lvl == 1) || (present && lvl <= 3 && (*e & PTE_PS));
+        bool fully = va >= base && va + step <= end;
 
-        if (!(e & PTE_P)) {
-            return NULL;
+        if (fully && lvl <= 3) {
+            uint64_t leaf;
+            if (present && is_leaf) {
+                leaf = (*e & PT_ADDR_MASK & ~(step - 1))
+                     | (*e & (PTE_P | PTE_RW | PTE_US | PTE_NX));
+            } else {
+                leaf = va | PTE_P | PTE_RW;
+            }
+            if (lvl >= 2) {
+                leaf |= PTE_PS;
+            }
+            if (pristine && !save_pte(e)) {
+                continue;
+            }
+            *e = pte_set_pat(leaf, wc_pat_index, lvl == 1);
+            continue;
         }
 
-        bool is_leaf = (lvl == 1) || ((lvl == 2 || lvl == 3) && (e & PTE_PS));
-        if (is_leaf) {
-            *pg_size = (uint64_t)1 << shift;
-            *large = (lvl != 1);
-            return &table[idx];
+        if (present && !is_leaf) {
+            wc_walk((uint64_t *)(*e & PT_ADDR_MASK), lvl - 1, va,
+                    base, end, pristine);
+            continue;
         }
 
-        table = (uint64_t *)(e & PT_ADDR_MASK);
+        if (pristine && !save_pte(e)) {
+            continue;
+        }
+        uint64_t *child;
+        if (present) {
+            child = split_leaf(*e, lvl);
+        } else {
+            child = ext_mem_alloc(0x1000);
+        }
+        *e = (uint64_t)child | PTE_P | PTE_RW | PTE_US;
+        wc_walk(child, lvl - 1, va, base, end, false);
     }
-    return NULL;
 }
 
-void efi_pt_set_fb_uc_minus(uint64_t base, uint64_t size) {
-    if (size == 0 || !pat_slot2_is_ucm()) {
+void efi_pt_set_fb_wc(uint64_t base, uint64_t size) {
+    if (size == 0) {
         return;
     }
 
-    // Clear CR0.WP so supervisor writes hit any firmware PTEs mapped R/O.
-    uint64_t old_cr0;
-    asm volatile ("mov %%cr0, %0" : "=r"(old_cr0));
-    asm volatile ("mov %0, %%cr0" :: "r"(old_cr0 & ~((uint64_t)1 << 16)) : "memory");
+    if (saved_pte_ptr == NULL) {
+        saved_pte_ptr = ext_mem_alloc(SAVED_PTES_MAX * sizeof(uint64_t *));
+        saved_pte_val = ext_mem_alloc(SAVED_PTES_MAX * sizeof(uint64_t));
+    }
+
+    asm volatile ("cli");
+
+    if (!ensure_wc_pat_slot()) {
+        goto out;
+    }
 
     uint64_t end = (base + size + 0xfff) & ~(uint64_t)0xfff;
     base &= ~(uint64_t)0xfff;
 
-    while (base < end) {
-        uint64_t pg;
-        bool large;
-        uint64_t *entry = walk_to_leaf(base, &pg, &large);
-        if (entry == NULL) {
-            base += 0x1000;
-            continue;
-        }
+    uint64_t cr3;
+    asm volatile ("mov %%cr3, %0" : "=r"(cr3));
+    uint64_t *top = (uint64_t *)(cr3 & PT_ADDR_MASK);
+    int levels = la57_enabled() ? 5 : 4;
 
-        uint64_t mask = large ? UCM_MASK_BIG : UCM_MASK_4K;
-        *entry = (*entry & ~mask) | UCM_VALUE;
+    uint64_t old_cr0;
+    wp_off(&old_cr0);
+    wc_walk(top, levels, 0, base, end, true);
+    wp_on(old_cr0);
 
-        invlpg(base);
-        base = (base & ~(pg - 1)) + pg;
+out:
+    asm volatile ("sti");
+}
+
+void efi_pt_restore(void) {
+    if (saved_pte_i == 0 && !pat_modified) {
+        goto out;
     }
 
-    asm volatile ("mov %0, %%cr0" :: "r"(old_cr0) : "memory");
+    asm volatile ("cli");
+
+    if (saved_pte_i != 0) {
+        uint64_t old_cr0;
+        wp_off(&old_cr0);
+        for (size_t i = saved_pte_i; i-- > 0;) {
+            *saved_pte_ptr[i] = saved_pte_val[i];
+        }
+        wp_on(old_cr0);
+    }
+
+    if (pat_modified) {
+        uint64_t old_cr0;
+        cache_off(&old_cr0);
+        wrmsr(IA32_PAT_MSR, saved_pat);
+        cache_on(old_cr0);
+    }
+
+    asm volatile ("sti");
+
+    saved_pte_i = 0;
+    pat_modified = false;
+    wc_pat_index = -1;
+
+out:
+    if (saved_pte_ptr != NULL) {
+        pmm_free(saved_pte_ptr, SAVED_PTES_MAX * sizeof(uint64_t *));
+        pmm_free(saved_pte_val, SAVED_PTES_MAX * sizeof(uint64_t));
+        saved_pte_ptr = NULL;
+        saved_pte_val = NULL;
+    }
 }
 
 #endif
diff --git a/common/mm/efi_pt.h b/common/mm/efi_pt.h
index ee6c57f6..8732aa45 100644
--- a/common/mm/efi_pt.h
+++ b/common/mm/efi_pt.h
@@ -5,7 +5,8 @@
 
 #if defined (__x86_64__) && defined (UEFI)
 
-void efi_pt_set_fb_uc_minus(uint64_t base, uint64_t size);
+void efi_pt_set_fb_wc(uint64_t base, uint64_t size);
+void efi_pt_restore(void);
 
 #endif
 
diff --git a/common/sys/cpu.h b/common/sys/cpu.h
index 6dcb385c..a91ed5e2 100644
--- a/common/sys/cpu.h
+++ b/common/sys/cpu.h
@@ -160,10 +160,6 @@ static inline uint64_t rdtsc(void) {
     return ((uint64_t)edx << 32) | eax;
 }
 
-static inline void invlpg(uintptr_t va) {
-    asm volatile ("invlpg (%0)" :: "r"(va) : "memory");
-}
-
 static inline uint64_t tsc_freq_arch(void) {
     uint32_t eax, ebx, ecx, edx;
     if (!cpuid(0x15, 0, &eax, &ebx, &ecx, &edx))
tab: 248 wrap: offon