1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 1995 Linus Torvalds
4 * Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.
5 * Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar
7 #include <linux/sched.h> /* test_thread_flag(), ... */
8 #include <linux/sched/task_stack.h> /* task_stack_*(), ... */
9 #include <linux/kdebug.h> /* oops_begin/end, ... */
10 #include <linux/extable.h> /* search_exception_tables */
11 #include <linux/memblock.h> /* max_low_pfn */
12 #include <linux/kprobes.h> /* NOKPROBE_SYMBOL, ... */
13 #include <linux/mmiotrace.h> /* kmmio_handler, ... */
14 #include <linux/perf_event.h> /* perf_sw_event */
15 #include <linux/hugetlb.h> /* hstate_index_to_shift */
16 #include <linux/prefetch.h> /* prefetchw */
17 #include <linux/context_tracking.h> /* exception_enter(), ... */
18 #include <linux/uaccess.h> /* faulthandler_disabled() */
19 #include <linux/efi.h> /* efi_crash_gracefully_on_page_fault()*/
20 #include <linux/mm_types.h>
22 #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() */
35 #define CREATE_TRACE_POINTS
36 #include <asm/trace/exceptions.h>
39 * Returns 0 if mmiotrace is disabled, or if the fault is not
40 * handled by mmiotrace:
42 static nokprobe_inline int
43 kmmio_fault(struct pt_regs *regs, unsigned long addr)
45 if (unlikely(is_kmmio_active()))
46 if (kmmio_handler(regs, addr) == 1)
56 * Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
57 * Check that here and ignore it. This is AMD erratum #91.
61 * Sometimes the CPU reports invalid exceptions on prefetch.
62 * Check that here and ignore it.
64 * Opcode checker based on code by Richard Brunner.
67 check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
68 unsigned char opcode, int *prefetch)
70 unsigned char instr_hi = opcode & 0xf0;
71 unsigned char instr_lo = opcode & 0x0f;
77 * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
78 * In X86_64 long mode, the CPU will signal invalid
79 * opcode if some of these prefixes are present so
80 * X86_64 will never get here anyway
82 return ((instr_lo & 7) == 0x6);
86 * In 64-bit mode 0x40..0x4F are valid REX prefixes
88 return (!user_mode(regs) || user_64bit_mode(regs));
91 /* 0x64 thru 0x67 are valid prefixes in all modes. */
92 return (instr_lo & 0xC) == 0x4;
94 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
95 return !instr_lo || (instr_lo>>1) == 1;
97 /* Prefetch instruction is 0x0F0D or 0x0F18 */
98 if (get_kernel_nofault(opcode, instr))
101 *prefetch = (instr_lo == 0xF) &&
102 (opcode == 0x0D || opcode == 0x18);
109 static bool is_amd_k8_pre_npt(void)
111 struct cpuinfo_x86 *c = &boot_cpu_data;
113 return unlikely(IS_ENABLED(CONFIG_CPU_SUP_AMD) &&
114 c->x86_vendor == X86_VENDOR_AMD &&
115 c->x86 == 0xf && c->x86_model < 0x40);
119 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
121 unsigned char *max_instr;
122 unsigned char *instr;
125 /* Erratum #91 affects AMD K8, pre-NPT CPUs */
126 if (!is_amd_k8_pre_npt())
130 * If it was a exec (instruction fetch) fault on NX page, then
131 * do not ignore the fault:
133 if (error_code & X86_PF_INSTR)
136 instr = (void *)convert_ip_to_linear(current, regs);
137 max_instr = instr + 15;
140 * This code has historically always bailed out if IP points to a
141 * not-present page (e.g. due to a race). No one has ever
142 * complained about this.
146 while (instr < max_instr) {
147 unsigned char opcode;
149 if (user_mode(regs)) {
150 if (get_user(opcode, instr))
153 if (get_kernel_nofault(opcode, instr))
159 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
167 DEFINE_SPINLOCK(pgd_lock);
171 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
173 unsigned index = pgd_index(address);
180 pgd_k = init_mm.pgd + index;
182 if (!pgd_present(*pgd_k))
186 * set_pgd(pgd, *pgd_k); here would be useless on PAE
187 * and redundant with the set_pmd() on non-PAE. As would
190 p4d = p4d_offset(pgd, address);
191 p4d_k = p4d_offset(pgd_k, address);
192 if (!p4d_present(*p4d_k))
195 pud = pud_offset(p4d, address);
196 pud_k = pud_offset(p4d_k, address);
197 if (!pud_present(*pud_k))
200 pmd = pmd_offset(pud, address);
201 pmd_k = pmd_offset(pud_k, address);
203 if (pmd_present(*pmd) != pmd_present(*pmd_k))
204 set_pmd(pmd, *pmd_k);
206 if (!pmd_present(*pmd_k))
209 BUG_ON(pmd_pfn(*pmd) != pmd_pfn(*pmd_k));
215 * Handle a fault on the vmalloc or module mapping area
217 * This is needed because there is a race condition between the time
218 * when the vmalloc mapping code updates the PMD to the point in time
219 * where it synchronizes this update with the other page-tables in the
222 * In this race window another thread/CPU can map an area on the same
223 * PMD, finds it already present and does not synchronize it with the
224 * rest of the system yet. As a result v[mz]alloc might return areas
225 * which are not mapped in every page-table in the system, causing an
226 * unhandled page-fault when they are accessed.
228 static noinline int vmalloc_fault(unsigned long address)
230 unsigned long pgd_paddr;
234 /* Make sure we are in vmalloc area: */
235 if (!(address >= VMALLOC_START && address < VMALLOC_END))
239 * Synchronize this task's top level page-table
240 * with the 'reference' page table.
242 * Do _not_ use "current" here. We might be inside
243 * an interrupt in the middle of a task switch..
245 pgd_paddr = read_cr3_pa();
246 pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
250 if (pmd_large(*pmd_k))
253 pte_k = pte_offset_kernel(pmd_k, address);
254 if (!pte_present(*pte_k))
259 NOKPROBE_SYMBOL(vmalloc_fault);
261 void arch_sync_kernel_mappings(unsigned long start, unsigned long end)
265 for (addr = start & PMD_MASK;
266 addr >= TASK_SIZE_MAX && addr < VMALLOC_END;
270 spin_lock(&pgd_lock);
271 list_for_each_entry(page, &pgd_list, lru) {
272 spinlock_t *pgt_lock;
274 /* the pgt_lock only for Xen */
275 pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
278 vmalloc_sync_one(page_address(page), addr);
279 spin_unlock(pgt_lock);
281 spin_unlock(&pgd_lock);
285 static bool low_pfn(unsigned long pfn)
287 return pfn < max_low_pfn;
290 static void dump_pagetable(unsigned long address)
292 pgd_t *base = __va(read_cr3_pa());
293 pgd_t *pgd = &base[pgd_index(address)];
299 #ifdef CONFIG_X86_PAE
300 pr_info("*pdpt = %016Lx ", pgd_val(*pgd));
301 if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
303 #define pr_pde pr_cont
305 #define pr_pde pr_info
307 p4d = p4d_offset(pgd, address);
308 pud = pud_offset(p4d, address);
309 pmd = pmd_offset(pud, address);
310 pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
314 * We must not directly access the pte in the highpte
315 * case if the page table is located in highmem.
316 * And let's rather not kmap-atomic the pte, just in case
317 * it's allocated already:
319 if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
322 pte = pte_offset_kernel(pmd, address);
323 pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
328 #else /* CONFIG_X86_64: */
330 #ifdef CONFIG_CPU_SUP_AMD
331 static const char errata93_warning[] =
333 "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
334 "******* Working around it, but it may cause SEGVs or burn power.\n"
335 "******* Please consider a BIOS update.\n"
336 "******* Disabling USB legacy in the BIOS may also help.\n";
339 static int bad_address(void *p)
343 return get_kernel_nofault(dummy, (unsigned long *)p);
346 static void dump_pagetable(unsigned long address)
348 pgd_t *base = __va(read_cr3_pa());
349 pgd_t *pgd = base + pgd_index(address);
355 if (bad_address(pgd))
358 pr_info("PGD %lx ", pgd_val(*pgd));
360 if (!pgd_present(*pgd))
363 p4d = p4d_offset(pgd, address);
364 if (bad_address(p4d))
367 pr_cont("P4D %lx ", p4d_val(*p4d));
368 if (!p4d_present(*p4d) || p4d_large(*p4d))
371 pud = pud_offset(p4d, address);
372 if (bad_address(pud))
375 pr_cont("PUD %lx ", pud_val(*pud));
376 if (!pud_present(*pud) || pud_large(*pud))
379 pmd = pmd_offset(pud, address);
380 if (bad_address(pmd))
383 pr_cont("PMD %lx ", pmd_val(*pmd));
384 if (!pmd_present(*pmd) || pmd_large(*pmd))
387 pte = pte_offset_kernel(pmd, address);
388 if (bad_address(pte))
391 pr_cont("PTE %lx", pte_val(*pte));
399 #endif /* CONFIG_X86_64 */
402 * Workaround for K8 erratum #93 & buggy BIOS.
404 * BIOS SMM functions are required to use a specific workaround
405 * to avoid corruption of the 64bit RIP register on C stepping K8.
407 * A lot of BIOS that didn't get tested properly miss this.
409 * The OS sees this as a page fault with the upper 32bits of RIP cleared.
410 * Try to work around it here.
412 * Note we only handle faults in kernel here.
413 * Does nothing on 32-bit.
415 static int is_errata93(struct pt_regs *regs, unsigned long address)
417 #if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
418 if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
419 || boot_cpu_data.x86 != 0xf)
425 if (address != regs->ip)
428 if ((address >> 32) != 0)
431 address |= 0xffffffffUL << 32;
432 if ((address >= (u64)_stext && address <= (u64)_etext) ||
433 (address >= MODULES_VADDR && address <= MODULES_END)) {
434 printk_once(errata93_warning);
443 * Work around K8 erratum #100 K8 in compat mode occasionally jumps
444 * to illegal addresses >4GB.
446 * We catch this in the page fault handler because these addresses
447 * are not reachable. Just detect this case and return. Any code
448 * segment in LDT is compatibility mode.
450 static int is_errata100(struct pt_regs *regs, unsigned long address)
453 if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
459 /* Pentium F0 0F C7 C8 bug workaround: */
460 static int is_f00f_bug(struct pt_regs *regs, unsigned long error_code,
461 unsigned long address)
463 #ifdef CONFIG_X86_F00F_BUG
464 if (boot_cpu_has_bug(X86_BUG_F00F) && !(error_code & X86_PF_USER) &&
465 idt_is_f00f_address(address)) {
466 handle_invalid_op(regs);
473 static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index)
475 u32 offset = (index >> 3) * sizeof(struct desc_struct);
477 struct ldttss_desc desc;
480 pr_alert("%s: NULL\n", name);
484 if (offset + sizeof(struct ldttss_desc) >= gdt->size) {
485 pr_alert("%s: 0x%hx -- out of bounds\n", name, index);
489 if (copy_from_kernel_nofault(&desc, (void *)(gdt->address + offset),
490 sizeof(struct ldttss_desc))) {
491 pr_alert("%s: 0x%hx -- GDT entry is not readable\n",
496 addr = desc.base0 | (desc.base1 << 16) | ((unsigned long)desc.base2 << 24);
498 addr |= ((u64)desc.base3 << 32);
500 pr_alert("%s: 0x%hx -- base=0x%lx limit=0x%x\n",
501 name, index, addr, (desc.limit0 | (desc.limit1 << 16)));
505 show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long address)
507 if (!oops_may_print())
510 if (error_code & X86_PF_INSTR) {
515 pgd = __va(read_cr3_pa());
516 pgd += pgd_index(address);
518 pte = lookup_address_in_pgd(pgd, address, &level);
520 if (pte && pte_present(*pte) && !pte_exec(*pte))
521 pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",
522 from_kuid(&init_user_ns, current_uid()));
523 if (pte && pte_present(*pte) && pte_exec(*pte) &&
524 (pgd_flags(*pgd) & _PAGE_USER) &&
525 (__read_cr4() & X86_CR4_SMEP))
526 pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",
527 from_kuid(&init_user_ns, current_uid()));
530 if (address < PAGE_SIZE && !user_mode(regs))
531 pr_alert("BUG: kernel NULL pointer dereference, address: %px\n",
534 pr_alert("BUG: unable to handle page fault for address: %px\n",
537 pr_alert("#PF: %s %s in %s mode\n",
538 (error_code & X86_PF_USER) ? "user" : "supervisor",
539 (error_code & X86_PF_INSTR) ? "instruction fetch" :
540 (error_code & X86_PF_WRITE) ? "write access" :
542 user_mode(regs) ? "user" : "kernel");
543 pr_alert("#PF: error_code(0x%04lx) - %s\n", error_code,
544 !(error_code & X86_PF_PROT) ? "not-present page" :
545 (error_code & X86_PF_RSVD) ? "reserved bit violation" :
546 (error_code & X86_PF_PK) ? "protection keys violation" :
547 "permissions violation");
549 if (!(error_code & X86_PF_USER) && user_mode(regs)) {
550 struct desc_ptr idt, gdt;
554 * This can happen for quite a few reasons. The more obvious
555 * ones are faults accessing the GDT, or LDT. Perhaps
556 * surprisingly, if the CPU tries to deliver a benign or
557 * contributory exception from user code and gets a page fault
558 * during delivery, the page fault can be delivered as though
559 * it originated directly from user code. This could happen
560 * due to wrong permissions on the IDT, GDT, LDT, TSS, or
561 * kernel or IST stack.
565 /* Usable even on Xen PV -- it's just slow. */
566 native_store_gdt(&gdt);
568 pr_alert("IDT: 0x%lx (limit=0x%hx) GDT: 0x%lx (limit=0x%hx)\n",
569 idt.address, idt.size, gdt.address, gdt.size);
572 show_ldttss(&gdt, "LDTR", ldtr);
575 show_ldttss(&gdt, "TR", tr);
578 dump_pagetable(address);
582 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
583 unsigned long address)
585 struct task_struct *tsk;
589 flags = oops_begin();
593 printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
595 dump_pagetable(address);
597 if (__die("Bad pagetable", regs, error_code))
600 oops_end(flags, regs, sig);
603 static void sanitize_error_code(unsigned long address,
604 unsigned long *error_code)
607 * To avoid leaking information about the kernel page
608 * table layout, pretend that user-mode accesses to
609 * kernel addresses are always protection faults.
611 * NB: This means that failed vsyscalls with vsyscall=none
612 * will have the PROT bit. This doesn't leak any
613 * information and does not appear to cause any problems.
615 if (address >= TASK_SIZE_MAX)
616 *error_code |= X86_PF_PROT;
619 static void set_signal_archinfo(unsigned long address,
620 unsigned long error_code)
622 struct task_struct *tsk = current;
624 tsk->thread.trap_nr = X86_TRAP_PF;
625 tsk->thread.error_code = error_code | X86_PF_USER;
626 tsk->thread.cr2 = address;
630 page_fault_oops(struct pt_regs *regs, unsigned long error_code,
631 unsigned long address)
636 if (user_mode(regs)) {
638 * Implicit kernel access from user mode? Skip the stack
639 * overflow and EFI special cases.
644 #ifdef CONFIG_VMAP_STACK
646 * Stack overflow? During boot, we can fault near the initial
647 * stack in the direct map, but that's not an overflow -- check
648 * that we're in vmalloc space to avoid this.
650 if (is_vmalloc_addr((void *)address) &&
651 (((unsigned long)current->stack - 1 - address < PAGE_SIZE) ||
652 address - ((unsigned long)current->stack + THREAD_SIZE) < PAGE_SIZE)) {
653 unsigned long stack = __this_cpu_ist_top_va(DF) - sizeof(void *);
655 * We're likely to be running with very little stack space
656 * left. It's plausible that we'd hit this condition but
657 * double-fault even before we get this far, in which case
658 * we're fine: the double-fault handler will deal with it.
660 * We don't want to make it all the way into the oops code
661 * and then double-fault, though, because we're likely to
662 * break the console driver and lose most of the stack dump.
664 asm volatile ("movq %[stack], %%rsp\n\t"
665 "call handle_stack_overflow\n\t"
667 : ASM_CALL_CONSTRAINT
668 : "D" ("kernel stack overflow (page fault)"),
669 "S" (regs), "d" (address),
670 [stack] "rm" (stack));
676 * Buggy firmware could access regions which might page fault. If
677 * this happens, EFI has a special OOPS path that will try to
678 * avoid hanging the system.
680 if (IS_ENABLED(CONFIG_EFI))
681 efi_crash_gracefully_on_page_fault(address);
685 * Oops. The kernel tried to access some bad page. We'll have to
686 * terminate things with extreme prejudice:
688 flags = oops_begin();
690 show_fault_oops(regs, error_code, address);
692 if (task_stack_end_corrupted(current))
693 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
696 if (__die("Oops", regs, error_code))
699 /* Executive summary in case the body of the oops scrolled away */
700 printk(KERN_DEFAULT "CR2: %016lx\n", address);
702 oops_end(flags, regs, sig);
706 kernelmode_fixup_or_oops(struct pt_regs *regs, unsigned long error_code,
707 unsigned long address, int signal, int si_code)
709 WARN_ON_ONCE(user_mode(regs));
711 /* Are we prepared to handle this kernel fault? */
712 if (fixup_exception(regs, X86_TRAP_PF, error_code, address)) {
714 * Any interrupt that takes a fault gets the fixup. This makes
715 * the below recursive fault logic only apply to a faults from
722 * Per the above we're !in_interrupt(), aka. task context.
724 * In this case we need to make sure we're not recursively
725 * faulting through the emulate_vsyscall() logic.
727 if (current->thread.sig_on_uaccess_err && signal) {
728 sanitize_error_code(address, &error_code);
730 set_signal_archinfo(address, error_code);
732 /* XXX: hwpoison faults will set the wrong code. */
733 force_sig_fault(signal, si_code, (void __user *)address);
737 * Barring that, we can do the fixup and be happy.
743 * AMD erratum #91 manifests as a spurious page fault on a PREFETCH
746 if (is_prefetch(regs, error_code, address))
749 page_fault_oops(regs, error_code, address);
753 * Print out info about fatal segfaults, if the show_unhandled_signals
757 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
758 unsigned long address, struct task_struct *tsk)
760 const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;
762 if (!unhandled_signal(tsk, SIGSEGV))
765 if (!printk_ratelimit())
768 printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",
769 loglvl, tsk->comm, task_pid_nr(tsk), address,
770 (void *)regs->ip, (void *)regs->sp, error_code);
772 print_vma_addr(KERN_CONT " in ", regs->ip);
774 printk(KERN_CONT "\n");
776 show_opcodes(regs, loglvl);
780 * The (legacy) vsyscall page is the long page in the kernel portion
781 * of the address space that has user-accessible permissions.
783 static bool is_vsyscall_vaddr(unsigned long vaddr)
785 return unlikely((vaddr & PAGE_MASK) == VSYSCALL_ADDR);
789 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
790 unsigned long address, u32 pkey, int si_code)
792 struct task_struct *tsk = current;
794 if (!user_mode(regs)) {
795 kernelmode_fixup_or_oops(regs, error_code, address, pkey, si_code);
799 if (!(error_code & X86_PF_USER)) {
800 /* Implicit user access to kernel memory -- just oops */
801 page_fault_oops(regs, error_code, address);
806 * User mode accesses just cause a SIGSEGV.
807 * It's possible to have interrupts off here:
812 * Valid to do another page fault here because this one came
815 if (is_prefetch(regs, error_code, address))
818 if (is_errata100(regs, address))
821 sanitize_error_code(address, &error_code);
823 if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
826 if (likely(show_unhandled_signals))
827 show_signal_msg(regs, error_code, address, tsk);
829 set_signal_archinfo(address, error_code);
831 if (si_code == SEGV_PKUERR)
832 force_sig_pkuerr((void __user *)address, pkey);
834 force_sig_fault(SIGSEGV, si_code, (void __user *)address);
840 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
841 unsigned long address)
843 __bad_area_nosemaphore(regs, error_code, address, 0, SEGV_MAPERR);
847 __bad_area(struct pt_regs *regs, unsigned long error_code,
848 unsigned long address, u32 pkey, int si_code)
850 struct mm_struct *mm = current->mm;
852 * Something tried to access memory that isn't in our memory map..
853 * Fix it, but check if it's kernel or user first..
855 mmap_read_unlock(mm);
857 __bad_area_nosemaphore(regs, error_code, address, pkey, si_code);
861 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
863 __bad_area(regs, error_code, address, 0, SEGV_MAPERR);
866 static inline bool bad_area_access_from_pkeys(unsigned long error_code,
867 struct vm_area_struct *vma)
869 /* This code is always called on the current mm */
870 bool foreign = false;
872 if (!boot_cpu_has(X86_FEATURE_OSPKE))
874 if (error_code & X86_PF_PK)
876 /* this checks permission keys on the VMA: */
877 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
878 (error_code & X86_PF_INSTR), foreign))
884 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
885 unsigned long address, struct vm_area_struct *vma)
888 * This OSPKE check is not strictly necessary at runtime.
889 * But, doing it this way allows compiler optimizations
890 * if pkeys are compiled out.
892 if (bad_area_access_from_pkeys(error_code, vma)) {
894 * A protection key fault means that the PKRU value did not allow
895 * access to some PTE. Userspace can figure out what PKRU was
896 * from the XSAVE state. This function captures the pkey from
897 * the vma and passes it to userspace so userspace can discover
898 * which protection key was set on the PTE.
900 * If we get here, we know that the hardware signaled a X86_PF_PK
901 * fault and that there was a VMA once we got in the fault
902 * handler. It does *not* guarantee that the VMA we find here
903 * was the one that we faulted on.
905 * 1. T1 : mprotect_key(foo, PAGE_SIZE, pkey=4);
906 * 2. T1 : set PKRU to deny access to pkey=4, touches page
908 * 4. T2: mprotect_key(foo, PAGE_SIZE, pkey=5);
909 * 5. T1 : enters fault handler, takes mmap_lock, etc...
910 * 6. T1 : reaches here, sees vma_pkey(vma)=5, when we really
911 * faulted on a pte with its pkey=4.
913 u32 pkey = vma_pkey(vma);
915 __bad_area(regs, error_code, address, pkey, SEGV_PKUERR);
917 __bad_area(regs, error_code, address, 0, SEGV_ACCERR);
922 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
925 /* Kernel mode? Handle exceptions or die: */
926 if (!user_mode(regs)) {
927 kernelmode_fixup_or_oops(regs, error_code, address, SIGBUS, BUS_ADRERR);
931 /* User-space => ok to do another page fault: */
932 if (is_prefetch(regs, error_code, address))
935 sanitize_error_code(address, &error_code);
937 if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
940 set_signal_archinfo(address, error_code);
942 #ifdef CONFIG_MEMORY_FAILURE
943 if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
944 struct task_struct *tsk = current;
948 "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
949 tsk->comm, tsk->pid, address);
950 if (fault & VM_FAULT_HWPOISON_LARGE)
951 lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));
952 if (fault & VM_FAULT_HWPOISON)
954 force_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb);
958 force_sig_fault(SIGBUS, BUS_ADRERR, (void __user *)address);
961 static int spurious_kernel_fault_check(unsigned long error_code, pte_t *pte)
963 if ((error_code & X86_PF_WRITE) && !pte_write(*pte))
966 if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))
973 * Handle a spurious fault caused by a stale TLB entry.
975 * This allows us to lazily refresh the TLB when increasing the
976 * permissions of a kernel page (RO -> RW or NX -> X). Doing it
977 * eagerly is very expensive since that implies doing a full
978 * cross-processor TLB flush, even if no stale TLB entries exist
979 * on other processors.
981 * Spurious faults may only occur if the TLB contains an entry with
982 * fewer permission than the page table entry. Non-present (P = 0)
983 * and reserved bit (R = 1) faults are never spurious.
985 * There are no security implications to leaving a stale TLB when
986 * increasing the permissions on a page.
988 * Returns non-zero if a spurious fault was handled, zero otherwise.
990 * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
991 * (Optional Invalidation).
994 spurious_kernel_fault(unsigned long error_code, unsigned long address)
1004 * Only writes to RO or instruction fetches from NX may cause
1007 * These could be from user or supervisor accesses but the TLB
1008 * is only lazily flushed after a kernel mapping protection
1009 * change, so user accesses are not expected to cause spurious
1012 if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&
1013 error_code != (X86_PF_INSTR | X86_PF_PROT))
1016 pgd = init_mm.pgd + pgd_index(address);
1017 if (!pgd_present(*pgd))
1020 p4d = p4d_offset(pgd, address);
1021 if (!p4d_present(*p4d))
1024 if (p4d_large(*p4d))
1025 return spurious_kernel_fault_check(error_code, (pte_t *) p4d);
1027 pud = pud_offset(p4d, address);
1028 if (!pud_present(*pud))
1031 if (pud_large(*pud))
1032 return spurious_kernel_fault_check(error_code, (pte_t *) pud);
1034 pmd = pmd_offset(pud, address);
1035 if (!pmd_present(*pmd))
1038 if (pmd_large(*pmd))
1039 return spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1041 pte = pte_offset_kernel(pmd, address);
1042 if (!pte_present(*pte))
1045 ret = spurious_kernel_fault_check(error_code, pte);
1050 * Make sure we have permissions in PMD.
1051 * If not, then there's a bug in the page tables:
1053 ret = spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1054 WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1058 NOKPROBE_SYMBOL(spurious_kernel_fault);
1060 int show_unhandled_signals = 1;
1063 access_error(unsigned long error_code, struct vm_area_struct *vma)
1065 /* This is only called for the current mm, so: */
1066 bool foreign = false;
1069 * Read or write was blocked by protection keys. This is
1070 * always an unconditional error and can never result in
1071 * a follow-up action to resolve the fault, like a COW.
1073 if (error_code & X86_PF_PK)
1077 * SGX hardware blocked the access. This usually happens
1078 * when the enclave memory contents have been destroyed, like
1079 * after a suspend/resume cycle. In any case, the kernel can't
1080 * fix the cause of the fault. Handle the fault as an access
1081 * error even in cases where no actual access violation
1082 * occurred. This allows userspace to rebuild the enclave in
1083 * response to the signal.
1085 if (unlikely(error_code & X86_PF_SGX))
1089 * Make sure to check the VMA so that we do not perform
1090 * faults just to hit a X86_PF_PK as soon as we fill in a
1093 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
1094 (error_code & X86_PF_INSTR), foreign))
1097 if (error_code & X86_PF_WRITE) {
1098 /* write, present and write, not present: */
1099 if (unlikely(!(vma->vm_flags & VM_WRITE)))
1104 /* read, present: */
1105 if (unlikely(error_code & X86_PF_PROT))
1108 /* read, not present: */
1109 if (unlikely(!vma_is_accessible(vma)))
1115 bool fault_in_kernel_space(unsigned long address)
1118 * On 64-bit systems, the vsyscall page is at an address above
1119 * TASK_SIZE_MAX, but is not considered part of the kernel
1122 if (IS_ENABLED(CONFIG_X86_64) && is_vsyscall_vaddr(address))
1125 return address >= TASK_SIZE_MAX;
1129 * Called for all faults where 'address' is part of the kernel address
1130 * space. Might get called for faults that originate from *code* that
1131 * ran in userspace or the kernel.
1134 do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,
1135 unsigned long address)
1138 * Protection keys exceptions only happen on user pages. We
1139 * have no user pages in the kernel portion of the address
1140 * space, so do not expect them here.
1142 WARN_ON_ONCE(hw_error_code & X86_PF_PK);
1144 #ifdef CONFIG_X86_32
1146 * We can fault-in kernel-space virtual memory on-demand. The
1147 * 'reference' page table is init_mm.pgd.
1149 * NOTE! We MUST NOT take any locks for this case. We may
1150 * be in an interrupt or a critical region, and should
1151 * only copy the information from the master page table,
1154 * Before doing this on-demand faulting, ensure that the
1155 * fault is not any of the following:
1156 * 1. A fault on a PTE with a reserved bit set.
1157 * 2. A fault caused by a user-mode access. (Do not demand-
1158 * fault kernel memory due to user-mode accesses).
1159 * 3. A fault caused by a page-level protection violation.
1160 * (A demand fault would be on a non-present page which
1161 * would have X86_PF_PROT==0).
1163 * This is only needed to close a race condition on x86-32 in
1164 * the vmalloc mapping/unmapping code. See the comment above
1165 * vmalloc_fault() for details. On x86-64 the race does not
1166 * exist as the vmalloc mappings don't need to be synchronized
1169 if (!(hw_error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {
1170 if (vmalloc_fault(address) >= 0)
1175 if (is_f00f_bug(regs, hw_error_code, address))
1178 /* Was the fault spurious, caused by lazy TLB invalidation? */
1179 if (spurious_kernel_fault(hw_error_code, address))
1182 /* kprobes don't want to hook the spurious faults: */
1183 if (kprobe_page_fault(regs, X86_TRAP_PF))
1187 * Note, despite being a "bad area", there are quite a few
1188 * acceptable reasons to get here, such as erratum fixups
1189 * and handling kernel code that can fault, like get_user().
1191 * Don't take the mm semaphore here. If we fixup a prefetch
1192 * fault we could otherwise deadlock:
1194 bad_area_nosemaphore(regs, hw_error_code, address);
1196 NOKPROBE_SYMBOL(do_kern_addr_fault);
1199 * Handle faults in the user portion of the address space. Nothing in here
1200 * should check X86_PF_USER without a specific justification: for almost
1201 * all purposes, we should treat a normal kernel access to user memory
1202 * (e.g. get_user(), put_user(), etc.) the same as the WRUSS instruction.
1203 * The one exception is AC flag handling, which is, per the x86
1204 * architecture, special for WRUSS.
1207 void do_user_addr_fault(struct pt_regs *regs,
1208 unsigned long error_code,
1209 unsigned long address)
1211 struct vm_area_struct *vma;
1212 struct task_struct *tsk;
1213 struct mm_struct *mm;
1215 unsigned int flags = FAULT_FLAG_DEFAULT;
1220 if (unlikely((error_code & (X86_PF_USER | X86_PF_INSTR)) == X86_PF_INSTR)) {
1222 * Whoops, this is kernel mode code trying to execute from
1223 * user memory. Unless this is AMD erratum #93, which
1224 * corrupts RIP such that it looks like a user address,
1225 * this is unrecoverable. Don't even try to look up the
1226 * VMA or look for extable entries.
1228 if (is_errata93(regs, address))
1231 page_fault_oops(regs, error_code, address);
1235 /* kprobes don't want to hook the spurious faults: */
1236 if (unlikely(kprobe_page_fault(regs, X86_TRAP_PF)))
1240 * Reserved bits are never expected to be set on
1241 * entries in the user portion of the page tables.
1243 if (unlikely(error_code & X86_PF_RSVD))
1244 pgtable_bad(regs, error_code, address);
1247 * If SMAP is on, check for invalid kernel (supervisor) access to user
1248 * pages in the user address space. The odd case here is WRUSS,
1249 * which, according to the preliminary documentation, does not respect
1250 * SMAP and will have the USER bit set so, in all cases, SMAP
1251 * enforcement appears to be consistent with the USER bit.
1253 if (unlikely(cpu_feature_enabled(X86_FEATURE_SMAP) &&
1254 !(error_code & X86_PF_USER) &&
1255 !(regs->flags & X86_EFLAGS_AC))) {
1257 * No extable entry here. This was a kernel access to an
1258 * invalid pointer. get_kernel_nofault() will not get here.
1260 page_fault_oops(regs, error_code, address);
1265 * If we're in an interrupt, have no user context or are running
1266 * in a region with pagefaults disabled then we must not take the fault
1268 if (unlikely(faulthandler_disabled() || !mm)) {
1269 bad_area_nosemaphore(regs, error_code, address);
1274 * It's safe to allow irq's after cr2 has been saved and the
1275 * vmalloc fault has been handled.
1277 * User-mode registers count as a user access even for any
1278 * potential system fault or CPU buglet:
1280 if (user_mode(regs)) {
1282 flags |= FAULT_FLAG_USER;
1284 if (regs->flags & X86_EFLAGS_IF)
1288 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1290 if (error_code & X86_PF_WRITE)
1291 flags |= FAULT_FLAG_WRITE;
1292 if (error_code & X86_PF_INSTR)
1293 flags |= FAULT_FLAG_INSTRUCTION;
1295 #ifdef CONFIG_X86_64
1297 * Faults in the vsyscall page might need emulation. The
1298 * vsyscall page is at a high address (>PAGE_OFFSET), but is
1299 * considered to be part of the user address space.
1301 * The vsyscall page does not have a "real" VMA, so do this
1302 * emulation before we go searching for VMAs.
1304 * PKRU never rejects instruction fetches, so we don't need
1305 * to consider the PF_PK bit.
1307 if (is_vsyscall_vaddr(address)) {
1308 if (emulate_vsyscall(error_code, regs, address))
1314 * Kernel-mode access to the user address space should only occur
1315 * on well-defined single instructions listed in the exception
1316 * tables. But, an erroneous kernel fault occurring outside one of
1317 * those areas which also holds mmap_lock might deadlock attempting
1318 * to validate the fault against the address space.
1320 * Only do the expensive exception table search when we might be at
1321 * risk of a deadlock. This happens if we
1322 * 1. Failed to acquire mmap_lock, and
1323 * 2. The access did not originate in userspace.
1325 if (unlikely(!mmap_read_trylock(mm))) {
1326 if (!user_mode(regs) && !search_exception_tables(regs->ip)) {
1328 * Fault from code in kernel from
1329 * which we do not expect faults.
1331 bad_area_nosemaphore(regs, error_code, address);
1338 * The above down_read_trylock() might have succeeded in
1339 * which case we'll have missed the might_sleep() from
1345 vma = find_vma(mm, address);
1346 if (unlikely(!vma)) {
1347 bad_area(regs, error_code, address);
1350 if (likely(vma->vm_start <= address))
1352 if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1353 bad_area(regs, error_code, address);
1356 if (unlikely(expand_stack(vma, address))) {
1357 bad_area(regs, error_code, address);
1362 * Ok, we have a good vm_area for this memory access, so
1363 * we can handle it..
1366 if (unlikely(access_error(error_code, vma))) {
1367 bad_area_access_error(regs, error_code, address, vma);
1372 * If for any reason at all we couldn't handle the fault,
1373 * make sure we exit gracefully rather than endlessly redo
1374 * the fault. Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1375 * we get VM_FAULT_RETRY back, the mmap_lock has been unlocked.
1377 * Note that handle_userfault() may also release and reacquire mmap_lock
1378 * (and not return with VM_FAULT_RETRY), when returning to userland to
1379 * repeat the page fault later with a VM_FAULT_NOPAGE retval
1380 * (potentially after handling any pending signal during the return to
1381 * userland). The return to userland is identified whenever
1382 * FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.
1384 fault = handle_mm_fault(vma, address, flags, regs);
1386 if (fault_signal_pending(fault, regs)) {
1388 * Quick path to respond to signals. The core mm code
1389 * has unlocked the mm for us if we get here.
1391 if (!user_mode(regs))
1392 kernelmode_fixup_or_oops(regs, error_code, address,
1393 SIGBUS, BUS_ADRERR);
1398 * If we need to retry the mmap_lock has already been released,
1399 * and if there is a fatal signal pending there is no guarantee
1400 * that we made any progress. Handle this case first.
1402 if (unlikely((fault & VM_FAULT_RETRY) &&
1403 (flags & FAULT_FLAG_ALLOW_RETRY))) {
1404 flags |= FAULT_FLAG_TRIED;
1408 mmap_read_unlock(mm);
1409 if (likely(!(fault & VM_FAULT_ERROR)))
1412 if (fatal_signal_pending(current) && !user_mode(regs)) {
1413 kernelmode_fixup_or_oops(regs, error_code, address, 0, 0);
1417 if (fault & VM_FAULT_OOM) {
1418 /* Kernel mode? Handle exceptions or die: */
1419 if (!user_mode(regs)) {
1420 kernelmode_fixup_or_oops(regs, error_code, address,
1421 SIGSEGV, SEGV_MAPERR);
1426 * We ran out of memory, call the OOM killer, and return the
1427 * userspace (which will retry the fault, or kill us if we got
1430 pagefault_out_of_memory();
1432 if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
1433 VM_FAULT_HWPOISON_LARGE))
1434 do_sigbus(regs, error_code, address, fault);
1435 else if (fault & VM_FAULT_SIGSEGV)
1436 bad_area_nosemaphore(regs, error_code, address);
1441 NOKPROBE_SYMBOL(do_user_addr_fault);
1443 static __always_inline void
1444 trace_page_fault_entries(struct pt_regs *regs, unsigned long error_code,
1445 unsigned long address)
1447 if (!trace_pagefault_enabled())
1450 if (user_mode(regs))
1451 trace_page_fault_user(address, regs, error_code);
1453 trace_page_fault_kernel(address, regs, error_code);
1456 static __always_inline void
1457 handle_page_fault(struct pt_regs *regs, unsigned long error_code,
1458 unsigned long address)
1460 trace_page_fault_entries(regs, error_code, address);
1462 if (unlikely(kmmio_fault(regs, address)))
1465 /* Was the fault on kernel-controlled part of the address space? */
1466 if (unlikely(fault_in_kernel_space(address))) {
1467 do_kern_addr_fault(regs, error_code, address);
1469 do_user_addr_fault(regs, error_code, address);
1471 * User address page fault handling might have reenabled
1472 * interrupts. Fixing up all potential exit points of
1473 * do_user_addr_fault() and its leaf functions is just not
1474 * doable w/o creating an unholy mess or turning the code
1477 local_irq_disable();
1481 DEFINE_IDTENTRY_RAW_ERRORCODE(exc_page_fault)
1483 unsigned long address = read_cr2();
1484 irqentry_state_t state;
1486 prefetchw(¤t->mm->mmap_lock);
1489 * KVM uses #PF vector to deliver 'page not present' events to guests
1490 * (asynchronous page fault mechanism). The event happens when a
1491 * userspace task is trying to access some valid (from guest's point of
1492 * view) memory which is not currently mapped by the host (e.g. the
1493 * memory is swapped out). Note, the corresponding "page ready" event
1494 * which is injected when the memory becomes available, is delived via
1495 * an interrupt mechanism and not a #PF exception
1496 * (see arch/x86/kernel/kvm.c: sysvec_kvm_asyncpf_interrupt()).
1498 * We are relying on the interrupted context being sane (valid RSP,
1499 * relevant locks not held, etc.), which is fine as long as the
1500 * interrupted context had IF=1. We are also relying on the KVM
1501 * async pf type field and CR2 being read consistently instead of
1502 * getting values from real and async page faults mixed up.
1506 * The async #PF handling code takes care of idtentry handling
1509 if (kvm_handle_async_pf(regs, (u32)address))
1513 * Entry handling for valid #PF from kernel mode is slightly
1514 * different: RCU is already watching and rcu_irq_enter() must not
1515 * be invoked because a kernel fault on a user space address might
1518 * In case the fault hit a RCU idle region the conditional entry
1519 * code reenabled RCU to avoid subsequent wreckage which helps
1522 state = irqentry_enter(regs);
1524 instrumentation_begin();
1525 handle_page_fault(regs, error_code, address);
1526 instrumentation_end();
1528 irqentry_exit(regs, state);