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/bootmem.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_recover_from_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/pgalloc.h> /* pgd_*(), ... */
25 #include <asm/fixmap.h> /* VSYSCALL_ADDR */
26 #include <asm/vsyscall.h> /* emulate_vsyscall */
27 #include <asm/vm86.h> /* struct vm86 */
28 #include <asm/mmu_context.h> /* vma_pkey() */
29 #include <asm/efi.h> /* efi_recover_from_page_fault()*/
31 #define CREATE_TRACE_POINTS
32 #include <asm/trace/exceptions.h>
35 * Returns 0 if mmiotrace is disabled, or if the fault is not
36 * handled by mmiotrace:
38 static nokprobe_inline int
39 kmmio_fault(struct pt_regs *regs, unsigned long addr)
41 if (unlikely(is_kmmio_active()))
42 if (kmmio_handler(regs, addr) == 1)
47 static nokprobe_inline int kprobes_fault(struct pt_regs *regs)
49 if (!kprobes_built_in())
54 * To be potentially processing a kprobe fault and to be allowed to call
55 * kprobe_running(), we have to be non-preemptible.
59 if (!kprobe_running())
61 return kprobe_fault_handler(regs, X86_TRAP_PF);
69 * Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
70 * Check that here and ignore it.
74 * Sometimes the CPU reports invalid exceptions on prefetch.
75 * Check that here and ignore it.
77 * Opcode checker based on code by Richard Brunner.
80 check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
81 unsigned char opcode, int *prefetch)
83 unsigned char instr_hi = opcode & 0xf0;
84 unsigned char instr_lo = opcode & 0x0f;
90 * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
91 * In X86_64 long mode, the CPU will signal invalid
92 * opcode if some of these prefixes are present so
93 * X86_64 will never get here anyway
95 return ((instr_lo & 7) == 0x6);
99 * In AMD64 long mode 0x40..0x4F are valid REX prefixes
100 * Need to figure out under what instruction mode the
101 * instruction was issued. Could check the LDT for lm,
102 * but for now it's good enough to assume that long
103 * mode only uses well known segments or kernel.
105 return (!user_mode(regs) || user_64bit_mode(regs));
108 /* 0x64 thru 0x67 are valid prefixes in all modes. */
109 return (instr_lo & 0xC) == 0x4;
111 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
112 return !instr_lo || (instr_lo>>1) == 1;
114 /* Prefetch instruction is 0x0F0D or 0x0F18 */
115 if (probe_kernel_address(instr, opcode))
118 *prefetch = (instr_lo == 0xF) &&
119 (opcode == 0x0D || opcode == 0x18);
127 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
129 unsigned char *max_instr;
130 unsigned char *instr;
134 * If it was a exec (instruction fetch) fault on NX page, then
135 * do not ignore the fault:
137 if (error_code & X86_PF_INSTR)
140 instr = (void *)convert_ip_to_linear(current, regs);
141 max_instr = instr + 15;
143 if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE_MAX)
146 while (instr < max_instr) {
147 unsigned char opcode;
149 if (probe_kernel_address(instr, opcode))
154 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
161 * A protection key fault means that the PKRU value did not allow
162 * access to some PTE. Userspace can figure out what PKRU was
163 * from the XSAVE state, and this function fills out a field in
164 * siginfo so userspace can discover which protection key was set
167 * If we get here, we know that the hardware signaled a X86_PF_PK
168 * fault and that there was a VMA once we got in the fault
169 * handler. It does *not* guarantee that the VMA we find here
170 * was the one that we faulted on.
172 * 1. T1 : mprotect_key(foo, PAGE_SIZE, pkey=4);
173 * 2. T1 : set PKRU to deny access to pkey=4, touches page
175 * 4. T2: mprotect_key(foo, PAGE_SIZE, pkey=5);
176 * 5. T1 : enters fault handler, takes mmap_sem, etc...
177 * 6. T1 : reaches here, sees vma_pkey(vma)=5, when we really
178 * faulted on a pte with its pkey=4.
180 static void fill_sig_info_pkey(int si_signo, int si_code, siginfo_t *info,
183 /* This is effectively an #ifdef */
184 if (!boot_cpu_has(X86_FEATURE_OSPKE))
187 /* Fault not from Protection Keys: nothing to do */
188 if ((si_code != SEGV_PKUERR) || (si_signo != SIGSEGV))
191 * force_sig_info_fault() is called from a number of
192 * contexts, some of which have a VMA and some of which
193 * do not. The X86_PF_PK handing happens after we have a
194 * valid VMA, so we should never reach this without a
198 WARN_ONCE(1, "PKU fault with no VMA passed in");
203 * si_pkey should be thought of as a strong hint, but not
204 * absolutely guranteed to be 100% accurate because of
205 * the race explained above.
207 info->si_pkey = *pkey;
211 force_sig_info_fault(int si_signo, int si_code, unsigned long address,
212 struct task_struct *tsk, u32 *pkey, int fault)
217 clear_siginfo(&info);
218 info.si_signo = si_signo;
220 info.si_code = si_code;
221 info.si_addr = (void __user *)address;
222 if (fault & VM_FAULT_HWPOISON_LARGE)
223 lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));
224 if (fault & VM_FAULT_HWPOISON)
226 info.si_addr_lsb = lsb;
228 fill_sig_info_pkey(si_signo, si_code, &info, pkey);
230 force_sig_info(si_signo, &info, tsk);
233 DEFINE_SPINLOCK(pgd_lock);
237 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
239 unsigned index = pgd_index(address);
246 pgd_k = init_mm.pgd + index;
248 if (!pgd_present(*pgd_k))
252 * set_pgd(pgd, *pgd_k); here would be useless on PAE
253 * and redundant with the set_pmd() on non-PAE. As would
256 p4d = p4d_offset(pgd, address);
257 p4d_k = p4d_offset(pgd_k, address);
258 if (!p4d_present(*p4d_k))
261 pud = pud_offset(p4d, address);
262 pud_k = pud_offset(p4d_k, address);
263 if (!pud_present(*pud_k))
266 pmd = pmd_offset(pud, address);
267 pmd_k = pmd_offset(pud_k, address);
268 if (!pmd_present(*pmd_k))
271 if (!pmd_present(*pmd))
272 set_pmd(pmd, *pmd_k);
274 BUG_ON(pmd_page(*pmd) != pmd_page(*pmd_k));
279 void vmalloc_sync_all(void)
281 unsigned long address;
283 if (SHARED_KERNEL_PMD)
286 for (address = VMALLOC_START & PMD_MASK;
287 address >= TASK_SIZE_MAX && address < FIXADDR_TOP;
288 address += PMD_SIZE) {
291 spin_lock(&pgd_lock);
292 list_for_each_entry(page, &pgd_list, lru) {
293 spinlock_t *pgt_lock;
296 /* the pgt_lock only for Xen */
297 pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
300 ret = vmalloc_sync_one(page_address(page), address);
301 spin_unlock(pgt_lock);
306 spin_unlock(&pgd_lock);
313 * Handle a fault on the vmalloc or module mapping area
315 static noinline int vmalloc_fault(unsigned long address)
317 unsigned long pgd_paddr;
321 /* Make sure we are in vmalloc area: */
322 if (!(address >= VMALLOC_START && address < VMALLOC_END))
326 * Synchronize this task's top level page-table
327 * with the 'reference' page table.
329 * Do _not_ use "current" here. We might be inside
330 * an interrupt in the middle of a task switch..
332 pgd_paddr = read_cr3_pa();
333 pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
337 if (pmd_large(*pmd_k))
340 pte_k = pte_offset_kernel(pmd_k, address);
341 if (!pte_present(*pte_k))
346 NOKPROBE_SYMBOL(vmalloc_fault);
349 * Did it hit the DOS screen memory VA from vm86 mode?
352 check_v8086_mode(struct pt_regs *regs, unsigned long address,
353 struct task_struct *tsk)
358 if (!v8086_mode(regs) || !tsk->thread.vm86)
361 bit = (address - 0xA0000) >> PAGE_SHIFT;
363 tsk->thread.vm86->screen_bitmap |= 1 << bit;
367 static bool low_pfn(unsigned long pfn)
369 return pfn < max_low_pfn;
372 static void dump_pagetable(unsigned long address)
374 pgd_t *base = __va(read_cr3_pa());
375 pgd_t *pgd = &base[pgd_index(address)];
381 #ifdef CONFIG_X86_PAE
382 pr_info("*pdpt = %016Lx ", pgd_val(*pgd));
383 if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
385 #define pr_pde pr_cont
387 #define pr_pde pr_info
389 p4d = p4d_offset(pgd, address);
390 pud = pud_offset(p4d, address);
391 pmd = pmd_offset(pud, address);
392 pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
396 * We must not directly access the pte in the highpte
397 * case if the page table is located in highmem.
398 * And let's rather not kmap-atomic the pte, just in case
399 * it's allocated already:
401 if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
404 pte = pte_offset_kernel(pmd, address);
405 pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
410 #else /* CONFIG_X86_64: */
412 void vmalloc_sync_all(void)
414 sync_global_pgds(VMALLOC_START & PGDIR_MASK, VMALLOC_END);
420 * Handle a fault on the vmalloc area
422 static noinline int vmalloc_fault(unsigned long address)
430 /* Make sure we are in vmalloc area: */
431 if (!(address >= VMALLOC_START && address < VMALLOC_END))
434 WARN_ON_ONCE(in_nmi());
437 * Copy kernel mappings over when needed. This can also
438 * happen within a race in page table update. In the later
441 pgd = (pgd_t *)__va(read_cr3_pa()) + pgd_index(address);
442 pgd_k = pgd_offset_k(address);
443 if (pgd_none(*pgd_k))
446 if (pgtable_l5_enabled()) {
447 if (pgd_none(*pgd)) {
448 set_pgd(pgd, *pgd_k);
449 arch_flush_lazy_mmu_mode();
451 BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_k));
455 /* With 4-level paging, copying happens on the p4d level. */
456 p4d = p4d_offset(pgd, address);
457 p4d_k = p4d_offset(pgd_k, address);
458 if (p4d_none(*p4d_k))
461 if (p4d_none(*p4d) && !pgtable_l5_enabled()) {
462 set_p4d(p4d, *p4d_k);
463 arch_flush_lazy_mmu_mode();
465 BUG_ON(p4d_pfn(*p4d) != p4d_pfn(*p4d_k));
468 BUILD_BUG_ON(CONFIG_PGTABLE_LEVELS < 4);
470 pud = pud_offset(p4d, address);
477 pmd = pmd_offset(pud, address);
484 pte = pte_offset_kernel(pmd, address);
485 if (!pte_present(*pte))
490 NOKPROBE_SYMBOL(vmalloc_fault);
492 #ifdef CONFIG_CPU_SUP_AMD
493 static const char errata93_warning[] =
495 "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
496 "******* Working around it, but it may cause SEGVs or burn power.\n"
497 "******* Please consider a BIOS update.\n"
498 "******* Disabling USB legacy in the BIOS may also help.\n";
502 * No vm86 mode in 64-bit mode:
505 check_v8086_mode(struct pt_regs *regs, unsigned long address,
506 struct task_struct *tsk)
510 static int bad_address(void *p)
514 return probe_kernel_address((unsigned long *)p, dummy);
517 static void dump_pagetable(unsigned long address)
519 pgd_t *base = __va(read_cr3_pa());
520 pgd_t *pgd = base + pgd_index(address);
526 if (bad_address(pgd))
529 pr_info("PGD %lx ", pgd_val(*pgd));
531 if (!pgd_present(*pgd))
534 p4d = p4d_offset(pgd, address);
535 if (bad_address(p4d))
538 pr_cont("P4D %lx ", p4d_val(*p4d));
539 if (!p4d_present(*p4d) || p4d_large(*p4d))
542 pud = pud_offset(p4d, address);
543 if (bad_address(pud))
546 pr_cont("PUD %lx ", pud_val(*pud));
547 if (!pud_present(*pud) || pud_large(*pud))
550 pmd = pmd_offset(pud, address);
551 if (bad_address(pmd))
554 pr_cont("PMD %lx ", pmd_val(*pmd));
555 if (!pmd_present(*pmd) || pmd_large(*pmd))
558 pte = pte_offset_kernel(pmd, address);
559 if (bad_address(pte))
562 pr_cont("PTE %lx", pte_val(*pte));
570 #endif /* CONFIG_X86_64 */
573 * Workaround for K8 erratum #93 & buggy BIOS.
575 * BIOS SMM functions are required to use a specific workaround
576 * to avoid corruption of the 64bit RIP register on C stepping K8.
578 * A lot of BIOS that didn't get tested properly miss this.
580 * The OS sees this as a page fault with the upper 32bits of RIP cleared.
581 * Try to work around it here.
583 * Note we only handle faults in kernel here.
584 * Does nothing on 32-bit.
586 static int is_errata93(struct pt_regs *regs, unsigned long address)
588 #if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
589 if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
590 || boot_cpu_data.x86 != 0xf)
593 if (address != regs->ip)
596 if ((address >> 32) != 0)
599 address |= 0xffffffffUL << 32;
600 if ((address >= (u64)_stext && address <= (u64)_etext) ||
601 (address >= MODULES_VADDR && address <= MODULES_END)) {
602 printk_once(errata93_warning);
611 * Work around K8 erratum #100 K8 in compat mode occasionally jumps
612 * to illegal addresses >4GB.
614 * We catch this in the page fault handler because these addresses
615 * are not reachable. Just detect this case and return. Any code
616 * segment in LDT is compatibility mode.
618 static int is_errata100(struct pt_regs *regs, unsigned long address)
621 if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
627 static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
629 #ifdef CONFIG_X86_F00F_BUG
633 * Pentium F0 0F C7 C8 bug workaround:
635 if (boot_cpu_has_bug(X86_BUG_F00F)) {
636 nr = (address - idt_descr.address) >> 3;
639 do_invalid_op(regs, 0);
648 show_fault_oops(struct pt_regs *regs, unsigned long error_code,
649 unsigned long address)
651 if (!oops_may_print())
654 if (error_code & X86_PF_INSTR) {
659 pgd = __va(read_cr3_pa());
660 pgd += pgd_index(address);
662 pte = lookup_address_in_pgd(pgd, address, &level);
664 if (pte && pte_present(*pte) && !pte_exec(*pte))
665 pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",
666 from_kuid(&init_user_ns, current_uid()));
667 if (pte && pte_present(*pte) && pte_exec(*pte) &&
668 (pgd_flags(*pgd) & _PAGE_USER) &&
669 (__read_cr4() & X86_CR4_SMEP))
670 pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",
671 from_kuid(&init_user_ns, current_uid()));
674 pr_alert("BUG: unable to handle kernel %s at %px\n",
675 address < PAGE_SIZE ? "NULL pointer dereference" : "paging request",
678 dump_pagetable(address);
682 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
683 unsigned long address)
685 struct task_struct *tsk;
689 flags = oops_begin();
693 printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
695 dump_pagetable(address);
697 tsk->thread.cr2 = address;
698 tsk->thread.trap_nr = X86_TRAP_PF;
699 tsk->thread.error_code = error_code;
701 if (__die("Bad pagetable", regs, error_code))
704 oops_end(flags, regs, sig);
708 no_context(struct pt_regs *regs, unsigned long error_code,
709 unsigned long address, int signal, int si_code)
711 struct task_struct *tsk = current;
715 /* Are we prepared to handle this kernel fault? */
716 if (fixup_exception(regs, X86_TRAP_PF, error_code, address)) {
718 * Any interrupt that takes a fault gets the fixup. This makes
719 * the below recursive fault logic only apply to a faults from
726 * Per the above we're !in_interrupt(), aka. task context.
728 * In this case we need to make sure we're not recursively
729 * faulting through the emulate_vsyscall() logic.
731 if (current->thread.sig_on_uaccess_err && signal) {
732 tsk->thread.trap_nr = X86_TRAP_PF;
733 tsk->thread.error_code = error_code | X86_PF_USER;
734 tsk->thread.cr2 = address;
736 /* XXX: hwpoison faults will set the wrong code. */
737 force_sig_info_fault(signal, si_code, address,
742 * Barring that, we can do the fixup and be happy.
747 #ifdef CONFIG_VMAP_STACK
749 * Stack overflow? During boot, we can fault near the initial
750 * stack in the direct map, but that's not an overflow -- check
751 * that we're in vmalloc space to avoid this.
753 if (is_vmalloc_addr((void *)address) &&
754 (((unsigned long)tsk->stack - 1 - address < PAGE_SIZE) ||
755 address - ((unsigned long)tsk->stack + THREAD_SIZE) < PAGE_SIZE)) {
756 unsigned long stack = this_cpu_read(orig_ist.ist[DOUBLEFAULT_STACK]) - sizeof(void *);
758 * We're likely to be running with very little stack space
759 * left. It's plausible that we'd hit this condition but
760 * double-fault even before we get this far, in which case
761 * we're fine: the double-fault handler will deal with it.
763 * We don't want to make it all the way into the oops code
764 * and then double-fault, though, because we're likely to
765 * break the console driver and lose most of the stack dump.
767 asm volatile ("movq %[stack], %%rsp\n\t"
768 "call handle_stack_overflow\n\t"
770 : ASM_CALL_CONSTRAINT
771 : "D" ("kernel stack overflow (page fault)"),
772 "S" (regs), "d" (address),
773 [stack] "rm" (stack));
781 * Valid to do another page fault here, because if this fault
782 * had been triggered by is_prefetch fixup_exception would have
787 * Hall of shame of CPU/BIOS bugs.
789 if (is_prefetch(regs, error_code, address))
792 if (is_errata93(regs, address))
796 * Buggy firmware could access regions which might page fault, try to
797 * recover from such faults.
799 if (IS_ENABLED(CONFIG_EFI))
800 efi_recover_from_page_fault(address);
803 * Oops. The kernel tried to access some bad page. We'll have to
804 * terminate things with extreme prejudice:
806 flags = oops_begin();
808 show_fault_oops(regs, error_code, address);
810 if (task_stack_end_corrupted(tsk))
811 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
813 tsk->thread.cr2 = address;
814 tsk->thread.trap_nr = X86_TRAP_PF;
815 tsk->thread.error_code = error_code;
818 if (__die("Oops", regs, error_code))
821 /* Executive summary in case the body of the oops scrolled away */
822 printk(KERN_DEFAULT "CR2: %016lx\n", address);
824 oops_end(flags, regs, sig);
828 * Print out info about fatal segfaults, if the show_unhandled_signals
832 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
833 unsigned long address, struct task_struct *tsk)
835 const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;
837 if (!unhandled_signal(tsk, SIGSEGV))
840 if (!printk_ratelimit())
843 printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",
844 loglvl, tsk->comm, task_pid_nr(tsk), address,
845 (void *)regs->ip, (void *)regs->sp, error_code);
847 print_vma_addr(KERN_CONT " in ", regs->ip);
849 printk(KERN_CONT "\n");
851 show_opcodes(regs, loglvl);
855 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
856 unsigned long address, u32 *pkey, int si_code)
858 struct task_struct *tsk = current;
860 /* User mode accesses just cause a SIGSEGV */
861 if (error_code & X86_PF_USER) {
863 * It's possible to have interrupts off here:
868 * Valid to do another page fault here because this one came
871 if (is_prefetch(regs, error_code, address))
874 if (is_errata100(regs, address))
879 * Instruction fetch faults in the vsyscall page might need
882 if (unlikely((error_code & X86_PF_INSTR) &&
883 ((address & ~0xfff) == VSYSCALL_ADDR))) {
884 if (emulate_vsyscall(regs, address))
890 * To avoid leaking information about the kernel page table
891 * layout, pretend that user-mode accesses to kernel addresses
892 * are always protection faults.
894 if (address >= TASK_SIZE_MAX)
895 error_code |= X86_PF_PROT;
897 if (likely(show_unhandled_signals))
898 show_signal_msg(regs, error_code, address, tsk);
900 tsk->thread.cr2 = address;
901 tsk->thread.error_code = error_code;
902 tsk->thread.trap_nr = X86_TRAP_PF;
904 force_sig_info_fault(SIGSEGV, si_code, address, tsk, pkey, 0);
909 if (is_f00f_bug(regs, address))
912 no_context(regs, error_code, address, SIGSEGV, si_code);
916 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
917 unsigned long address, u32 *pkey)
919 __bad_area_nosemaphore(regs, error_code, address, pkey, SEGV_MAPERR);
923 __bad_area(struct pt_regs *regs, unsigned long error_code,
924 unsigned long address, struct vm_area_struct *vma, int si_code)
926 struct mm_struct *mm = current->mm;
930 pkey = vma_pkey(vma);
933 * Something tried to access memory that isn't in our memory map..
934 * Fix it, but check if it's kernel or user first..
936 up_read(&mm->mmap_sem);
938 __bad_area_nosemaphore(regs, error_code, address,
939 (vma) ? &pkey : NULL, si_code);
943 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
945 __bad_area(regs, error_code, address, NULL, SEGV_MAPERR);
948 static inline bool bad_area_access_from_pkeys(unsigned long error_code,
949 struct vm_area_struct *vma)
951 /* This code is always called on the current mm */
952 bool foreign = false;
954 if (!boot_cpu_has(X86_FEATURE_OSPKE))
956 if (error_code & X86_PF_PK)
958 /* this checks permission keys on the VMA: */
959 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
960 (error_code & X86_PF_INSTR), foreign))
966 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
967 unsigned long address, struct vm_area_struct *vma)
970 * This OSPKE check is not strictly necessary at runtime.
971 * But, doing it this way allows compiler optimizations
972 * if pkeys are compiled out.
974 if (bad_area_access_from_pkeys(error_code, vma))
975 __bad_area(regs, error_code, address, vma, SEGV_PKUERR);
977 __bad_area(regs, error_code, address, vma, SEGV_ACCERR);
981 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
982 u32 *pkey, unsigned int fault)
984 struct task_struct *tsk = current;
985 int code = BUS_ADRERR;
987 /* Kernel mode? Handle exceptions or die: */
988 if (!(error_code & X86_PF_USER)) {
989 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
993 /* User-space => ok to do another page fault: */
994 if (is_prefetch(regs, error_code, address))
997 tsk->thread.cr2 = address;
998 tsk->thread.error_code = error_code;
999 tsk->thread.trap_nr = X86_TRAP_PF;
1001 #ifdef CONFIG_MEMORY_FAILURE
1002 if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
1004 "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
1005 tsk->comm, tsk->pid, address);
1006 code = BUS_MCEERR_AR;
1009 force_sig_info_fault(SIGBUS, code, address, tsk, pkey, fault);
1012 static noinline void
1013 mm_fault_error(struct pt_regs *regs, unsigned long error_code,
1014 unsigned long address, u32 *pkey, vm_fault_t fault)
1016 if (fatal_signal_pending(current) && !(error_code & X86_PF_USER)) {
1017 no_context(regs, error_code, address, 0, 0);
1021 if (fault & VM_FAULT_OOM) {
1022 /* Kernel mode? Handle exceptions or die: */
1023 if (!(error_code & X86_PF_USER)) {
1024 no_context(regs, error_code, address,
1025 SIGSEGV, SEGV_MAPERR);
1030 * We ran out of memory, call the OOM killer, and return the
1031 * userspace (which will retry the fault, or kill us if we got
1034 pagefault_out_of_memory();
1036 if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
1037 VM_FAULT_HWPOISON_LARGE))
1038 do_sigbus(regs, error_code, address, pkey, fault);
1039 else if (fault & VM_FAULT_SIGSEGV)
1040 bad_area_nosemaphore(regs, error_code, address, pkey);
1046 static int spurious_fault_check(unsigned long error_code, pte_t *pte)
1048 if ((error_code & X86_PF_WRITE) && !pte_write(*pte))
1051 if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))
1054 * Note: We do not do lazy flushing on protection key
1055 * changes, so no spurious fault will ever set X86_PF_PK.
1057 if ((error_code & X86_PF_PK))
1064 * Handle a spurious fault caused by a stale TLB entry.
1066 * This allows us to lazily refresh the TLB when increasing the
1067 * permissions of a kernel page (RO -> RW or NX -> X). Doing it
1068 * eagerly is very expensive since that implies doing a full
1069 * cross-processor TLB flush, even if no stale TLB entries exist
1070 * on other processors.
1072 * Spurious faults may only occur if the TLB contains an entry with
1073 * fewer permission than the page table entry. Non-present (P = 0)
1074 * and reserved bit (R = 1) faults are never spurious.
1076 * There are no security implications to leaving a stale TLB when
1077 * increasing the permissions on a page.
1079 * Returns non-zero if a spurious fault was handled, zero otherwise.
1081 * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
1082 * (Optional Invalidation).
1085 spurious_fault(unsigned long error_code, unsigned long address)
1095 * Only writes to RO or instruction fetches from NX may cause
1098 * These could be from user or supervisor accesses but the TLB
1099 * is only lazily flushed after a kernel mapping protection
1100 * change, so user accesses are not expected to cause spurious
1103 if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&
1104 error_code != (X86_PF_INSTR | X86_PF_PROT))
1107 pgd = init_mm.pgd + pgd_index(address);
1108 if (!pgd_present(*pgd))
1111 p4d = p4d_offset(pgd, address);
1112 if (!p4d_present(*p4d))
1115 if (p4d_large(*p4d))
1116 return spurious_fault_check(error_code, (pte_t *) p4d);
1118 pud = pud_offset(p4d, address);
1119 if (!pud_present(*pud))
1122 if (pud_large(*pud))
1123 return spurious_fault_check(error_code, (pte_t *) pud);
1125 pmd = pmd_offset(pud, address);
1126 if (!pmd_present(*pmd))
1129 if (pmd_large(*pmd))
1130 return spurious_fault_check(error_code, (pte_t *) pmd);
1132 pte = pte_offset_kernel(pmd, address);
1133 if (!pte_present(*pte))
1136 ret = spurious_fault_check(error_code, pte);
1141 * Make sure we have permissions in PMD.
1142 * If not, then there's a bug in the page tables:
1144 ret = spurious_fault_check(error_code, (pte_t *) pmd);
1145 WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1149 NOKPROBE_SYMBOL(spurious_fault);
1151 int show_unhandled_signals = 1;
1154 access_error(unsigned long error_code, struct vm_area_struct *vma)
1156 /* This is only called for the current mm, so: */
1157 bool foreign = false;
1160 * Read or write was blocked by protection keys. This is
1161 * always an unconditional error and can never result in
1162 * a follow-up action to resolve the fault, like a COW.
1164 if (error_code & X86_PF_PK)
1168 * Make sure to check the VMA so that we do not perform
1169 * faults just to hit a X86_PF_PK as soon as we fill in a
1172 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
1173 (error_code & X86_PF_INSTR), foreign))
1176 if (error_code & X86_PF_WRITE) {
1177 /* write, present and write, not present: */
1178 if (unlikely(!(vma->vm_flags & VM_WRITE)))
1183 /* read, present: */
1184 if (unlikely(error_code & X86_PF_PROT))
1187 /* read, not present: */
1188 if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))))
1194 static int fault_in_kernel_space(unsigned long address)
1196 return address >= TASK_SIZE_MAX;
1199 static inline bool smap_violation(int error_code, struct pt_regs *regs)
1201 if (!IS_ENABLED(CONFIG_X86_SMAP))
1204 if (!static_cpu_has(X86_FEATURE_SMAP))
1207 if (error_code & X86_PF_USER)
1210 if (!user_mode(regs) && (regs->flags & X86_EFLAGS_AC))
1217 * This routine handles page faults. It determines the address,
1218 * and the problem, and then passes it off to one of the appropriate
1221 static noinline void
1222 __do_page_fault(struct pt_regs *regs, unsigned long error_code,
1223 unsigned long address)
1225 struct vm_area_struct *vma;
1226 struct task_struct *tsk;
1227 struct mm_struct *mm;
1228 vm_fault_t fault, major = 0;
1229 unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1235 prefetchw(&mm->mmap_sem);
1237 if (unlikely(kmmio_fault(regs, address)))
1241 * We fault-in kernel-space virtual memory on-demand. The
1242 * 'reference' page table is init_mm.pgd.
1244 * NOTE! We MUST NOT take any locks for this case. We may
1245 * be in an interrupt or a critical region, and should
1246 * only copy the information from the master page table,
1249 * This verifies that the fault happens in kernel space
1250 * (error_code & 4) == 0, and that the fault was not a
1251 * protection error (error_code & 9) == 0.
1253 if (unlikely(fault_in_kernel_space(address))) {
1254 if (!(error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {
1255 if (vmalloc_fault(address) >= 0)
1259 /* Can handle a stale RO->RW TLB: */
1260 if (spurious_fault(error_code, address))
1263 /* kprobes don't want to hook the spurious faults: */
1264 if (kprobes_fault(regs))
1267 * Don't take the mm semaphore here. If we fixup a prefetch
1268 * fault we could otherwise deadlock:
1270 bad_area_nosemaphore(regs, error_code, address, NULL);
1275 /* kprobes don't want to hook the spurious faults: */
1276 if (unlikely(kprobes_fault(regs)))
1279 if (unlikely(error_code & X86_PF_RSVD))
1280 pgtable_bad(regs, error_code, address);
1282 if (unlikely(smap_violation(error_code, regs))) {
1283 bad_area_nosemaphore(regs, error_code, address, NULL);
1288 * If we're in an interrupt, have no user context or are running
1289 * in a region with pagefaults disabled then we must not take the fault
1291 if (unlikely(faulthandler_disabled() || !mm)) {
1292 bad_area_nosemaphore(regs, error_code, address, NULL);
1297 * It's safe to allow irq's after cr2 has been saved and the
1298 * vmalloc fault has been handled.
1300 * User-mode registers count as a user access even for any
1301 * potential system fault or CPU buglet:
1303 if (user_mode(regs)) {
1305 error_code |= X86_PF_USER;
1306 flags |= FAULT_FLAG_USER;
1308 if (regs->flags & X86_EFLAGS_IF)
1312 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1314 if (error_code & X86_PF_WRITE)
1315 flags |= FAULT_FLAG_WRITE;
1316 if (error_code & X86_PF_INSTR)
1317 flags |= FAULT_FLAG_INSTRUCTION;
1320 * When running in the kernel we expect faults to occur only to
1321 * addresses in user space. All other faults represent errors in
1322 * the kernel and should generate an OOPS. Unfortunately, in the
1323 * case of an erroneous fault occurring in a code path which already
1324 * holds mmap_sem we will deadlock attempting to validate the fault
1325 * against the address space. Luckily the kernel only validly
1326 * references user space from well defined areas of code, which are
1327 * listed in the exceptions table.
1329 * As the vast majority of faults will be valid we will only perform
1330 * the source reference check when there is a possibility of a
1331 * deadlock. Attempt to lock the address space, if we cannot we then
1332 * validate the source. If this is invalid we can skip the address
1333 * space check, thus avoiding the deadlock:
1335 if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
1336 if (!(error_code & X86_PF_USER) &&
1337 !search_exception_tables(regs->ip)) {
1338 bad_area_nosemaphore(regs, error_code, address, NULL);
1342 down_read(&mm->mmap_sem);
1345 * The above down_read_trylock() might have succeeded in
1346 * which case we'll have missed the might_sleep() from
1352 vma = find_vma(mm, address);
1353 if (unlikely(!vma)) {
1354 bad_area(regs, error_code, address);
1357 if (likely(vma->vm_start <= address))
1359 if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1360 bad_area(regs, error_code, address);
1363 if (error_code & X86_PF_USER) {
1365 * Accessing the stack below %sp is always a bug.
1366 * The large cushion allows instructions like enter
1367 * and pusha to work. ("enter $65535, $31" pushes
1368 * 32 pointers and then decrements %sp by 65535.)
1370 if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
1371 bad_area(regs, error_code, address);
1375 if (unlikely(expand_stack(vma, address))) {
1376 bad_area(regs, error_code, address);
1381 * Ok, we have a good vm_area for this memory access, so
1382 * we can handle it..
1385 if (unlikely(access_error(error_code, vma))) {
1386 bad_area_access_error(regs, error_code, address, vma);
1391 * If for any reason at all we couldn't handle the fault,
1392 * make sure we exit gracefully rather than endlessly redo
1393 * the fault. Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1394 * we get VM_FAULT_RETRY back, the mmap_sem has been unlocked.
1396 * Note that handle_userfault() may also release and reacquire mmap_sem
1397 * (and not return with VM_FAULT_RETRY), when returning to userland to
1398 * repeat the page fault later with a VM_FAULT_NOPAGE retval
1399 * (potentially after handling any pending signal during the return to
1400 * userland). The return to userland is identified whenever
1401 * FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.
1402 * Thus we have to be careful about not touching vma after handling the
1403 * fault, so we read the pkey beforehand.
1405 pkey = vma_pkey(vma);
1406 fault = handle_mm_fault(vma, address, flags);
1407 major |= fault & VM_FAULT_MAJOR;
1410 * If we need to retry the mmap_sem has already been released,
1411 * and if there is a fatal signal pending there is no guarantee
1412 * that we made any progress. Handle this case first.
1414 if (unlikely(fault & VM_FAULT_RETRY)) {
1415 /* Retry at most once */
1416 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1417 flags &= ~FAULT_FLAG_ALLOW_RETRY;
1418 flags |= FAULT_FLAG_TRIED;
1419 if (!fatal_signal_pending(tsk))
1423 /* User mode? Just return to handle the fatal exception */
1424 if (flags & FAULT_FLAG_USER)
1427 /* Not returning to user mode? Handle exceptions or die: */
1428 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
1432 up_read(&mm->mmap_sem);
1433 if (unlikely(fault & VM_FAULT_ERROR)) {
1434 mm_fault_error(regs, error_code, address, &pkey, fault);
1439 * Major/minor page fault accounting. If any of the events
1440 * returned VM_FAULT_MAJOR, we account it as a major fault.
1444 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
1447 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
1450 check_v8086_mode(regs, address, tsk);
1452 NOKPROBE_SYMBOL(__do_page_fault);
1454 static nokprobe_inline void
1455 trace_page_fault_entries(unsigned long address, struct pt_regs *regs,
1456 unsigned long error_code)
1458 if (user_mode(regs))
1459 trace_page_fault_user(address, regs, error_code);
1461 trace_page_fault_kernel(address, regs, error_code);
1465 * We must have this function blacklisted from kprobes, tagged with notrace
1466 * and call read_cr2() before calling anything else. To avoid calling any
1467 * kind of tracing machinery before we've observed the CR2 value.
1469 * exception_{enter,exit}() contains all sorts of tracepoints.
1471 dotraplinkage void notrace
1472 do_page_fault(struct pt_regs *regs, unsigned long error_code)
1474 unsigned long address = read_cr2(); /* Get the faulting address */
1475 enum ctx_state prev_state;
1477 prev_state = exception_enter();
1478 if (trace_pagefault_enabled())
1479 trace_page_fault_entries(address, regs, error_code);
1481 __do_page_fault(regs, error_code, address);
1482 exception_exit(prev_state);
1484 NOKPROBE_SYMBOL(do_page_fault);