// SPDX-License-Identifier: GPL-2.01/*2* Copyright (C) 1995 Linus Torvalds3* Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.4* Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar5*/6#include <linux/sched.h> /* test_thread_flag(), ... */7#include <linux/sched/task_stack.h> /* task_stack_*(), ... */8#include <linux/kdebug.h> /* oops_begin/end, ... */9#include <linux/memblock.h> /* max_low_pfn */10#include <linux/kfence.h> /* kfence_handle_page_fault */11#include <linux/kprobes.h> /* NOKPROBE_SYMBOL, ... */12#include <linux/mmiotrace.h> /* kmmio_handler, ... */13#include <linux/perf_event.h> /* perf_sw_event */14#include <linux/hugetlb.h> /* hstate_index_to_shift */15#include <linux/context_tracking.h> /* exception_enter(), ... */16#include <linux/uaccess.h> /* faulthandler_disabled() */17#include <linux/efi.h> /* efi_crash_gracefully_on_page_fault()*/18#include <linux/mm_types.h>19#include <linux/mm.h> /* find_and_lock_vma() */20#include <linux/vmalloc.h>2122#include <asm/cpufeature.h> /* boot_cpu_has, ... */23#include <asm/traps.h> /* dotraplinkage, ... */24#include <asm/fixmap.h> /* VSYSCALL_ADDR */25#include <asm/vsyscall.h> /* emulate_vsyscall */26#include <asm/vm86.h> /* struct vm86 */27#include <asm/mmu_context.h> /* vma_pkey() */28#include <asm/efi.h> /* efi_crash_gracefully_on_page_fault()*/29#include <asm/desc.h> /* store_idt(), ... */30#include <asm/cpu_entry_area.h> /* exception stack */31#include <asm/pgtable_areas.h> /* VMALLOC_START, ... */32#include <asm/kvm_para.h> /* kvm_handle_async_pf */33#include <asm/vdso.h> /* fixup_vdso_exception() */34#include <asm/irq_stack.h>35#include <asm/fred.h>36#include <asm/sev.h> /* snp_dump_hva_rmpentry() */3738#define CREATE_TRACE_POINTS39#include <trace/events/exceptions.h>4041/*42* Returns 0 if mmiotrace is disabled, or if the fault is not43* handled by mmiotrace:44*/45static nokprobe_inline int46kmmio_fault(struct pt_regs *regs, unsigned long addr)47{48if (unlikely(is_kmmio_active()))49if (kmmio_handler(regs, addr) == 1)50return -1;51return 0;52}5354/*55* Prefetch quirks:56*57* 32-bit mode:58*59* Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.60* Check that here and ignore it. This is AMD erratum #91.61*62* 64-bit mode:63*64* Sometimes the CPU reports invalid exceptions on prefetch.65* Check that here and ignore it.66*67* Opcode checker based on code by Richard Brunner.68*/69static inline int70check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,71unsigned char opcode, int *prefetch)72{73unsigned char instr_hi = opcode & 0xf0;74unsigned char instr_lo = opcode & 0x0f;7576switch (instr_hi) {77case 0x20:78case 0x30:79/*80* Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.81* In X86_64 long mode, the CPU will signal invalid82* opcode if some of these prefixes are present so83* X86_64 will never get here anyway84*/85return ((instr_lo & 7) == 0x6);86#ifdef CONFIG_X86_6487case 0x40:88/*89* In 64-bit mode 0x40..0x4F are valid REX prefixes90*/91return (!user_mode(regs) || user_64bit_mode(regs));92#endif93case 0x60:94/* 0x64 thru 0x67 are valid prefixes in all modes. */95return (instr_lo & 0xC) == 0x4;96case 0xF0:97/* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */98return !instr_lo || (instr_lo>>1) == 1;99case 0x00:100/* Prefetch instruction is 0x0F0D or 0x0F18 */101if (get_kernel_nofault(opcode, instr))102return 0;103104*prefetch = (instr_lo == 0xF) &&105(opcode == 0x0D || opcode == 0x18);106return 0;107default:108return 0;109}110}111112static bool is_amd_k8_pre_npt(void)113{114struct cpuinfo_x86 *c = &boot_cpu_data;115116return unlikely(IS_ENABLED(CONFIG_CPU_SUP_AMD) &&117c->x86_vendor == X86_VENDOR_AMD &&118c->x86 == 0xf && c->x86_model < 0x40);119}120121static int122is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)123{124unsigned char *max_instr;125unsigned char *instr;126int prefetch = 0;127128/* Erratum #91 affects AMD K8, pre-NPT CPUs */129if (!is_amd_k8_pre_npt())130return 0;131132/*133* If it was a exec (instruction fetch) fault on NX page, then134* do not ignore the fault:135*/136if (error_code & X86_PF_INSTR)137return 0;138139instr = (void *)convert_ip_to_linear(current, regs);140max_instr = instr + 15;141142/*143* This code has historically always bailed out if IP points to a144* not-present page (e.g. due to a race). No one has ever145* complained about this.146*/147pagefault_disable();148149while (instr < max_instr) {150unsigned char opcode;151152if (user_mode(regs)) {153if (get_user(opcode, (unsigned char __user *) instr))154break;155} else {156if (get_kernel_nofault(opcode, instr))157break;158}159160instr++;161162if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))163break;164}165166pagefault_enable();167return prefetch;168}169170DEFINE_SPINLOCK(pgd_lock);171LIST_HEAD(pgd_list);172173#ifdef CONFIG_X86_32174static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)175{176unsigned index = pgd_index(address);177pgd_t *pgd_k;178p4d_t *p4d, *p4d_k;179pud_t *pud, *pud_k;180pmd_t *pmd, *pmd_k;181182pgd += index;183pgd_k = init_mm.pgd + index;184185if (!pgd_present(*pgd_k))186return NULL;187188/*189* set_pgd(pgd, *pgd_k); here would be useless on PAE190* and redundant with the set_pmd() on non-PAE. As would191* set_p4d/set_pud.192*/193p4d = p4d_offset(pgd, address);194p4d_k = p4d_offset(pgd_k, address);195if (!p4d_present(*p4d_k))196return NULL;197198pud = pud_offset(p4d, address);199pud_k = pud_offset(p4d_k, address);200if (!pud_present(*pud_k))201return NULL;202203pmd = pmd_offset(pud, address);204pmd_k = pmd_offset(pud_k, address);205206if (pmd_present(*pmd) != pmd_present(*pmd_k))207set_pmd(pmd, *pmd_k);208209if (!pmd_present(*pmd_k))210return NULL;211else212BUG_ON(pmd_pfn(*pmd) != pmd_pfn(*pmd_k));213214return pmd_k;215}216217/*218* Handle a fault on the vmalloc or module mapping area219*220* This is needed because there is a race condition between the time221* when the vmalloc mapping code updates the PMD to the point in time222* where it synchronizes this update with the other page-tables in the223* system.224*225* In this race window another thread/CPU can map an area on the same226* PMD, finds it already present and does not synchronize it with the227* rest of the system yet. As a result v[mz]alloc might return areas228* which are not mapped in every page-table in the system, causing an229* unhandled page-fault when they are accessed.230*/231static noinline int vmalloc_fault(unsigned long address)232{233unsigned long pgd_paddr;234pmd_t *pmd_k;235pte_t *pte_k;236237/* Make sure we are in vmalloc area: */238if (!(address >= VMALLOC_START && address < VMALLOC_END))239return -1;240241/*242* Synchronize this task's top level page-table243* with the 'reference' page table.244*245* Do _not_ use "current" here. We might be inside246* an interrupt in the middle of a task switch..247*/248pgd_paddr = read_cr3_pa();249pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);250if (!pmd_k)251return -1;252253if (pmd_leaf(*pmd_k))254return 0;255256pte_k = pte_offset_kernel(pmd_k, address);257if (!pte_present(*pte_k))258return -1;259260return 0;261}262NOKPROBE_SYMBOL(vmalloc_fault);263264void arch_sync_kernel_mappings(unsigned long start, unsigned long end)265{266unsigned long addr;267268for (addr = start & PMD_MASK;269addr >= TASK_SIZE_MAX && addr < VMALLOC_END;270addr += PMD_SIZE) {271struct page *page;272273spin_lock(&pgd_lock);274list_for_each_entry(page, &pgd_list, lru) {275spinlock_t *pgt_lock;276277/* the pgt_lock only for Xen */278pgt_lock = &pgd_page_get_mm(page)->page_table_lock;279280spin_lock(pgt_lock);281vmalloc_sync_one(page_address(page), addr);282spin_unlock(pgt_lock);283}284spin_unlock(&pgd_lock);285}286}287288static bool low_pfn(unsigned long pfn)289{290return pfn < max_low_pfn;291}292293static void dump_pagetable(unsigned long address)294{295pgd_t *base = __va(read_cr3_pa());296pgd_t *pgd = &base[pgd_index(address)];297p4d_t *p4d;298pud_t *pud;299pmd_t *pmd;300pte_t *pte;301302#ifdef CONFIG_X86_PAE303pr_info("*pdpt = %016Lx ", pgd_val(*pgd));304if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))305goto out;306#define pr_pde pr_cont307#else308#define pr_pde pr_info309#endif310p4d = p4d_offset(pgd, address);311pud = pud_offset(p4d, address);312pmd = pmd_offset(pud, address);313pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));314#undef pr_pde315316/*317* We must not directly access the pte in the highpte318* case if the page table is located in highmem.319* And let's rather not kmap-atomic the pte, just in case320* it's allocated already:321*/322if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_leaf(*pmd))323goto out;324325pte = pte_offset_kernel(pmd, address);326pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));327out:328pr_cont("\n");329}330331#else /* CONFIG_X86_64: */332333#ifdef CONFIG_CPU_SUP_AMD334static const char errata93_warning[] =335KERN_ERR336"******* Your BIOS seems to not contain a fix for K8 errata #93\n"337"******* Working around it, but it may cause SEGVs or burn power.\n"338"******* Please consider a BIOS update.\n"339"******* Disabling USB legacy in the BIOS may also help.\n";340#endif341342static int bad_address(void *p)343{344unsigned long dummy;345346return get_kernel_nofault(dummy, (unsigned long *)p);347}348349static void dump_pagetable(unsigned long address)350{351pgd_t *base = __va(read_cr3_pa());352pgd_t *pgd = base + pgd_index(address);353p4d_t *p4d;354pud_t *pud;355pmd_t *pmd;356pte_t *pte;357358if (bad_address(pgd))359goto bad;360361pr_info("PGD %lx ", pgd_val(*pgd));362363if (!pgd_present(*pgd))364goto out;365366p4d = p4d_offset(pgd, address);367if (bad_address(p4d))368goto bad;369370pr_cont("P4D %lx ", p4d_val(*p4d));371if (!p4d_present(*p4d) || p4d_leaf(*p4d))372goto out;373374pud = pud_offset(p4d, address);375if (bad_address(pud))376goto bad;377378pr_cont("PUD %lx ", pud_val(*pud));379if (!pud_present(*pud) || pud_leaf(*pud))380goto out;381382pmd = pmd_offset(pud, address);383if (bad_address(pmd))384goto bad;385386pr_cont("PMD %lx ", pmd_val(*pmd));387if (!pmd_present(*pmd) || pmd_leaf(*pmd))388goto out;389390pte = pte_offset_kernel(pmd, address);391if (bad_address(pte))392goto bad;393394pr_cont("PTE %lx", pte_val(*pte));395out:396pr_cont("\n");397return;398bad:399pr_info("BAD\n");400}401402#endif /* CONFIG_X86_64 */403404/*405* Workaround for K8 erratum #93 & buggy BIOS.406*407* BIOS SMM functions are required to use a specific workaround408* to avoid corruption of the 64bit RIP register on C stepping K8.409*410* A lot of BIOS that didn't get tested properly miss this.411*412* The OS sees this as a page fault with the upper 32bits of RIP cleared.413* Try to work around it here.414*415* Note we only handle faults in kernel here.416* Does nothing on 32-bit.417*/418static int is_errata93(struct pt_regs *regs, unsigned long address)419{420#if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)421if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD422|| boot_cpu_data.x86 != 0xf)423return 0;424425if (user_mode(regs))426return 0;427428if (address != regs->ip)429return 0;430431if ((address >> 32) != 0)432return 0;433434address |= 0xffffffffUL << 32;435if ((address >= (u64)_stext && address <= (u64)_etext) ||436(address >= MODULES_VADDR && address <= MODULES_END)) {437printk_once(errata93_warning);438regs->ip = address;439return 1;440}441#endif442return 0;443}444445/*446* Work around K8 erratum #100 K8 in compat mode occasionally jumps447* to illegal addresses >4GB.448*449* We catch this in the page fault handler because these addresses450* are not reachable. Just detect this case and return. Any code451* segment in LDT is compatibility mode.452*/453static int is_errata100(struct pt_regs *regs, unsigned long address)454{455#ifdef CONFIG_X86_64456if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))457return 1;458#endif459return 0;460}461462/* Pentium F0 0F C7 C8 bug workaround: */463static int is_f00f_bug(struct pt_regs *regs, unsigned long error_code,464unsigned long address)465{466#ifdef CONFIG_X86_F00F_BUG467if (boot_cpu_has_bug(X86_BUG_F00F) && !(error_code & X86_PF_USER) &&468idt_is_f00f_address(address)) {469handle_invalid_op(regs);470return 1;471}472#endif473return 0;474}475476static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index)477{478u32 offset = (index >> 3) * sizeof(struct desc_struct);479unsigned long addr;480struct ldttss_desc desc;481482if (index == 0) {483pr_alert("%s: NULL\n", name);484return;485}486487if (offset + sizeof(struct ldttss_desc) >= gdt->size) {488pr_alert("%s: 0x%hx -- out of bounds\n", name, index);489return;490}491492if (copy_from_kernel_nofault(&desc, (void *)(gdt->address + offset),493sizeof(struct ldttss_desc))) {494pr_alert("%s: 0x%hx -- GDT entry is not readable\n",495name, index);496return;497}498499addr = desc.base0 | (desc.base1 << 16) | ((unsigned long)desc.base2 << 24);500#ifdef CONFIG_X86_64501addr |= ((u64)desc.base3 << 32);502#endif503pr_alert("%s: 0x%hx -- base=0x%lx limit=0x%x\n",504name, index, addr, (desc.limit0 | (desc.limit1 << 16)));505}506507static void508show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long address)509{510if (!oops_may_print())511return;512513if (error_code & X86_PF_INSTR) {514unsigned int level;515bool nx, rw;516pgd_t *pgd;517pte_t *pte;518519pgd = __va(read_cr3_pa());520pgd += pgd_index(address);521522pte = lookup_address_in_pgd_attr(pgd, address, &level, &nx, &rw);523524if (pte && pte_present(*pte) && (!pte_exec(*pte) || nx))525pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",526from_kuid(&init_user_ns, current_uid()));527if (pte && pte_present(*pte) && pte_exec(*pte) && !nx &&528(pgd_flags(*pgd) & _PAGE_USER) &&529(__read_cr4() & X86_CR4_SMEP))530pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",531from_kuid(&init_user_ns, current_uid()));532}533534if (address < PAGE_SIZE && !user_mode(regs))535pr_alert("BUG: kernel NULL pointer dereference, address: %px\n",536(void *)address);537else538pr_alert("BUG: unable to handle page fault for address: %px\n",539(void *)address);540541pr_alert("#PF: %s %s in %s mode\n",542(error_code & X86_PF_USER) ? "user" : "supervisor",543(error_code & X86_PF_INSTR) ? "instruction fetch" :544(error_code & X86_PF_WRITE) ? "write access" :545"read access",546user_mode(regs) ? "user" : "kernel");547pr_alert("#PF: error_code(0x%04lx) - %s\n", error_code,548!(error_code & X86_PF_PROT) ? "not-present page" :549(error_code & X86_PF_RSVD) ? "reserved bit violation" :550(error_code & X86_PF_PK) ? "protection keys violation" :551(error_code & X86_PF_RMP) ? "RMP violation" :552"permissions violation");553554if (!(error_code & X86_PF_USER) && user_mode(regs)) {555struct desc_ptr idt, gdt;556u16 ldtr, tr;557558/*559* This can happen for quite a few reasons. The more obvious560* ones are faults accessing the GDT, or LDT. Perhaps561* surprisingly, if the CPU tries to deliver a benign or562* contributory exception from user code and gets a page fault563* during delivery, the page fault can be delivered as though564* it originated directly from user code. This could happen565* due to wrong permissions on the IDT, GDT, LDT, TSS, or566* kernel or IST stack.567*/568store_idt(&idt);569570/* Usable even on Xen PV -- it's just slow. */571native_store_gdt(&gdt);572573pr_alert("IDT: 0x%lx (limit=0x%hx) GDT: 0x%lx (limit=0x%hx)\n",574idt.address, idt.size, gdt.address, gdt.size);575576store_ldt(ldtr);577show_ldttss(&gdt, "LDTR", ldtr);578579store_tr(tr);580show_ldttss(&gdt, "TR", tr);581}582583dump_pagetable(address);584585if (error_code & X86_PF_RMP)586snp_dump_hva_rmpentry(address);587}588589static noinline void590pgtable_bad(struct pt_regs *regs, unsigned long error_code,591unsigned long address)592{593struct task_struct *tsk;594unsigned long flags;595int sig;596597flags = oops_begin();598tsk = current;599sig = SIGKILL;600601printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",602tsk->comm, address);603dump_pagetable(address);604605if (__die("Bad pagetable", regs, error_code))606sig = 0;607608oops_end(flags, regs, sig);609}610611static void sanitize_error_code(unsigned long address,612unsigned long *error_code)613{614/*615* To avoid leaking information about the kernel page616* table layout, pretend that user-mode accesses to617* kernel addresses are always protection faults.618*619* NB: This means that failed vsyscalls with vsyscall=none620* will have the PROT bit. This doesn't leak any621* information and does not appear to cause any problems.622*/623if (address >= TASK_SIZE_MAX)624*error_code |= X86_PF_PROT;625}626627static void set_signal_archinfo(unsigned long address,628unsigned long error_code)629{630struct task_struct *tsk = current;631632tsk->thread.trap_nr = X86_TRAP_PF;633tsk->thread.error_code = error_code | X86_PF_USER;634tsk->thread.cr2 = address;635}636637static noinline void638page_fault_oops(struct pt_regs *regs, unsigned long error_code,639unsigned long address)640{641#ifdef CONFIG_VMAP_STACK642struct stack_info info;643#endif644unsigned long flags;645int sig;646647if (user_mode(regs)) {648/*649* Implicit kernel access from user mode? Skip the stack650* overflow and EFI special cases.651*/652goto oops;653}654655#ifdef CONFIG_VMAP_STACK656/*657* Stack overflow? During boot, we can fault near the initial658* stack in the direct map, but that's not an overflow -- check659* that we're in vmalloc space to avoid this.660*/661if (is_vmalloc_addr((void *)address) &&662get_stack_guard_info((void *)address, &info)) {663/*664* We're likely to be running with very little stack space665* left. It's plausible that we'd hit this condition but666* double-fault even before we get this far, in which case667* we're fine: the double-fault handler will deal with it.668*669* We don't want to make it all the way into the oops code670* and then double-fault, though, because we're likely to671* break the console driver and lose most of the stack dump.672*/673call_on_stack(__this_cpu_ist_top_va(DF) - sizeof(void*),674handle_stack_overflow,675ASM_CALL_ARG3,676, [arg1] "r" (regs), [arg2] "r" (address), [arg3] "r" (&info));677678BUG();679}680#endif681682/*683* Buggy firmware could access regions which might page fault. If684* this happens, EFI has a special OOPS path that will try to685* avoid hanging the system.686*/687if (IS_ENABLED(CONFIG_EFI))688efi_crash_gracefully_on_page_fault(address);689690/* Only not-present faults should be handled by KFENCE. */691if (!(error_code & X86_PF_PROT) &&692kfence_handle_page_fault(address, error_code & X86_PF_WRITE, regs))693return;694695oops:696/*697* Oops. The kernel tried to access some bad page. We'll have to698* terminate things with extreme prejudice:699*/700flags = oops_begin();701702show_fault_oops(regs, error_code, address);703704if (task_stack_end_corrupted(current))705printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");706707sig = SIGKILL;708if (__die("Oops", regs, error_code))709sig = 0;710711/* Executive summary in case the body of the oops scrolled away */712printk(KERN_DEFAULT "CR2: %016lx\n", address);713714oops_end(flags, regs, sig);715}716717static noinline void718kernelmode_fixup_or_oops(struct pt_regs *regs, unsigned long error_code,719unsigned long address, int signal, int si_code,720u32 pkey)721{722WARN_ON_ONCE(user_mode(regs));723724/* Are we prepared to handle this kernel fault? */725if (fixup_exception(regs, X86_TRAP_PF, error_code, address))726return;727728/*729* AMD erratum #91 manifests as a spurious page fault on a PREFETCH730* instruction.731*/732if (is_prefetch(regs, error_code, address))733return;734735page_fault_oops(regs, error_code, address);736}737738/*739* Print out info about fatal segfaults, if the show_unhandled_signals740* sysctl is set:741*/742static inline void743show_signal_msg(struct pt_regs *regs, unsigned long error_code,744unsigned long address, struct task_struct *tsk)745{746const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;747/* This is a racy snapshot, but it's better than nothing. */748int cpu = raw_smp_processor_id();749750if (!unhandled_signal(tsk, SIGSEGV))751return;752753if (!printk_ratelimit())754return;755756printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",757loglvl, tsk->comm, task_pid_nr(tsk), address,758(void *)regs->ip, (void *)regs->sp, error_code);759760print_vma_addr(KERN_CONT " in ", regs->ip);761762/*763* Dump the likely CPU where the fatal segfault happened.764* This can help identify faulty hardware.765*/766printk(KERN_CONT " likely on CPU %d (core %d, socket %d)", cpu,767topology_core_id(cpu), topology_physical_package_id(cpu));768769770printk(KERN_CONT "\n");771772show_opcodes(regs, loglvl);773}774775static void776__bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,777unsigned long address, u32 pkey, int si_code)778{779struct task_struct *tsk = current;780781if (!user_mode(regs)) {782kernelmode_fixup_or_oops(regs, error_code, address,783SIGSEGV, si_code, pkey);784return;785}786787if (!(error_code & X86_PF_USER)) {788/* Implicit user access to kernel memory -- just oops */789page_fault_oops(regs, error_code, address);790return;791}792793/*794* User mode accesses just cause a SIGSEGV.795* It's possible to have interrupts off here:796*/797local_irq_enable();798799/*800* Valid to do another page fault here because this one came801* from user space:802*/803if (is_prefetch(regs, error_code, address))804return;805806if (is_errata100(regs, address))807return;808809sanitize_error_code(address, &error_code);810811if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))812return;813814if (likely(show_unhandled_signals))815show_signal_msg(regs, error_code, address, tsk);816817set_signal_archinfo(address, error_code);818819if (si_code == SEGV_PKUERR)820force_sig_pkuerr((void __user *)address, pkey);821else822force_sig_fault(SIGSEGV, si_code, (void __user *)address);823824local_irq_disable();825}826827static noinline void828bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,829unsigned long address)830{831__bad_area_nosemaphore(regs, error_code, address, 0, SEGV_MAPERR);832}833834static void835__bad_area(struct pt_regs *regs, unsigned long error_code,836unsigned long address, struct mm_struct *mm,837struct vm_area_struct *vma, u32 pkey, int si_code)838{839/*840* Something tried to access memory that isn't in our memory map..841* Fix it, but check if it's kernel or user first..842*/843if (mm)844mmap_read_unlock(mm);845else846vma_end_read(vma);847848__bad_area_nosemaphore(regs, error_code, address, pkey, si_code);849}850851static inline bool bad_area_access_from_pkeys(unsigned long error_code,852struct vm_area_struct *vma)853{854/* This code is always called on the current mm */855bool foreign = false;856857if (!cpu_feature_enabled(X86_FEATURE_OSPKE))858return false;859if (error_code & X86_PF_PK)860return true;861/* this checks permission keys on the VMA: */862if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),863(error_code & X86_PF_INSTR), foreign))864return true;865return false;866}867868static noinline void869bad_area_access_error(struct pt_regs *regs, unsigned long error_code,870unsigned long address, struct mm_struct *mm,871struct vm_area_struct *vma)872{873/*874* This OSPKE check is not strictly necessary at runtime.875* But, doing it this way allows compiler optimizations876* if pkeys are compiled out.877*/878if (bad_area_access_from_pkeys(error_code, vma)) {879/*880* A protection key fault means that the PKRU value did not allow881* access to some PTE. Userspace can figure out what PKRU was882* from the XSAVE state. This function captures the pkey from883* the vma and passes it to userspace so userspace can discover884* which protection key was set on the PTE.885*886* If we get here, we know that the hardware signaled a X86_PF_PK887* fault and that there was a VMA once we got in the fault888* handler. It does *not* guarantee that the VMA we find here889* was the one that we faulted on.890*891* 1. T1 : mprotect_key(foo, PAGE_SIZE, pkey=4);892* 2. T1 : set PKRU to deny access to pkey=4, touches page893* 3. T1 : faults...894* 4. T2: mprotect_key(foo, PAGE_SIZE, pkey=5);895* 5. T1 : enters fault handler, takes mmap_lock, etc...896* 6. T1 : reaches here, sees vma_pkey(vma)=5, when we really897* faulted on a pte with its pkey=4.898*/899u32 pkey = vma_pkey(vma);900901__bad_area(regs, error_code, address, mm, vma, pkey, SEGV_PKUERR);902} else {903__bad_area(regs, error_code, address, mm, vma, 0, SEGV_ACCERR);904}905}906907static void908do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,909vm_fault_t fault)910{911/* Kernel mode? Handle exceptions or die: */912if (!user_mode(regs)) {913kernelmode_fixup_or_oops(regs, error_code, address,914SIGBUS, BUS_ADRERR, ARCH_DEFAULT_PKEY);915return;916}917918/* User-space => ok to do another page fault: */919if (is_prefetch(regs, error_code, address))920return;921922sanitize_error_code(address, &error_code);923924if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))925return;926927set_signal_archinfo(address, error_code);928929#ifdef CONFIG_MEMORY_FAILURE930if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {931struct task_struct *tsk = current;932unsigned lsb = 0;933934pr_err(935"MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",936tsk->comm, tsk->pid, address);937if (fault & VM_FAULT_HWPOISON_LARGE)938lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));939if (fault & VM_FAULT_HWPOISON)940lsb = PAGE_SHIFT;941force_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb);942return;943}944#endif945force_sig_fault(SIGBUS, BUS_ADRERR, (void __user *)address);946}947948static int spurious_kernel_fault_check(unsigned long error_code, pte_t *pte)949{950if ((error_code & X86_PF_WRITE) && !pte_write(*pte))951return 0;952953if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))954return 0;955956return 1;957}958959/*960* Handle a spurious fault caused by a stale TLB entry.961*962* This allows us to lazily refresh the TLB when increasing the963* permissions of a kernel page (RO -> RW or NX -> X). Doing it964* eagerly is very expensive since that implies doing a full965* cross-processor TLB flush, even if no stale TLB entries exist966* on other processors.967*968* Spurious faults may only occur if the TLB contains an entry with969* fewer permission than the page table entry. Non-present (P = 0)970* and reserved bit (R = 1) faults are never spurious.971*972* There are no security implications to leaving a stale TLB when973* increasing the permissions on a page.974*975* Returns non-zero if a spurious fault was handled, zero otherwise.976*977* See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3978* (Optional Invalidation).979*/980static noinline int981spurious_kernel_fault(unsigned long error_code, unsigned long address)982{983pgd_t *pgd;984p4d_t *p4d;985pud_t *pud;986pmd_t *pmd;987pte_t *pte;988int ret;989990/*991* Only writes to RO or instruction fetches from NX may cause992* spurious faults.993*994* These could be from user or supervisor accesses but the TLB995* is only lazily flushed after a kernel mapping protection996* change, so user accesses are not expected to cause spurious997* faults.998*/999if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&1000error_code != (X86_PF_INSTR | X86_PF_PROT))1001return 0;10021003pgd = init_mm.pgd + pgd_index(address);1004if (!pgd_present(*pgd))1005return 0;10061007p4d = p4d_offset(pgd, address);1008if (!p4d_present(*p4d))1009return 0;10101011if (p4d_leaf(*p4d))1012return spurious_kernel_fault_check(error_code, (pte_t *) p4d);10131014pud = pud_offset(p4d, address);1015if (!pud_present(*pud))1016return 0;10171018if (pud_leaf(*pud))1019return spurious_kernel_fault_check(error_code, (pte_t *) pud);10201021pmd = pmd_offset(pud, address);1022if (!pmd_present(*pmd))1023return 0;10241025if (pmd_leaf(*pmd))1026return spurious_kernel_fault_check(error_code, (pte_t *) pmd);10271028pte = pte_offset_kernel(pmd, address);1029if (!pte_present(*pte))1030return 0;10311032ret = spurious_kernel_fault_check(error_code, pte);1033if (!ret)1034return 0;10351036/*1037* Make sure we have permissions in PMD.1038* If not, then there's a bug in the page tables:1039*/1040ret = spurious_kernel_fault_check(error_code, (pte_t *) pmd);1041WARN_ONCE(!ret, "PMD has incorrect permission bits\n");10421043return ret;1044}1045NOKPROBE_SYMBOL(spurious_kernel_fault);10461047int show_unhandled_signals = 1;10481049static inline int1050access_error(unsigned long error_code, struct vm_area_struct *vma)1051{1052/* This is only called for the current mm, so: */1053bool foreign = false;10541055/*1056* Read or write was blocked by protection keys. This is1057* always an unconditional error and can never result in1058* a follow-up action to resolve the fault, like a COW.1059*/1060if (error_code & X86_PF_PK)1061return 1;10621063/*1064* SGX hardware blocked the access. This usually happens1065* when the enclave memory contents have been destroyed, like1066* after a suspend/resume cycle. In any case, the kernel can't1067* fix the cause of the fault. Handle the fault as an access1068* error even in cases where no actual access violation1069* occurred. This allows userspace to rebuild the enclave in1070* response to the signal.1071*/1072if (unlikely(error_code & X86_PF_SGX))1073return 1;10741075/*1076* Make sure to check the VMA so that we do not perform1077* faults just to hit a X86_PF_PK as soon as we fill in a1078* page.1079*/1080if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),1081(error_code & X86_PF_INSTR), foreign))1082return 1;10831084/*1085* Shadow stack accesses (PF_SHSTK=1) are only permitted to1086* shadow stack VMAs. All other accesses result in an error.1087*/1088if (error_code & X86_PF_SHSTK) {1089if (unlikely(!(vma->vm_flags & VM_SHADOW_STACK)))1090return 1;1091if (unlikely(!(vma->vm_flags & VM_WRITE)))1092return 1;1093return 0;1094}10951096if (error_code & X86_PF_WRITE) {1097/* write, present and write, not present: */1098if (unlikely(vma->vm_flags & VM_SHADOW_STACK))1099return 1;1100if (unlikely(!(vma->vm_flags & VM_WRITE)))1101return 1;1102return 0;1103}11041105/* read, present: */1106if (unlikely(error_code & X86_PF_PROT))1107return 1;11081109/* read, not present: */1110if (unlikely(!vma_is_accessible(vma)))1111return 1;11121113return 0;1114}11151116bool fault_in_kernel_space(unsigned long address)1117{1118/*1119* On 64-bit systems, the vsyscall page is at an address above1120* TASK_SIZE_MAX, but is not considered part of the kernel1121* address space.1122*/1123if (IS_ENABLED(CONFIG_X86_64) && is_vsyscall_vaddr(address))1124return false;11251126return address >= TASK_SIZE_MAX;1127}11281129/*1130* Called for all faults where 'address' is part of the kernel address1131* space. Might get called for faults that originate from *code* that1132* ran in userspace or the kernel.1133*/1134static void1135do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,1136unsigned long address)1137{1138/*1139* Protection keys exceptions only happen on user pages. We1140* have no user pages in the kernel portion of the address1141* space, so do not expect them here.1142*/1143WARN_ON_ONCE(hw_error_code & X86_PF_PK);11441145#ifdef CONFIG_X86_321146/*1147* We can fault-in kernel-space virtual memory on-demand. The1148* 'reference' page table is init_mm.pgd.1149*1150* NOTE! We MUST NOT take any locks for this case. We may1151* be in an interrupt or a critical region, and should1152* only copy the information from the master page table,1153* nothing more.1154*1155* Before doing this on-demand faulting, ensure that the1156* fault is not any of the following:1157* 1. A fault on a PTE with a reserved bit set.1158* 2. A fault caused by a user-mode access. (Do not demand-1159* fault kernel memory due to user-mode accesses).1160* 3. A fault caused by a page-level protection violation.1161* (A demand fault would be on a non-present page which1162* would have X86_PF_PROT==0).1163*1164* This is only needed to close a race condition on x86-32 in1165* the vmalloc mapping/unmapping code. See the comment above1166* vmalloc_fault() for details. On x86-64 the race does not1167* exist as the vmalloc mappings don't need to be synchronized1168* there.1169*/1170if (!(hw_error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {1171if (vmalloc_fault(address) >= 0)1172return;1173}1174#endif11751176if (is_f00f_bug(regs, hw_error_code, address))1177return;11781179/* Was the fault spurious, caused by lazy TLB invalidation? */1180if (spurious_kernel_fault(hw_error_code, address))1181return;11821183/* kprobes don't want to hook the spurious faults: */1184if (WARN_ON_ONCE(kprobe_page_fault(regs, X86_TRAP_PF)))1185return;11861187/*1188* Note, despite being a "bad area", there are quite a few1189* acceptable reasons to get here, such as erratum fixups1190* and handling kernel code that can fault, like get_user().1191*1192* Don't take the mm semaphore here. If we fixup a prefetch1193* fault we could otherwise deadlock:1194*/1195bad_area_nosemaphore(regs, hw_error_code, address);1196}1197NOKPROBE_SYMBOL(do_kern_addr_fault);11981199/*1200* Handle faults in the user portion of the address space. Nothing in here1201* should check X86_PF_USER without a specific justification: for almost1202* all purposes, we should treat a normal kernel access to user memory1203* (e.g. get_user(), put_user(), etc.) the same as the WRUSS instruction.1204* The one exception is AC flag handling, which is, per the x861205* architecture, special for WRUSS.1206*/1207static inline1208void do_user_addr_fault(struct pt_regs *regs,1209unsigned long error_code,1210unsigned long address)1211{1212struct vm_area_struct *vma;1213struct task_struct *tsk;1214struct mm_struct *mm;1215vm_fault_t fault;1216unsigned int flags = FAULT_FLAG_DEFAULT;12171218tsk = current;1219mm = tsk->mm;12201221if (unlikely((error_code & (X86_PF_USER | X86_PF_INSTR)) == X86_PF_INSTR)) {1222/*1223* Whoops, this is kernel mode code trying to execute from1224* user memory. Unless this is AMD erratum #93, which1225* corrupts RIP such that it looks like a user address,1226* this is unrecoverable. Don't even try to look up the1227* VMA or look for extable entries.1228*/1229if (is_errata93(regs, address))1230return;12311232page_fault_oops(regs, error_code, address);1233return;1234}12351236/* kprobes don't want to hook the spurious faults: */1237if (WARN_ON_ONCE(kprobe_page_fault(regs, X86_TRAP_PF)))1238return;12391240/*1241* Reserved bits are never expected to be set on1242* entries in the user portion of the page tables.1243*/1244if (unlikely(error_code & X86_PF_RSVD))1245pgtable_bad(regs, error_code, address);12461247/*1248* If SMAP is on, check for invalid kernel (supervisor) access to user1249* pages in the user address space. The odd case here is WRUSS,1250* which, according to the preliminary documentation, does not respect1251* SMAP and will have the USER bit set so, in all cases, SMAP1252* enforcement appears to be consistent with the USER bit.1253*/1254if (unlikely(cpu_feature_enabled(X86_FEATURE_SMAP) &&1255!(error_code & X86_PF_USER) &&1256!(regs->flags & X86_EFLAGS_AC))) {1257/*1258* No extable entry here. This was a kernel access to an1259* invalid pointer. get_kernel_nofault() will not get here.1260*/1261page_fault_oops(regs, error_code, address);1262return;1263}12641265/*1266* If we're in an interrupt, have no user context or are running1267* in a region with pagefaults disabled then we must not take the fault1268*/1269if (unlikely(faulthandler_disabled() || !mm)) {1270bad_area_nosemaphore(regs, error_code, address);1271return;1272}12731274/* Legacy check - remove this after verifying that it doesn't trigger */1275if (WARN_ON_ONCE(!(regs->flags & X86_EFLAGS_IF))) {1276bad_area_nosemaphore(regs, error_code, address);1277return;1278}12791280local_irq_enable();12811282perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);12831284/*1285* Read-only permissions can not be expressed in shadow stack PTEs.1286* Treat all shadow stack accesses as WRITE faults. This ensures1287* that the MM will prepare everything (e.g., break COW) such that1288* maybe_mkwrite() can create a proper shadow stack PTE.1289*/1290if (error_code & X86_PF_SHSTK)1291flags |= FAULT_FLAG_WRITE;1292if (error_code & X86_PF_WRITE)1293flags |= FAULT_FLAG_WRITE;1294if (error_code & X86_PF_INSTR)1295flags |= FAULT_FLAG_INSTRUCTION;12961297/*1298* We set FAULT_FLAG_USER based on the register state, not1299* based on X86_PF_USER. User space accesses that cause1300* system page faults are still user accesses.1301*/1302if (user_mode(regs))1303flags |= FAULT_FLAG_USER;13041305#ifdef CONFIG_X86_641306/*1307* Faults in the vsyscall page might need emulation. The1308* vsyscall page is at a high address (>PAGE_OFFSET), but is1309* considered to be part of the user address space.1310*1311* The vsyscall page does not have a "real" VMA, so do this1312* emulation before we go searching for VMAs.1313*1314* PKRU never rejects instruction fetches, so we don't need1315* to consider the PF_PK bit.1316*/1317if (is_vsyscall_vaddr(address)) {1318if (emulate_vsyscall(error_code, regs, address))1319return;1320}1321#endif13221323if (!(flags & FAULT_FLAG_USER))1324goto lock_mmap;13251326vma = lock_vma_under_rcu(mm, address);1327if (!vma)1328goto lock_mmap;13291330if (unlikely(access_error(error_code, vma))) {1331bad_area_access_error(regs, error_code, address, NULL, vma);1332count_vm_vma_lock_event(VMA_LOCK_SUCCESS);1333return;1334}1335fault = handle_mm_fault(vma, address, flags | FAULT_FLAG_VMA_LOCK, regs);1336if (!(fault & (VM_FAULT_RETRY | VM_FAULT_COMPLETED)))1337vma_end_read(vma);13381339if (!(fault & VM_FAULT_RETRY)) {1340count_vm_vma_lock_event(VMA_LOCK_SUCCESS);1341goto done;1342}1343count_vm_vma_lock_event(VMA_LOCK_RETRY);1344if (fault & VM_FAULT_MAJOR)1345flags |= FAULT_FLAG_TRIED;13461347/* Quick path to respond to signals */1348if (fault_signal_pending(fault, regs)) {1349if (!user_mode(regs))1350kernelmode_fixup_or_oops(regs, error_code, address,1351SIGBUS, BUS_ADRERR,1352ARCH_DEFAULT_PKEY);1353return;1354}1355lock_mmap:13561357retry:1358vma = lock_mm_and_find_vma(mm, address, regs);1359if (unlikely(!vma)) {1360bad_area_nosemaphore(regs, error_code, address);1361return;1362}13631364/*1365* Ok, we have a good vm_area for this memory access, so1366* we can handle it..1367*/1368if (unlikely(access_error(error_code, vma))) {1369bad_area_access_error(regs, error_code, address, mm, vma);1370return;1371}13721373/*1374* If for any reason at all we couldn't handle the fault,1375* make sure we exit gracefully rather than endlessly redo1376* the fault. Since we never set FAULT_FLAG_RETRY_NOWAIT, if1377* we get VM_FAULT_RETRY back, the mmap_lock has been unlocked.1378*1379* Note that handle_userfault() may also release and reacquire mmap_lock1380* (and not return with VM_FAULT_RETRY), when returning to userland to1381* repeat the page fault later with a VM_FAULT_NOPAGE retval1382* (potentially after handling any pending signal during the return to1383* userland). The return to userland is identified whenever1384* FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.1385*/1386fault = handle_mm_fault(vma, address, flags, regs);13871388if (fault_signal_pending(fault, regs)) {1389/*1390* Quick path to respond to signals. The core mm code1391* has unlocked the mm for us if we get here.1392*/1393if (!user_mode(regs))1394kernelmode_fixup_or_oops(regs, error_code, address,1395SIGBUS, BUS_ADRERR,1396ARCH_DEFAULT_PKEY);1397return;1398}13991400/* The fault is fully completed (including releasing mmap lock) */1401if (fault & VM_FAULT_COMPLETED)1402return;14031404/*1405* If we need to retry the mmap_lock has already been released,1406* and if there is a fatal signal pending there is no guarantee1407* that we made any progress. Handle this case first.1408*/1409if (unlikely(fault & VM_FAULT_RETRY)) {1410flags |= FAULT_FLAG_TRIED;1411goto retry;1412}14131414mmap_read_unlock(mm);1415done:1416if (likely(!(fault & VM_FAULT_ERROR)))1417return;14181419if (fatal_signal_pending(current) && !user_mode(regs)) {1420kernelmode_fixup_or_oops(regs, error_code, address,14210, 0, ARCH_DEFAULT_PKEY);1422return;1423}14241425if (fault & VM_FAULT_OOM) {1426/* Kernel mode? Handle exceptions or die: */1427if (!user_mode(regs)) {1428kernelmode_fixup_or_oops(regs, error_code, address,1429SIGSEGV, SEGV_MAPERR,1430ARCH_DEFAULT_PKEY);1431return;1432}14331434/*1435* We ran out of memory, call the OOM killer, and return the1436* userspace (which will retry the fault, or kill us if we got1437* oom-killed):1438*/1439pagefault_out_of_memory();1440} else {1441if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|1442VM_FAULT_HWPOISON_LARGE))1443do_sigbus(regs, error_code, address, fault);1444else if (fault & VM_FAULT_SIGSEGV)1445bad_area_nosemaphore(regs, error_code, address);1446else1447BUG();1448}1449}1450NOKPROBE_SYMBOL(do_user_addr_fault);14511452static __always_inline void1453trace_page_fault_entries(struct pt_regs *regs, unsigned long error_code,1454unsigned long address)1455{1456if (user_mode(regs))1457trace_page_fault_user(address, regs, error_code);1458else1459trace_page_fault_kernel(address, regs, error_code);1460}14611462static __always_inline void1463handle_page_fault(struct pt_regs *regs, unsigned long error_code,1464unsigned long address)1465{1466trace_page_fault_entries(regs, error_code, address);14671468if (unlikely(kmmio_fault(regs, address)))1469return;14701471/* Was the fault on kernel-controlled part of the address space? */1472if (unlikely(fault_in_kernel_space(address))) {1473do_kern_addr_fault(regs, error_code, address);1474} else {1475do_user_addr_fault(regs, error_code, address);1476/*1477* User address page fault handling might have reenabled1478* interrupts. Fixing up all potential exit points of1479* do_user_addr_fault() and its leaf functions is just not1480* doable w/o creating an unholy mess or turning the code1481* upside down.1482*/1483local_irq_disable();1484}1485}14861487DEFINE_IDTENTRY_RAW_ERRORCODE(exc_page_fault)1488{1489irqentry_state_t state;1490unsigned long address;14911492address = cpu_feature_enabled(X86_FEATURE_FRED) ? fred_event_data(regs) : read_cr2();14931494/*1495* KVM uses #PF vector to deliver 'page not present' events to guests1496* (asynchronous page fault mechanism). The event happens when a1497* userspace task is trying to access some valid (from guest's point of1498* view) memory which is not currently mapped by the host (e.g. the1499* memory is swapped out). Note, the corresponding "page ready" event1500* which is injected when the memory becomes available, is delivered via1501* an interrupt mechanism and not a #PF exception1502* (see arch/x86/kernel/kvm.c: sysvec_kvm_asyncpf_interrupt()).1503*1504* We are relying on the interrupted context being sane (valid RSP,1505* relevant locks not held, etc.), which is fine as long as the1506* interrupted context had IF=1. We are also relying on the KVM1507* async pf type field and CR2 being read consistently instead of1508* getting values from real and async page faults mixed up.1509*1510* Fingers crossed.1511*1512* The async #PF handling code takes care of idtentry handling1513* itself.1514*/1515if (kvm_handle_async_pf(regs, (u32)address))1516return;15171518/*1519* Entry handling for valid #PF from kernel mode is slightly1520* different: RCU is already watching and ct_irq_enter() must not1521* be invoked because a kernel fault on a user space address might1522* sleep.1523*1524* In case the fault hit a RCU idle region the conditional entry1525* code reenabled RCU to avoid subsequent wreckage which helps1526* debuggability.1527*/1528state = irqentry_enter(regs);15291530instrumentation_begin();1531handle_page_fault(regs, error_code, address);1532instrumentation_end();15331534irqentry_exit(regs, state);1535}153615371538