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_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/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_recover_from_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.
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 AMD64 long mode 0x40..0x4F are valid REX prefixes
87 * Need to figure out under what instruction mode the
88 * instruction was issued. Could check the LDT for lm,
89 * but for now it's good enough to assume that long
90 * mode only uses well known segments or kernel.
92 return (!user_mode(regs) || user_64bit_mode(regs));
95 /* 0x64 thru 0x67 are valid prefixes in all modes. */
96 return (instr_lo & 0xC) == 0x4;
98 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
99 return !instr_lo || (instr_lo>>1) == 1;
101 /* Prefetch instruction is 0x0F0D or 0x0F18 */
102 if (get_kernel_nofault(opcode, instr))
105 *prefetch = (instr_lo == 0xF) &&
106 (opcode == 0x0D || opcode == 0x18);
114 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
116 unsigned char *max_instr;
117 unsigned char *instr;
121 * If it was a exec (instruction fetch) fault on NX page, then
122 * do not ignore the fault:
124 if (error_code & X86_PF_INSTR)
127 instr = (void *)convert_ip_to_linear(current, regs);
128 max_instr = instr + 15;
130 if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE_MAX)
133 while (instr < max_instr) {
134 unsigned char opcode;
136 if (get_kernel_nofault(opcode, instr))
141 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
147 DEFINE_SPINLOCK(pgd_lock);
151 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
153 unsigned index = pgd_index(address);
160 pgd_k = init_mm.pgd + index;
162 if (!pgd_present(*pgd_k))
166 * set_pgd(pgd, *pgd_k); here would be useless on PAE
167 * and redundant with the set_pmd() on non-PAE. As would
170 p4d = p4d_offset(pgd, address);
171 p4d_k = p4d_offset(pgd_k, address);
172 if (!p4d_present(*p4d_k))
175 pud = pud_offset(p4d, address);
176 pud_k = pud_offset(p4d_k, address);
177 if (!pud_present(*pud_k))
180 pmd = pmd_offset(pud, address);
181 pmd_k = pmd_offset(pud_k, address);
183 if (pmd_present(*pmd) != pmd_present(*pmd_k))
184 set_pmd(pmd, *pmd_k);
186 if (!pmd_present(*pmd_k))
189 BUG_ON(pmd_pfn(*pmd) != pmd_pfn(*pmd_k));
195 * Handle a fault on the vmalloc or module mapping area
197 * This is needed because there is a race condition between the time
198 * when the vmalloc mapping code updates the PMD to the point in time
199 * where it synchronizes this update with the other page-tables in the
202 * In this race window another thread/CPU can map an area on the same
203 * PMD, finds it already present and does not synchronize it with the
204 * rest of the system yet. As a result v[mz]alloc might return areas
205 * which are not mapped in every page-table in the system, causing an
206 * unhandled page-fault when they are accessed.
208 static noinline int vmalloc_fault(unsigned long address)
210 unsigned long pgd_paddr;
214 /* Make sure we are in vmalloc area: */
215 if (!(address >= VMALLOC_START && address < VMALLOC_END))
219 * Synchronize this task's top level page-table
220 * with the 'reference' page table.
222 * Do _not_ use "current" here. We might be inside
223 * an interrupt in the middle of a task switch..
225 pgd_paddr = read_cr3_pa();
226 pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
230 if (pmd_large(*pmd_k))
233 pte_k = pte_offset_kernel(pmd_k, address);
234 if (!pte_present(*pte_k))
239 NOKPROBE_SYMBOL(vmalloc_fault);
241 void arch_sync_kernel_mappings(unsigned long start, unsigned long end)
245 for (addr = start & PMD_MASK;
246 addr >= TASK_SIZE_MAX && addr < VMALLOC_END;
250 spin_lock(&pgd_lock);
251 list_for_each_entry(page, &pgd_list, lru) {
252 spinlock_t *pgt_lock;
254 /* the pgt_lock only for Xen */
255 pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
258 vmalloc_sync_one(page_address(page), addr);
259 spin_unlock(pgt_lock);
261 spin_unlock(&pgd_lock);
266 * Did it hit the DOS screen memory VA from vm86 mode?
269 check_v8086_mode(struct pt_regs *regs, unsigned long address,
270 struct task_struct *tsk)
275 if (!v8086_mode(regs) || !tsk->thread.vm86)
278 bit = (address - 0xA0000) >> PAGE_SHIFT;
280 tsk->thread.vm86->screen_bitmap |= 1 << bit;
284 static bool low_pfn(unsigned long pfn)
286 return pfn < max_low_pfn;
289 static void dump_pagetable(unsigned long address)
291 pgd_t *base = __va(read_cr3_pa());
292 pgd_t *pgd = &base[pgd_index(address)];
298 #ifdef CONFIG_X86_PAE
299 pr_info("*pdpt = %016Lx ", pgd_val(*pgd));
300 if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
302 #define pr_pde pr_cont
304 #define pr_pde pr_info
306 p4d = p4d_offset(pgd, address);
307 pud = pud_offset(p4d, address);
308 pmd = pmd_offset(pud, address);
309 pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
313 * We must not directly access the pte in the highpte
314 * case if the page table is located in highmem.
315 * And let's rather not kmap-atomic the pte, just in case
316 * it's allocated already:
318 if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
321 pte = pte_offset_kernel(pmd, address);
322 pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
327 #else /* CONFIG_X86_64: */
329 #ifdef CONFIG_CPU_SUP_AMD
330 static const char errata93_warning[] =
332 "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
333 "******* Working around it, but it may cause SEGVs or burn power.\n"
334 "******* Please consider a BIOS update.\n"
335 "******* Disabling USB legacy in the BIOS may also help.\n";
339 * No vm86 mode in 64-bit mode:
342 check_v8086_mode(struct pt_regs *regs, unsigned long address,
343 struct task_struct *tsk)
347 static int bad_address(void *p)
351 return get_kernel_nofault(dummy, (unsigned long *)p);
354 static void dump_pagetable(unsigned long address)
356 pgd_t *base = __va(read_cr3_pa());
357 pgd_t *pgd = base + pgd_index(address);
363 if (bad_address(pgd))
366 pr_info("PGD %lx ", pgd_val(*pgd));
368 if (!pgd_present(*pgd))
371 p4d = p4d_offset(pgd, address);
372 if (bad_address(p4d))
375 pr_cont("P4D %lx ", p4d_val(*p4d));
376 if (!p4d_present(*p4d) || p4d_large(*p4d))
379 pud = pud_offset(p4d, address);
380 if (bad_address(pud))
383 pr_cont("PUD %lx ", pud_val(*pud));
384 if (!pud_present(*pud) || pud_large(*pud))
387 pmd = pmd_offset(pud, address);
388 if (bad_address(pmd))
391 pr_cont("PMD %lx ", pmd_val(*pmd));
392 if (!pmd_present(*pmd) || pmd_large(*pmd))
395 pte = pte_offset_kernel(pmd, address);
396 if (bad_address(pte))
399 pr_cont("PTE %lx", pte_val(*pte));
407 #endif /* CONFIG_X86_64 */
410 * Workaround for K8 erratum #93 & buggy BIOS.
412 * BIOS SMM functions are required to use a specific workaround
413 * to avoid corruption of the 64bit RIP register on C stepping K8.
415 * A lot of BIOS that didn't get tested properly miss this.
417 * The OS sees this as a page fault with the upper 32bits of RIP cleared.
418 * Try to work around it here.
420 * Note we only handle faults in kernel here.
421 * Does nothing on 32-bit.
423 static int is_errata93(struct pt_regs *regs, unsigned long address)
425 #if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
426 if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
427 || boot_cpu_data.x86 != 0xf)
430 if (address != regs->ip)
433 if ((address >> 32) != 0)
436 address |= 0xffffffffUL << 32;
437 if ((address >= (u64)_stext && address <= (u64)_etext) ||
438 (address >= MODULES_VADDR && address <= MODULES_END)) {
439 printk_once(errata93_warning);
448 * Work around K8 erratum #100 K8 in compat mode occasionally jumps
449 * to illegal addresses >4GB.
451 * We catch this in the page fault handler because these addresses
452 * are not reachable. Just detect this case and return. Any code
453 * segment in LDT is compatibility mode.
455 static int is_errata100(struct pt_regs *regs, unsigned long address)
458 if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
464 /* Pentium F0 0F C7 C8 bug workaround: */
465 static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
467 #ifdef CONFIG_X86_F00F_BUG
468 if (boot_cpu_has_bug(X86_BUG_F00F) && idt_is_f00f_address(address)) {
469 handle_invalid_op(regs);
476 static void show_ldttss(const struct desc_ptr *gdt, const char *name, u16 index)
478 u32 offset = (index >> 3) * sizeof(struct desc_struct);
480 struct ldttss_desc desc;
483 pr_alert("%s: NULL\n", name);
487 if (offset + sizeof(struct ldttss_desc) >= gdt->size) {
488 pr_alert("%s: 0x%hx -- out of bounds\n", name, index);
492 if (copy_from_kernel_nofault(&desc, (void *)(gdt->address + offset),
493 sizeof(struct ldttss_desc))) {
494 pr_alert("%s: 0x%hx -- GDT entry is not readable\n",
499 addr = desc.base0 | (desc.base1 << 16) | ((unsigned long)desc.base2 << 24);
501 addr |= ((u64)desc.base3 << 32);
503 pr_alert("%s: 0x%hx -- base=0x%lx limit=0x%x\n",
504 name, index, addr, (desc.limit0 | (desc.limit1 << 16)));
508 show_fault_oops(struct pt_regs *regs, unsigned long error_code, unsigned long address)
510 if (!oops_may_print())
513 if (error_code & X86_PF_INSTR) {
518 pgd = __va(read_cr3_pa());
519 pgd += pgd_index(address);
521 pte = lookup_address_in_pgd(pgd, address, &level);
523 if (pte && pte_present(*pte) && !pte_exec(*pte))
524 pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",
525 from_kuid(&init_user_ns, current_uid()));
526 if (pte && pte_present(*pte) && pte_exec(*pte) &&
527 (pgd_flags(*pgd) & _PAGE_USER) &&
528 (__read_cr4() & X86_CR4_SMEP))
529 pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",
530 from_kuid(&init_user_ns, current_uid()));
533 if (address < PAGE_SIZE && !user_mode(regs))
534 pr_alert("BUG: kernel NULL pointer dereference, address: %px\n",
537 pr_alert("BUG: unable to handle page fault for address: %px\n",
540 pr_alert("#PF: %s %s in %s mode\n",
541 (error_code & X86_PF_USER) ? "user" : "supervisor",
542 (error_code & X86_PF_INSTR) ? "instruction fetch" :
543 (error_code & X86_PF_WRITE) ? "write access" :
545 user_mode(regs) ? "user" : "kernel");
546 pr_alert("#PF: error_code(0x%04lx) - %s\n", error_code,
547 !(error_code & X86_PF_PROT) ? "not-present page" :
548 (error_code & X86_PF_RSVD) ? "reserved bit violation" :
549 (error_code & X86_PF_PK) ? "protection keys violation" :
550 "permissions violation");
552 if (!(error_code & X86_PF_USER) && user_mode(regs)) {
553 struct desc_ptr idt, gdt;
557 * This can happen for quite a few reasons. The more obvious
558 * ones are faults accessing the GDT, or LDT. Perhaps
559 * surprisingly, if the CPU tries to deliver a benign or
560 * contributory exception from user code and gets a page fault
561 * during delivery, the page fault can be delivered as though
562 * it originated directly from user code. This could happen
563 * due to wrong permissions on the IDT, GDT, LDT, TSS, or
564 * kernel or IST stack.
568 /* Usable even on Xen PV -- it's just slow. */
569 native_store_gdt(&gdt);
571 pr_alert("IDT: 0x%lx (limit=0x%hx) GDT: 0x%lx (limit=0x%hx)\n",
572 idt.address, idt.size, gdt.address, gdt.size);
575 show_ldttss(&gdt, "LDTR", ldtr);
578 show_ldttss(&gdt, "TR", tr);
581 dump_pagetable(address);
585 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
586 unsigned long address)
588 struct task_struct *tsk;
592 flags = oops_begin();
596 printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
598 dump_pagetable(address);
600 if (__die("Bad pagetable", regs, error_code))
603 oops_end(flags, regs, sig);
606 static void sanitize_error_code(unsigned long address,
607 unsigned long *error_code)
610 * To avoid leaking information about the kernel page
611 * table layout, pretend that user-mode accesses to
612 * kernel addresses are always protection faults.
614 * NB: This means that failed vsyscalls with vsyscall=none
615 * will have the PROT bit. This doesn't leak any
616 * information and does not appear to cause any problems.
618 if (address >= TASK_SIZE_MAX)
619 *error_code |= X86_PF_PROT;
622 static void set_signal_archinfo(unsigned long address,
623 unsigned long error_code)
625 struct task_struct *tsk = current;
627 tsk->thread.trap_nr = X86_TRAP_PF;
628 tsk->thread.error_code = error_code | X86_PF_USER;
629 tsk->thread.cr2 = address;
633 no_context(struct pt_regs *regs, unsigned long error_code,
634 unsigned long address, int signal, int si_code)
636 struct task_struct *tsk = current;
640 if (user_mode(regs)) {
642 * This is an implicit supervisor-mode access from user
643 * mode. Bypass all the kernel-mode recovery code and just
649 /* Are we prepared to handle this kernel fault? */
650 if (fixup_exception(regs, X86_TRAP_PF, error_code, address)) {
652 * Any interrupt that takes a fault gets the fixup. This makes
653 * the below recursive fault logic only apply to a faults from
660 * Per the above we're !in_interrupt(), aka. task context.
662 * In this case we need to make sure we're not recursively
663 * faulting through the emulate_vsyscall() logic.
665 if (current->thread.sig_on_uaccess_err && signal) {
666 sanitize_error_code(address, &error_code);
668 set_signal_archinfo(address, error_code);
670 /* XXX: hwpoison faults will set the wrong code. */
671 force_sig_fault(signal, si_code, (void __user *)address);
675 * Barring that, we can do the fixup and be happy.
680 #ifdef CONFIG_VMAP_STACK
682 * Stack overflow? During boot, we can fault near the initial
683 * stack in the direct map, but that's not an overflow -- check
684 * that we're in vmalloc space to avoid this.
686 if (is_vmalloc_addr((void *)address) &&
687 (((unsigned long)tsk->stack - 1 - address < PAGE_SIZE) ||
688 address - ((unsigned long)tsk->stack + THREAD_SIZE) < PAGE_SIZE)) {
689 unsigned long stack = __this_cpu_ist_top_va(DF) - sizeof(void *);
691 * We're likely to be running with very little stack space
692 * left. It's plausible that we'd hit this condition but
693 * double-fault even before we get this far, in which case
694 * we're fine: the double-fault handler will deal with it.
696 * We don't want to make it all the way into the oops code
697 * and then double-fault, though, because we're likely to
698 * break the console driver and lose most of the stack dump.
700 asm volatile ("movq %[stack], %%rsp\n\t"
701 "call handle_stack_overflow\n\t"
703 : ASM_CALL_CONSTRAINT
704 : "D" ("kernel stack overflow (page fault)"),
705 "S" (regs), "d" (address),
706 [stack] "rm" (stack));
714 * Valid to do another page fault here, because if this fault
715 * had been triggered by is_prefetch fixup_exception would have
720 * Hall of shame of CPU/BIOS bugs.
722 if (is_prefetch(regs, error_code, address))
725 if (is_errata93(regs, address))
729 * Buggy firmware could access regions which might page fault, try to
730 * recover from such faults.
732 if (IS_ENABLED(CONFIG_EFI))
733 efi_recover_from_page_fault(address);
737 * Oops. The kernel tried to access some bad page. We'll have to
738 * terminate things with extreme prejudice:
740 flags = oops_begin();
742 show_fault_oops(regs, error_code, address);
744 if (task_stack_end_corrupted(tsk))
745 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
748 if (__die("Oops", regs, error_code))
751 /* Executive summary in case the body of the oops scrolled away */
752 printk(KERN_DEFAULT "CR2: %016lx\n", address);
754 oops_end(flags, regs, sig);
758 * Print out info about fatal segfaults, if the show_unhandled_signals
762 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
763 unsigned long address, struct task_struct *tsk)
765 const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;
767 if (!unhandled_signal(tsk, SIGSEGV))
770 if (!printk_ratelimit())
773 printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",
774 loglvl, tsk->comm, task_pid_nr(tsk), address,
775 (void *)regs->ip, (void *)regs->sp, error_code);
777 print_vma_addr(KERN_CONT " in ", regs->ip);
779 printk(KERN_CONT "\n");
781 show_opcodes(regs, loglvl);
785 * The (legacy) vsyscall page is the long page in the kernel portion
786 * of the address space that has user-accessible permissions.
788 static bool is_vsyscall_vaddr(unsigned long vaddr)
790 return unlikely((vaddr & PAGE_MASK) == VSYSCALL_ADDR);
794 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
795 unsigned long address, u32 pkey, int si_code)
797 struct task_struct *tsk = current;
799 /* User mode accesses just cause a SIGSEGV */
800 if (user_mode(regs) && (error_code & X86_PF_USER)) {
802 * It's possible to have interrupts off here:
807 * Valid to do another page fault here because this one came
810 if (is_prefetch(regs, error_code, address))
813 if (is_errata100(regs, address))
816 sanitize_error_code(address, &error_code);
818 if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
821 if (likely(show_unhandled_signals))
822 show_signal_msg(regs, error_code, address, tsk);
824 set_signal_archinfo(address, error_code);
826 if (si_code == SEGV_PKUERR)
827 force_sig_pkuerr((void __user *)address, pkey);
829 force_sig_fault(SIGSEGV, si_code, (void __user *)address);
836 if (is_f00f_bug(regs, address))
839 no_context(regs, error_code, address, SIGSEGV, si_code);
843 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
844 unsigned long address)
846 __bad_area_nosemaphore(regs, error_code, address, 0, SEGV_MAPERR);
850 __bad_area(struct pt_regs *regs, unsigned long error_code,
851 unsigned long address, u32 pkey, int si_code)
853 struct mm_struct *mm = current->mm;
855 * Something tried to access memory that isn't in our memory map..
856 * Fix it, but check if it's kernel or user first..
858 mmap_read_unlock(mm);
860 __bad_area_nosemaphore(regs, error_code, address, pkey, si_code);
864 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
866 __bad_area(regs, error_code, address, 0, SEGV_MAPERR);
869 static inline bool bad_area_access_from_pkeys(unsigned long error_code,
870 struct vm_area_struct *vma)
872 /* This code is always called on the current mm */
873 bool foreign = false;
875 if (!boot_cpu_has(X86_FEATURE_OSPKE))
877 if (error_code & X86_PF_PK)
879 /* this checks permission keys on the VMA: */
880 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
881 (error_code & X86_PF_INSTR), foreign))
887 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
888 unsigned long address, struct vm_area_struct *vma)
891 * This OSPKE check is not strictly necessary at runtime.
892 * But, doing it this way allows compiler optimizations
893 * if pkeys are compiled out.
895 if (bad_area_access_from_pkeys(error_code, vma)) {
897 * A protection key fault means that the PKRU value did not allow
898 * access to some PTE. Userspace can figure out what PKRU was
899 * from the XSAVE state. This function captures the pkey from
900 * the vma and passes it to userspace so userspace can discover
901 * which protection key was set on the PTE.
903 * If we get here, we know that the hardware signaled a X86_PF_PK
904 * fault and that there was a VMA once we got in the fault
905 * handler. It does *not* guarantee that the VMA we find here
906 * was the one that we faulted on.
908 * 1. T1 : mprotect_key(foo, PAGE_SIZE, pkey=4);
909 * 2. T1 : set PKRU to deny access to pkey=4, touches page
911 * 4. T2: mprotect_key(foo, PAGE_SIZE, pkey=5);
912 * 5. T1 : enters fault handler, takes mmap_lock, etc...
913 * 6. T1 : reaches here, sees vma_pkey(vma)=5, when we really
914 * faulted on a pte with its pkey=4.
916 u32 pkey = vma_pkey(vma);
918 __bad_area(regs, error_code, address, pkey, SEGV_PKUERR);
920 __bad_area(regs, error_code, address, 0, SEGV_ACCERR);
925 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
928 /* Kernel mode? Handle exceptions or die: */
929 if (!(error_code & X86_PF_USER)) {
930 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
934 /* User-space => ok to do another page fault: */
935 if (is_prefetch(regs, error_code, address))
938 sanitize_error_code(address, &error_code);
940 if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
943 set_signal_archinfo(address, error_code);
945 #ifdef CONFIG_MEMORY_FAILURE
946 if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
947 struct task_struct *tsk = current;
951 "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
952 tsk->comm, tsk->pid, address);
953 if (fault & VM_FAULT_HWPOISON_LARGE)
954 lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));
955 if (fault & VM_FAULT_HWPOISON)
957 force_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb);
961 force_sig_fault(SIGBUS, BUS_ADRERR, (void __user *)address);
965 mm_fault_error(struct pt_regs *regs, unsigned long error_code,
966 unsigned long address, vm_fault_t fault)
968 if (fatal_signal_pending(current) && !(error_code & X86_PF_USER)) {
969 no_context(regs, error_code, address, 0, 0);
973 if (fault & VM_FAULT_OOM) {
974 /* Kernel mode? Handle exceptions or die: */
975 if (!(error_code & X86_PF_USER)) {
976 no_context(regs, error_code, address,
977 SIGSEGV, SEGV_MAPERR);
982 * We ran out of memory, call the OOM killer, and return the
983 * userspace (which will retry the fault, or kill us if we got
986 pagefault_out_of_memory();
988 if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
989 VM_FAULT_HWPOISON_LARGE))
990 do_sigbus(regs, error_code, address, fault);
991 else if (fault & VM_FAULT_SIGSEGV)
992 bad_area_nosemaphore(regs, error_code, address);
998 static int spurious_kernel_fault_check(unsigned long error_code, pte_t *pte)
1000 if ((error_code & X86_PF_WRITE) && !pte_write(*pte))
1003 if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))
1010 * Handle a spurious fault caused by a stale TLB entry.
1012 * This allows us to lazily refresh the TLB when increasing the
1013 * permissions of a kernel page (RO -> RW or NX -> X). Doing it
1014 * eagerly is very expensive since that implies doing a full
1015 * cross-processor TLB flush, even if no stale TLB entries exist
1016 * on other processors.
1018 * Spurious faults may only occur if the TLB contains an entry with
1019 * fewer permission than the page table entry. Non-present (P = 0)
1020 * and reserved bit (R = 1) faults are never spurious.
1022 * There are no security implications to leaving a stale TLB when
1023 * increasing the permissions on a page.
1025 * Returns non-zero if a spurious fault was handled, zero otherwise.
1027 * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
1028 * (Optional Invalidation).
1031 spurious_kernel_fault(unsigned long error_code, unsigned long address)
1041 * Only writes to RO or instruction fetches from NX may cause
1044 * These could be from user or supervisor accesses but the TLB
1045 * is only lazily flushed after a kernel mapping protection
1046 * change, so user accesses are not expected to cause spurious
1049 if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&
1050 error_code != (X86_PF_INSTR | X86_PF_PROT))
1053 pgd = init_mm.pgd + pgd_index(address);
1054 if (!pgd_present(*pgd))
1057 p4d = p4d_offset(pgd, address);
1058 if (!p4d_present(*p4d))
1061 if (p4d_large(*p4d))
1062 return spurious_kernel_fault_check(error_code, (pte_t *) p4d);
1064 pud = pud_offset(p4d, address);
1065 if (!pud_present(*pud))
1068 if (pud_large(*pud))
1069 return spurious_kernel_fault_check(error_code, (pte_t *) pud);
1071 pmd = pmd_offset(pud, address);
1072 if (!pmd_present(*pmd))
1075 if (pmd_large(*pmd))
1076 return spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1078 pte = pte_offset_kernel(pmd, address);
1079 if (!pte_present(*pte))
1082 ret = spurious_kernel_fault_check(error_code, pte);
1087 * Make sure we have permissions in PMD.
1088 * If not, then there's a bug in the page tables:
1090 ret = spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1091 WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1095 NOKPROBE_SYMBOL(spurious_kernel_fault);
1097 int show_unhandled_signals = 1;
1100 access_error(unsigned long error_code, struct vm_area_struct *vma)
1102 /* This is only called for the current mm, so: */
1103 bool foreign = false;
1106 * Read or write was blocked by protection keys. This is
1107 * always an unconditional error and can never result in
1108 * a follow-up action to resolve the fault, like a COW.
1110 if (error_code & X86_PF_PK)
1114 * SGX hardware blocked the access. This usually happens
1115 * when the enclave memory contents have been destroyed, like
1116 * after a suspend/resume cycle. In any case, the kernel can't
1117 * fix the cause of the fault. Handle the fault as an access
1118 * error even in cases where no actual access violation
1119 * occurred. This allows userspace to rebuild the enclave in
1120 * response to the signal.
1122 if (unlikely(error_code & X86_PF_SGX))
1126 * Make sure to check the VMA so that we do not perform
1127 * faults just to hit a X86_PF_PK as soon as we fill in a
1130 if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
1131 (error_code & X86_PF_INSTR), foreign))
1134 if (error_code & X86_PF_WRITE) {
1135 /* write, present and write, not present: */
1136 if (unlikely(!(vma->vm_flags & VM_WRITE)))
1141 /* read, present: */
1142 if (unlikely(error_code & X86_PF_PROT))
1145 /* read, not present: */
1146 if (unlikely(!vma_is_accessible(vma)))
1152 bool fault_in_kernel_space(unsigned long address)
1155 * On 64-bit systems, the vsyscall page is at an address above
1156 * TASK_SIZE_MAX, but is not considered part of the kernel
1159 if (IS_ENABLED(CONFIG_X86_64) && is_vsyscall_vaddr(address))
1162 return address >= TASK_SIZE_MAX;
1166 * Called for all faults where 'address' is part of the kernel address
1167 * space. Might get called for faults that originate from *code* that
1168 * ran in userspace or the kernel.
1171 do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,
1172 unsigned long address)
1175 * Protection keys exceptions only happen on user pages. We
1176 * have no user pages in the kernel portion of the address
1177 * space, so do not expect them here.
1179 WARN_ON_ONCE(hw_error_code & X86_PF_PK);
1181 #ifdef CONFIG_X86_32
1183 * We can fault-in kernel-space virtual memory on-demand. The
1184 * 'reference' page table is init_mm.pgd.
1186 * NOTE! We MUST NOT take any locks for this case. We may
1187 * be in an interrupt or a critical region, and should
1188 * only copy the information from the master page table,
1191 * Before doing this on-demand faulting, ensure that the
1192 * fault is not any of the following:
1193 * 1. A fault on a PTE with a reserved bit set.
1194 * 2. A fault caused by a user-mode access. (Do not demand-
1195 * fault kernel memory due to user-mode accesses).
1196 * 3. A fault caused by a page-level protection violation.
1197 * (A demand fault would be on a non-present page which
1198 * would have X86_PF_PROT==0).
1200 * This is only needed to close a race condition on x86-32 in
1201 * the vmalloc mapping/unmapping code. See the comment above
1202 * vmalloc_fault() for details. On x86-64 the race does not
1203 * exist as the vmalloc mappings don't need to be synchronized
1206 if (!(hw_error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {
1207 if (vmalloc_fault(address) >= 0)
1212 /* Was the fault spurious, caused by lazy TLB invalidation? */
1213 if (spurious_kernel_fault(hw_error_code, address))
1216 /* kprobes don't want to hook the spurious faults: */
1217 if (kprobe_page_fault(regs, X86_TRAP_PF))
1221 * Note, despite being a "bad area", there are quite a few
1222 * acceptable reasons to get here, such as erratum fixups
1223 * and handling kernel code that can fault, like get_user().
1225 * Don't take the mm semaphore here. If we fixup a prefetch
1226 * fault we could otherwise deadlock:
1228 bad_area_nosemaphore(regs, hw_error_code, address);
1230 NOKPROBE_SYMBOL(do_kern_addr_fault);
1232 /* Handle faults in the user portion of the address space */
1234 void do_user_addr_fault(struct pt_regs *regs,
1235 unsigned long hw_error_code,
1236 unsigned long address)
1238 struct vm_area_struct *vma;
1239 struct task_struct *tsk;
1240 struct mm_struct *mm;
1242 unsigned int flags = FAULT_FLAG_DEFAULT;
1247 /* kprobes don't want to hook the spurious faults: */
1248 if (unlikely(kprobe_page_fault(regs, X86_TRAP_PF)))
1252 * Reserved bits are never expected to be set on
1253 * entries in the user portion of the page tables.
1255 if (unlikely(hw_error_code & X86_PF_RSVD))
1256 pgtable_bad(regs, hw_error_code, address);
1259 * If SMAP is on, check for invalid kernel (supervisor) access to user
1260 * pages in the user address space. The odd case here is WRUSS,
1261 * which, according to the preliminary documentation, does not respect
1262 * SMAP and will have the USER bit set so, in all cases, SMAP
1263 * enforcement appears to be consistent with the USER bit.
1265 if (unlikely(cpu_feature_enabled(X86_FEATURE_SMAP) &&
1266 !(hw_error_code & X86_PF_USER) &&
1267 !(regs->flags & X86_EFLAGS_AC)))
1269 bad_area_nosemaphore(regs, hw_error_code, address);
1274 * If we're in an interrupt, have no user context or are running
1275 * in a region with pagefaults disabled then we must not take the fault
1277 if (unlikely(faulthandler_disabled() || !mm)) {
1278 bad_area_nosemaphore(regs, hw_error_code, address);
1283 * It's safe to allow irq's after cr2 has been saved and the
1284 * vmalloc fault has been handled.
1286 * User-mode registers count as a user access even for any
1287 * potential system fault or CPU buglet:
1289 if (user_mode(regs)) {
1291 flags |= FAULT_FLAG_USER;
1293 if (regs->flags & X86_EFLAGS_IF)
1297 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1299 if (hw_error_code & X86_PF_WRITE)
1300 flags |= FAULT_FLAG_WRITE;
1301 if (hw_error_code & X86_PF_INSTR)
1302 flags |= FAULT_FLAG_INSTRUCTION;
1304 #ifdef CONFIG_X86_64
1306 * Faults in the vsyscall page might need emulation. The
1307 * vsyscall page is at a high address (>PAGE_OFFSET), but is
1308 * considered to be part of the user address space.
1310 * The vsyscall page does not have a "real" VMA, so do this
1311 * emulation before we go searching for VMAs.
1313 * PKRU never rejects instruction fetches, so we don't need
1314 * to consider the PF_PK bit.
1316 if (is_vsyscall_vaddr(address)) {
1317 if (emulate_vsyscall(hw_error_code, regs, address))
1323 * Kernel-mode access to the user address space should only occur
1324 * on well-defined single instructions listed in the exception
1325 * tables. But, an erroneous kernel fault occurring outside one of
1326 * those areas which also holds mmap_lock might deadlock attempting
1327 * to validate the fault against the address space.
1329 * Only do the expensive exception table search when we might be at
1330 * risk of a deadlock. This happens if we
1331 * 1. Failed to acquire mmap_lock, and
1332 * 2. The access did not originate in userspace.
1334 if (unlikely(!mmap_read_trylock(mm))) {
1335 if (!user_mode(regs) && !search_exception_tables(regs->ip)) {
1337 * Fault from code in kernel from
1338 * which we do not expect faults.
1340 bad_area_nosemaphore(regs, hw_error_code, address);
1347 * The above down_read_trylock() might have succeeded in
1348 * which case we'll have missed the might_sleep() from
1354 vma = find_vma(mm, address);
1355 if (unlikely(!vma)) {
1356 bad_area(regs, hw_error_code, address);
1359 if (likely(vma->vm_start <= address))
1361 if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1362 bad_area(regs, hw_error_code, address);
1365 if (unlikely(expand_stack(vma, address))) {
1366 bad_area(regs, hw_error_code, address);
1371 * Ok, we have a good vm_area for this memory access, so
1372 * we can handle it..
1375 if (unlikely(access_error(hw_error_code, vma))) {
1376 bad_area_access_error(regs, hw_error_code, address, vma);
1381 * If for any reason at all we couldn't handle the fault,
1382 * make sure we exit gracefully rather than endlessly redo
1383 * the fault. Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1384 * we get VM_FAULT_RETRY back, the mmap_lock has been unlocked.
1386 * Note that handle_userfault() may also release and reacquire mmap_lock
1387 * (and not return with VM_FAULT_RETRY), when returning to userland to
1388 * repeat the page fault later with a VM_FAULT_NOPAGE retval
1389 * (potentially after handling any pending signal during the return to
1390 * userland). The return to userland is identified whenever
1391 * FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.
1393 fault = handle_mm_fault(vma, address, flags, regs);
1395 /* Quick path to respond to signals */
1396 if (fault_signal_pending(fault, regs)) {
1397 if (!user_mode(regs))
1398 no_context(regs, hw_error_code, address, SIGBUS,
1404 * If we need to retry the mmap_lock has already been released,
1405 * and if there is a fatal signal pending there is no guarantee
1406 * that we made any progress. Handle this case first.
1408 if (unlikely((fault & VM_FAULT_RETRY) &&
1409 (flags & FAULT_FLAG_ALLOW_RETRY))) {
1410 flags |= FAULT_FLAG_TRIED;
1414 mmap_read_unlock(mm);
1415 if (unlikely(fault & VM_FAULT_ERROR)) {
1416 mm_fault_error(regs, hw_error_code, address, fault);
1420 check_v8086_mode(regs, address, tsk);
1422 NOKPROBE_SYMBOL(do_user_addr_fault);
1424 static __always_inline void
1425 trace_page_fault_entries(struct pt_regs *regs, unsigned long error_code,
1426 unsigned long address)
1428 if (!trace_pagefault_enabled())
1431 if (user_mode(regs))
1432 trace_page_fault_user(address, regs, error_code);
1434 trace_page_fault_kernel(address, regs, error_code);
1437 static __always_inline void
1438 handle_page_fault(struct pt_regs *regs, unsigned long error_code,
1439 unsigned long address)
1441 trace_page_fault_entries(regs, error_code, address);
1443 if (unlikely(kmmio_fault(regs, address)))
1446 /* Was the fault on kernel-controlled part of the address space? */
1447 if (unlikely(fault_in_kernel_space(address))) {
1448 do_kern_addr_fault(regs, error_code, address);
1450 do_user_addr_fault(regs, error_code, address);
1452 * User address page fault handling might have reenabled
1453 * interrupts. Fixing up all potential exit points of
1454 * do_user_addr_fault() and its leaf functions is just not
1455 * doable w/o creating an unholy mess or turning the code
1458 local_irq_disable();
1462 DEFINE_IDTENTRY_RAW_ERRORCODE(exc_page_fault)
1464 unsigned long address = read_cr2();
1465 irqentry_state_t state;
1467 prefetchw(¤t->mm->mmap_lock);
1470 * KVM uses #PF vector to deliver 'page not present' events to guests
1471 * (asynchronous page fault mechanism). The event happens when a
1472 * userspace task is trying to access some valid (from guest's point of
1473 * view) memory which is not currently mapped by the host (e.g. the
1474 * memory is swapped out). Note, the corresponding "page ready" event
1475 * which is injected when the memory becomes available, is delived via
1476 * an interrupt mechanism and not a #PF exception
1477 * (see arch/x86/kernel/kvm.c: sysvec_kvm_asyncpf_interrupt()).
1479 * We are relying on the interrupted context being sane (valid RSP,
1480 * relevant locks not held, etc.), which is fine as long as the
1481 * interrupted context had IF=1. We are also relying on the KVM
1482 * async pf type field and CR2 being read consistently instead of
1483 * getting values from real and async page faults mixed up.
1487 * The async #PF handling code takes care of idtentry handling
1490 if (kvm_handle_async_pf(regs, (u32)address))
1494 * Entry handling for valid #PF from kernel mode is slightly
1495 * different: RCU is already watching and rcu_irq_enter() must not
1496 * be invoked because a kernel fault on a user space address might
1499 * In case the fault hit a RCU idle region the conditional entry
1500 * code reenabled RCU to avoid subsequent wreckage which helps
1503 state = irqentry_enter(regs);
1505 instrumentation_begin();
1506 handle_page_fault(regs, error_code, address);
1507 instrumentation_end();
1509 irqentry_exit(regs, state);